TM: Don't allow passing NULL to tm_workspace API
[geany-mirror.git] / src / document.c
blobba9663ed4161908962ae3c4fcbc89c1bda0c0765
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 the same document pointer
88 * can represent a different document later on, or it may have been closed and become invalid.
89 * For this reason, you should use document_find_by_id() instead of storing
90 * document pointers over time if there is a chance the user can close the
91 * document.
93 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
94 * This is done automatically if you use the foreach_document() macro.
96 * @note
97 * Never assume that the order of document pointers is the same as the order of notebook tabs.
98 * One reason is that notebook tabs can be reordered.
99 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
101 * @see documents. */
102 GPtrArray *documents_array = NULL;
105 /* an undo action, also used for redo actions */
106 typedef struct
108 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
109 guint type; /* to identify the action */
110 gpointer *data; /* the old value (before the change), in case of a redo action
111 * it contains the new value */
112 } undo_action;
114 /* Custom document info bar response IDs */
115 enum
117 RESPONSE_DOCUMENT_RELOAD = 1,
118 RESPONSE_DOCUMENT_SAVE,
122 static guint doc_id_counter = 0;
125 static void document_undo_clear(GeanyDocument *doc);
126 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
127 static gboolean remove_page(guint page_num);
128 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
129 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
130 const gchar *btn_1, GtkResponseType response_1,
131 const gchar *btn_2, GtkResponseType response_2,
132 const gchar *btn_3, GtkResponseType response_3,
133 const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
137 * Finds a document whose @c real_path field matches the given filename.
139 * @param realname The filename to search, which should be identical to the
140 * string returned by @c tm_get_real_path().
142 * @return The matching document, or @c NULL.
143 * @note This is only really useful when passing a @c TMSourceFile::file_name.
144 * @see GeanyDocument::real_path.
145 * @see document_find_by_filename().
147 * @since 0.15
149 GeanyDocument* document_find_by_real_path(const gchar *realname)
151 guint i;
153 if (! realname)
154 return NULL; /* file doesn't exist on disk */
156 for (i = 0; i < documents_array->len; i++)
158 GeanyDocument *doc = documents[i];
160 if (! doc->is_valid || ! doc->real_path)
161 continue;
163 if (utils_filenamecmp(realname, doc->real_path) == 0)
165 return doc;
168 return NULL;
172 /* dereference symlinks, /../ junk in path and return locale encoding */
173 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
175 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
176 gchar *realname = tm_get_real_path(locale_name);
178 g_free(locale_name);
179 return realname;
184 * Finds a document with the given filename.
185 * This matches either an exact GeanyDocument::file_name string, or variant
186 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
187 * match @c "/name").
189 * @param utf8_filename The filename to search (in UTF-8 encoding).
191 * @return The matching document, or @c NULL.
192 * @see document_find_by_real_path().
194 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
196 guint i;
197 GeanyDocument *doc;
198 gchar *realname;
200 g_return_val_if_fail(utf8_filename != NULL, NULL);
202 /* First search GeanyDocument::file_name, so we can find documents with a
203 * filename set but not saved on disk, like vcdiff produces */
204 for (i = 0; i < documents_array->len; i++)
206 doc = documents[i];
208 if (! doc->is_valid || doc->file_name == NULL)
209 continue;
211 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
213 return doc;
216 /* Now try matching based on the realpath(), which is unique per file on disk */
217 realname = get_real_path_from_utf8(utf8_filename);
218 doc = document_find_by_real_path(realname);
219 g_free(realname);
220 return doc;
224 /* returns the document which has sci, or NULL. */
225 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
227 guint i;
229 g_return_val_if_fail(sci != NULL, NULL);
231 for (i = 0; i < documents_array->len; i++)
233 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
234 return documents[i];
236 return NULL;
240 /** Lookup an old document by its ID.
241 * Useful when the corresponding document may have been closed since the
242 * ID was retrieved.
243 * @param id The ID of the document to find
244 * @return @c NULL if the document is no longer open.
246 * Example:
247 * @code
248 * static guint id;
249 * GeanyDocument *doc = ...;
250 * id = doc->id; // store ID
251 * ...
252 * // time passes - the document may have been closed by now
253 * GeanyDocument *doc = document_find_by_id(id);
254 * gboolean still_open = (doc != NULL);
255 * @endcode
256 * @since 1.25. */
257 GeanyDocument *document_find_by_id(guint id)
259 guint i;
261 if (!id)
262 return NULL;
264 foreach_document(i)
266 if (documents[i]->id == id)
267 return documents[i];
269 return NULL;
273 /** Gets the notebook page index for a document.
274 * @param doc The document.
275 * @return The index.
276 * @since 0.19 */
277 gint document_get_notebook_page(GeanyDocument *doc)
279 GtkWidget *parent;
280 GtkWidget *child;
282 g_return_val_if_fail(doc != NULL, -1);
284 child = GTK_WIDGET(doc->editor->sci);
285 parent = gtk_widget_get_parent(child);
286 /* search for the direct notebook child, mirroring document_get_from_page() */
287 while (parent && ! GTK_IS_NOTEBOOK(parent))
289 child = parent;
290 parent = gtk_widget_get_parent(child);
293 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
298 * Recursively searches a containers children until it finds a
299 * Scintilla widget, or NULL if one was not found.
301 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
303 ScintillaObject *sci = NULL;
304 GList *children, *iter;
306 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
308 children = gtk_container_get_children(GTK_CONTAINER(container));
309 for (iter = children; iter != NULL; iter = g_list_next(iter))
311 if (IS_SCINTILLA(iter->data))
313 sci = SCINTILLA(iter->data);
314 break;
316 else if (GTK_IS_CONTAINER(iter->data))
318 sci = locate_sci_in_container(iter->data);
319 if (IS_SCINTILLA(sci))
320 break;
321 sci = NULL;
324 g_list_free(children);
326 return sci;
331 * Finds the document for the given notebook page @a page_num.
333 * @param page_num The notebook page number to search.
335 * @return The corresponding document for the given notebook page, or @c NULL.
337 GeanyDocument *document_get_from_page(guint page_num)
339 GtkWidget *parent;
340 ScintillaObject *sci;
342 if (page_num >= documents_array->len)
343 return NULL;
345 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
346 g_return_val_if_fail(GTK_IS_BOX(parent), NULL);
348 sci = locate_sci_in_container(parent);
349 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
351 return document_find_by_sci(sci);
356 * Finds the current document.
358 * @return A pointer to the current document or @c NULL if there are no opened documents.
360 GeanyDocument *document_get_current(void)
362 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
364 if (cur_page == -1)
365 return NULL;
366 else
367 return document_get_from_page((guint) cur_page);
371 void document_init_doclist(void)
373 documents_array = g_ptr_array_new();
377 void document_finalize(void)
379 guint i;
381 for (i = 0; i < documents_array->len; i++)
382 g_free(documents[i]);
383 g_ptr_array_free(documents_array, TRUE);
388 * Returns the last part of the filename of the given GeanyDocument. The result is also
389 * truncated to a maximum of @a length characters in case the filename is very long.
391 * @param doc The document to use.
392 * @param length The length of the resulting string or -1 to use a default value.
394 * @return The ellipsized last part of the filename of @a doc, should be freed when no
395 * longer needed.
397 * @since 0.17
399 /* TODO make more use of this */
400 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
402 gchar *base_name, *short_name;
404 g_return_val_if_fail(doc != NULL, NULL);
406 if (length < 0)
407 length = 30;
409 base_name = g_path_get_basename(DOC_FILENAME(doc));
410 short_name = utils_str_middle_truncate(base_name, (guint)length);
412 g_free(base_name);
414 return short_name;
418 void document_update_tab_label(GeanyDocument *doc)
420 gchar *short_name;
421 GtkWidget *parent;
423 g_return_if_fail(doc != NULL);
425 short_name = document_get_basename_for_display(doc, -1);
427 /* we need to use the event box for the tooltip, labels don't get the necessary events */
428 parent = gtk_widget_get_parent(doc->priv->tab_label);
429 parent = gtk_widget_get_parent(parent);
431 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
433 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
435 g_free(short_name);
440 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
441 * according to the document's save state.
442 * This is called by Geany mostly when opening or saving files.
444 * @param doc The document to use.
445 * @param changed Whether the document state should indicate changes have been made.
447 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
449 g_return_if_fail(doc != NULL);
451 doc->changed = changed;
453 if (! main_status.quitting)
455 ui_update_tab_status(doc);
456 ui_save_buttons_toggle(changed);
457 ui_set_window_title(doc);
458 ui_update_statusbar(doc, -1);
463 /* returns the next free place in the document list,
464 * or -1 if the documents_array is full */
465 static gint document_get_new_idx(void)
467 guint i;
469 for (i = 0; i < documents_array->len; i++)
471 if (documents[i]->editor == NULL)
473 return (gint) i;
476 return -1;
480 static void queue_colourise(GeanyDocument *doc)
482 /* Colourise the editor before it is next drawn */
483 doc->priv->colourise_needed = TRUE;
485 /* If the editor doesn't need drawing (e.g. after saving the current
486 * document), we need to force a redraw, so the expose event is triggered.
487 * This ensures we don't start colourising before all documents are opened/saved,
488 * only once the editor is drawn. */
489 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
493 #ifdef USE_GIO_FILEMON
494 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
495 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
496 GeanyDocument *doc)
498 g_return_if_fail(doc != NULL);
500 if (file_prefs.disk_check_timeout == 0)
501 return;
503 geany_debug("%s: event: %d previous file status: %d",
504 G_STRFUNC, event, doc->priv->file_disk_status);
505 switch (event)
507 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
509 if (doc->priv->file_disk_status == FILE_IGNORE)
510 doc->priv->file_disk_status = FILE_OK;
511 else
512 doc->priv->file_disk_status = FILE_CHANGED;
513 g_message("%s: FILE_CHANGED", G_STRFUNC);
514 break;
516 case G_FILE_MONITOR_EVENT_DELETED:
518 doc->priv->file_disk_status = FILE_CHANGED;
519 g_message("%s: FILE_MISSING", G_STRFUNC);
520 break;
522 default:
523 break;
525 if (doc->priv->file_disk_status != FILE_OK)
527 ui_update_tab_status(doc);
530 #endif
533 static void document_stop_file_monitoring(GeanyDocument *doc)
535 g_return_if_fail(doc != NULL);
537 if (doc->priv->monitor != NULL)
539 g_object_unref(doc->priv->monitor);
540 doc->priv->monitor = NULL;
545 static void monitor_file_setup(GeanyDocument *doc)
547 g_return_if_fail(doc != NULL);
548 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
549 * doesn't work at all for remote files and legacy polling is too slow. */
550 if (! doc->priv->is_remote)
552 #ifdef USE_GIO_FILEMON
553 gchar *locale_filename;
555 /* stop any previous monitoring */
556 document_stop_file_monitoring(doc);
558 locale_filename = utils_get_locale_from_utf8(doc->file_name);
559 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
561 /* get a file monitor and connect to the 'changed' signal */
562 GFile *file = g_file_new_for_path(locale_filename);
563 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
564 g_signal_connect(doc->priv->monitor, "changed",
565 G_CALLBACK(monitor_file_changed_cb), doc);
567 /* we set the rate limit according to the GUI pref but it's most probably not used */
568 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
570 g_object_unref(file);
572 g_free(locale_filename);
573 #endif
575 doc->priv->file_disk_status = FILE_OK;
579 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
581 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
582 if (DOC_VALID(doc))
584 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
585 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
587 if (source_widget == NULL)
588 source_widget = doc->priv->tag_tree;
590 if (focusw == source_widget)
591 gtk_widget_grab_focus(sci);
596 static gboolean on_idle_focus(gpointer doc)
598 document_try_focus(doc, NULL);
599 return FALSE;
603 /* Creates a new document and editor, adding a tab in the notebook.
604 * @return The created document */
605 static GeanyDocument *document_create(const gchar *utf8_filename)
607 GeanyDocument *doc;
608 gint new_idx;
609 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
611 if (cur_pages == 1)
613 doc = document_get_current();
614 /* remove the empty document first */
615 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
616 /* prevent immediately opening another new doc with
617 * new_document_after_close pref */
618 remove_page(0);
621 new_idx = document_get_new_idx();
622 if (new_idx == -1) /* expand the array, no free places */
624 doc = g_new0(GeanyDocument, 1);
626 new_idx = documents_array->len;
627 g_ptr_array_add(documents_array, doc);
630 doc = documents[new_idx];
632 /* initialize default document settings */
633 doc->priv = g_new0(GeanyDocumentPrivate, 1);
634 doc->id = ++doc_id_counter;
635 doc->index = new_idx;
636 doc->file_name = g_strdup(utf8_filename);
637 doc->editor = editor_create(doc);
638 #ifndef USE_GIO_FILEMON
639 doc->priv->last_check = time(NULL);
640 #endif
642 sidebar_openfiles_add(doc); /* sets doc->iter */
644 notebook_new_tab(doc);
646 /* select document in sidebar */
648 GtkTreeSelection *sel;
650 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
651 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
654 ui_document_buttons_update();
656 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
657 return doc;
662 * Closes the given document.
664 * @param doc The document to remove.
666 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
668 * @since 0.15
670 gboolean document_close(GeanyDocument *doc)
672 g_return_val_if_fail(doc, FALSE);
674 return document_remove_page(document_get_notebook_page(doc));
678 /* Call document_remove_page() instead, this is only needed for document_create()
679 * to prevent re-opening a new document when the last document is closed (if enabled). */
680 static gboolean remove_page(guint page_num)
682 GeanyDocument *doc = document_get_from_page(page_num);
684 g_return_val_if_fail(doc != NULL, FALSE);
686 if (doc->changed && ! dialogs_show_unsaved_file(doc))
687 return FALSE;
689 /* tell any plugins that the document is about to be closed */
690 g_signal_emit_by_name(geany_object, "document-close", doc);
692 /* Checking real_path makes it likely the file exists on disk */
693 if (! main_status.closing_all && doc->real_path != NULL)
694 ui_add_recent_document(doc);
696 doc->is_valid = FALSE;
697 doc->id = 0;
699 if (main_status.quitting)
701 /* we need to destroy the ScintillaWidget so our handlers on it are
702 * disconnected before we free any data they may use (like the editor).
703 * when not quitting, this is handled by removing the notebook page. */
704 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
706 else
708 notebook_remove_page(page_num);
709 sidebar_remove_document(doc);
710 navqueue_remove_file(doc->file_name);
711 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
713 g_free(doc->encoding);
714 g_free(doc->priv->saved_encoding.encoding);
715 g_free(doc->file_name);
716 g_free(doc->real_path);
717 if (doc->tm_file)
719 tm_workspace_remove_source_file(doc->tm_file);
720 tm_source_file_free(doc->tm_file);
723 if (doc->priv->tag_tree)
724 gtk_widget_destroy(doc->priv->tag_tree);
726 editor_destroy(doc->editor);
727 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
729 document_stop_file_monitoring(doc);
731 document_undo_clear(doc);
733 g_free(doc->priv);
735 /* reset document settings to defaults for re-use */
736 memset(doc, 0, sizeof(GeanyDocument));
738 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
740 sidebar_update_tag_list(NULL, FALSE);
741 ui_set_window_title(NULL);
742 ui_save_buttons_toggle(FALSE);
743 ui_update_popup_reundo_items(NULL);
744 ui_document_buttons_update();
745 build_menu_update(NULL);
747 return TRUE;
752 * Removes the given notebook tab at @a page_num and clears all related information
753 * in the document list.
755 * @param page_num The notebook page number to remove.
757 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
759 gboolean document_remove_page(guint page_num)
761 gboolean done = remove_page(page_num);
763 if (done && ui_prefs.new_document_after_close)
764 document_new_file_if_non_open();
766 return done;
770 /* used to keep a record of the unchanged document state encoding */
771 static void store_saved_encoding(GeanyDocument *doc)
773 g_free(doc->priv->saved_encoding.encoding);
774 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
775 doc->priv->saved_encoding.has_bom = doc->has_bom;
779 /* Opens a new empty document only if there are no other documents open */
780 GeanyDocument *document_new_file_if_non_open(void)
782 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
783 return document_new_file(NULL, NULL, NULL);
785 return NULL;
790 * Creates a new document.
791 * Line endings in @a text will be converted to the default setting.
792 * Afterwards, the @c "document-new" signal is emitted for plugins.
794 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
795 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
796 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
798 * @return The new document.
800 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
802 GeanyDocument *doc;
804 if (utf8_filename && g_path_is_absolute(utf8_filename))
806 gchar *tmp;
807 tmp = utils_strdupa(utf8_filename); /* work around const */
808 utils_tidy_path(tmp);
809 utf8_filename = tmp;
811 doc = document_create(utf8_filename);
813 g_assert(doc != NULL);
815 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
816 if (text)
818 GString *template = g_string_new(text);
819 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
821 sci_set_text(doc->editor->sci, template->str);
822 g_string_free(template, TRUE);
824 else
825 sci_clear_all(doc->editor->sci);
827 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
829 sci_set_undo_collection(doc->editor->sci, TRUE);
830 sci_empty_undo_buffer(doc->editor->sci);
832 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
833 /* store the opened encoding for undo/redo */
834 store_saved_encoding(doc);
836 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
837 ft = filetypes_detect_from_document(doc);
839 document_set_filetype(doc, ft); /* also re-parses tags */
841 ui_set_window_title(doc);
842 build_menu_update(doc);
843 document_set_text_changed(doc, FALSE);
844 ui_document_show_hide(doc); /* update the document menu */
846 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
847 /* bring it in front, jump to the start and grab the focus */
848 editor_goto_pos(doc->editor, 0, FALSE);
849 document_try_focus(doc, NULL);
851 #ifdef USE_GIO_FILEMON
852 monitor_file_setup(doc);
853 #else
854 doc->priv->mtime = time(NULL);
855 #endif
857 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
858 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
860 g_signal_emit_by_name(geany_object, "document-new", doc);
862 msgwin_status_add(_("New file \"%s\" opened."),
863 DOC_FILENAME(doc));
865 return doc;
870 * Opens a document specified by @a locale_filename.
871 * Afterwards, the @c "document-open" signal is emitted for plugins.
873 * @param locale_filename The filename of the document to load, in locale encoding.
874 * @param readonly Whether to open the document in read-only mode.
875 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
876 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
878 * @return The document opened or @c NULL.
880 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
881 GeanyFiletype *ft, const gchar *forced_enc)
883 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
887 typedef struct
889 gchar *data; /* null-terminated file data */
890 gsize len; /* string length of data */
891 gchar *enc;
892 gboolean bom;
893 time_t mtime; /* modification time, read by stat::st_mtime */
894 gboolean readonly;
895 } FileData;
898 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
899 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
900 FileData *filedata, const gchar *forced_enc)
902 GError *err = NULL;
903 struct stat st;
905 filedata->data = NULL;
906 filedata->len = 0;
907 filedata->enc = NULL;
908 filedata->bom = FALSE;
909 filedata->readonly = FALSE;
911 if (g_stat(locale_filename, &st) != 0)
913 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
914 display_filename, g_strerror(errno));
915 return FALSE;
918 filedata->mtime = st.st_mtime;
920 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
922 ui_set_statusbar(TRUE, "%s", err->message);
923 g_error_free(err);
924 return FALSE;
927 filedata->len = (gsize) st.st_size;
928 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
929 &filedata->enc, &filedata->bom, &filedata->readonly))
931 if (forced_enc)
933 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
934 display_filename, forced_enc);
936 else
938 ui_set_statusbar(TRUE,
939 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
940 display_filename);
942 g_free(filedata->data);
943 return FALSE;
946 if (filedata->readonly)
948 const gchar *warn_msg = _(
949 "The file \"%s\" could not be opened properly and has been truncated. " \
950 "This can occur if the file contains a NULL byte. " \
951 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
953 if (main_status.main_window_realized)
954 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
956 ui_set_statusbar(TRUE, warn_msg, display_filename);
959 return TRUE;
963 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
964 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
965 * if cl_options.goto_column is set.
967 * returns the new position which may have changed */
968 static gint set_cursor_position(GeanyEditor *editor, gint pos)
970 if (cl_options.goto_line >= 0)
971 { /* goto line which was specified on command line and then undefine the line */
972 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
973 editor->scroll_percent = 0.5F;
974 cl_options.goto_line = -1;
976 else if (pos > 0)
978 sci_set_current_position(editor->sci, pos, FALSE);
979 editor->scroll_percent = 0.5F;
982 if (cl_options.goto_column >= 0)
983 { /* goto column which was specified on command line and then undefine the column */
985 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
986 sci_set_current_position(editor->sci, new_pos, FALSE);
987 editor->scroll_percent = 0.5F;
988 cl_options.goto_column = -1;
989 return new_pos;
991 return sci_get_current_position(editor->sci);
995 /* Count lines that start with some hard tabs then a soft tab. */
996 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
998 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
999 ScintillaObject *sci = editor->sci;
1000 gsize count = 0;
1001 struct Sci_TextToFind ttf;
1002 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1003 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1005 g_free(soft_tab);
1007 ttf.chrg.cpMin = 0;
1008 ttf.chrg.cpMax = sci_get_length(sci);
1009 ttf.lpstrText = regex;
1010 while (1)
1012 gint pos;
1014 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1015 if (pos == -1)
1016 break; /* no more matches */
1017 count++;
1018 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1020 g_free(regex);
1021 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1022 return count > sci_get_line_count(sci) * 0.02;
1026 /* Detect the indent type based on counting the leading indent characters for each line.
1027 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1028 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1030 GeanyEditor *editor = doc->editor;
1031 ScintillaObject *sci = editor->sci;
1032 gint line, line_count;
1033 gsize tabs = 0, spaces = 0;
1035 if (detect_tabs_and_spaces(editor))
1037 *type_ = GEANY_INDENT_TYPE_BOTH;
1038 return TRUE;
1041 line_count = sci_get_line_count(sci);
1042 for (line = 0; line < line_count; line++)
1044 gint pos = sci_get_position_from_line(sci, line);
1045 gchar c;
1047 /* most code will have indent total <= 24, otherwise it's more likely to be
1048 * alignment than indentation */
1049 if (sci_get_line_indentation(sci, line) > 24)
1050 continue;
1052 c = sci_get_char_at(sci, pos);
1053 if (c == '\t')
1054 tabs++;
1055 /* check for at least 2 spaces */
1056 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1057 spaces++;
1059 if (spaces == 0 && tabs == 0)
1060 return FALSE;
1062 /* the factors may need to be tweaked */
1063 if (spaces > tabs * 4)
1064 *type_ = GEANY_INDENT_TYPE_SPACES;
1065 else if (tabs > spaces * 4)
1066 *type_ = GEANY_INDENT_TYPE_TABS;
1067 else
1068 *type_ = GEANY_INDENT_TYPE_BOTH;
1070 return TRUE;
1074 /* Detect the indent width based on counting the leading indent characters for each line.
1075 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1076 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1078 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1079 ScintillaObject *sci = editor->sci;
1080 gint line, line_count;
1081 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1082 gint count, width, i;
1084 /* can't easily detect the supposed width of a tab, guess the default is OK */
1085 if (type == GEANY_INDENT_TYPE_TABS)
1086 return FALSE;
1088 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1089 sci_set_tab_width(sci, 8);
1091 line_count = sci_get_line_count(sci);
1092 for (line = 0; line < line_count; line++)
1094 gint pos = sci_get_line_indent_position(sci, line);
1096 /* We probably don't have style info yet, because we're generally called just after
1097 * the document got created, so we can't use highlighting_is_code_style().
1098 * That's not good, but the assumption below that concerning lines start with an
1099 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1100 * without removing too much legitimate lines. */
1101 if (sci_get_char_at(sci, pos) == '*')
1102 continue;
1104 width = sci_get_line_indentation(sci, line);
1105 /* most code will have indent total <= 24, otherwise it's more likely to be
1106 * alignment than indentation */
1107 if (width > 24)
1108 continue;
1109 /* < 2 is no indentation */
1110 if (width < 2)
1111 continue;
1113 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1115 if ((width % (i + 2)) == 0)
1116 widths[i]++;
1119 count = 0;
1120 width = iprefs->width;
1121 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1123 /* give large indents higher weight not to be fooled by spurious indents */
1124 if (widths[i] >= count * 1.5)
1126 width = i + 2;
1127 count = widths[i];
1131 if (count == 0)
1132 return FALSE;
1134 *width_ = width;
1135 return TRUE;
1139 /* same as detect_indent_width() but uses editor's indent type */
1140 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1142 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1146 void document_apply_indent_settings(GeanyDocument *doc)
1148 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1149 GeanyIndentType type = iprefs->type;
1150 gint width = iprefs->width;
1152 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1154 if (type != iprefs->type)
1156 const gchar *name = NULL;
1158 switch (type)
1160 case GEANY_INDENT_TYPE_SPACES:
1161 name = _("Spaces");
1162 break;
1163 case GEANY_INDENT_TYPE_TABS:
1164 name = _("Tabs");
1165 break;
1166 case GEANY_INDENT_TYPE_BOTH:
1167 name = _("Tabs and Spaces");
1168 break;
1170 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1171 * and Spaces), the second one is the filename */
1172 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1173 DOC_FILENAME(doc));
1176 else if (doc->file_type->indent_type > -1)
1177 type = doc->file_type->indent_type;
1179 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1181 if (width != iprefs->width)
1183 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1184 DOC_FILENAME(doc));
1187 else if (doc->file_type->indent_width > -1)
1188 width = doc->file_type->indent_width;
1190 editor_set_indent(doc->editor, type, width);
1194 void document_show_tab(GeanyDocument *doc)
1196 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1197 document_get_notebook_page(doc));
1201 /* To open a new file, set doc to NULL; filename should be locale encoded.
1202 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1203 * pos is the cursor position, which can be overridden by --line and --column.
1204 * forced_enc can be NULL to detect the file encoding.
1205 * Returns: doc of the opened file or NULL if an error occurred. */
1206 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1207 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1209 gint editor_mode;
1210 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1211 gchar *utf8_filename = NULL;
1212 gchar *display_filename = NULL;
1213 gchar *locale_filename = NULL;
1214 GeanyFiletype *use_ft;
1215 FileData filedata;
1217 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1219 if (reload)
1221 utf8_filename = g_strdup(doc->file_name);
1222 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1224 else
1226 /* filename must not be NULL when opening a file */
1227 g_return_val_if_fail(filename, NULL);
1229 #ifdef G_OS_WIN32
1230 /* if filename is a shortcut, try to resolve it */
1231 locale_filename = win32_get_shortcut_target(filename);
1232 #else
1233 locale_filename = g_strdup(filename);
1234 #endif
1235 /* remove relative junk */
1236 utils_tidy_path(locale_filename);
1238 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1239 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1241 /* if file is already open, switch to it and go */
1242 doc = document_find_by_filename(utf8_filename);
1243 if (doc != NULL)
1245 ui_add_recent_document(doc); /* either add or reorder recent item */
1246 /* show the doc before reload dialog */
1247 document_show_tab(doc);
1248 document_check_disk_status(doc, TRUE); /* force a file changed check */
1251 if (reload || doc == NULL)
1252 { /* doc possibly changed */
1253 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1255 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1257 g_free(display_filename);
1258 g_free(utf8_filename);
1259 g_free(locale_filename);
1260 return NULL;
1263 if (! reload)
1265 doc = document_create(utf8_filename);
1266 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1268 /* file exists on disk, set real_path */
1269 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1271 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1272 monitor_file_setup(doc);
1275 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1276 sci_empty_undo_buffer(doc->editor->sci);
1278 /* add the text to the ScintillaObject */
1279 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1280 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1281 queue_colourise(doc); /* Ensure the document gets colourised. */
1283 /* detect & set line endings */
1284 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1285 sci_set_eol_mode(doc->editor->sci, editor_mode);
1286 g_free(filedata.data);
1288 sci_set_undo_collection(doc->editor->sci, TRUE);
1290 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1291 g_free(doc->encoding); /* if reloading, free old encoding */
1292 doc->encoding = filedata.enc;
1293 doc->has_bom = filedata.bom;
1294 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1296 doc->readonly = readonly || filedata.readonly;
1297 sci_set_readonly(doc->editor->sci, doc->readonly);
1298 doc->priv->protected = 0;
1300 /* update line number margin width */
1301 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1302 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1304 if (! reload)
1307 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1308 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1309 doc->editor);
1311 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1313 else
1314 { /* reloading */
1315 document_undo_clear(doc);
1317 use_ft = ft;
1319 /* update taglist, typedef keywords and build menu if necessary */
1320 document_set_filetype(doc, use_ft);
1322 /* set indentation settings after setting the filetype */
1323 if (reload)
1324 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1325 else
1326 document_apply_indent_settings(doc);
1328 document_set_text_changed(doc, FALSE); /* also updates tab state */
1329 ui_document_show_hide(doc); /* update the document menu */
1331 /* finally add current file to recent files menu, but not the files from the last session */
1332 if (! main_status.opening_session_files)
1333 ui_add_recent_document(doc);
1335 if (reload)
1337 g_signal_emit_by_name(geany_object, "document-reload", doc);
1338 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1340 else
1342 g_signal_emit_by_name(geany_object, "document-open", doc);
1343 /* For translators: this is the status window message for opening a file. %d is the number
1344 * of the newly opened file, %s indicates whether the file is opened read-only
1345 * (it is replaced with the string ", read-only"). */
1346 msgwin_status_add(_("File %s opened(%d%s)."),
1347 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1348 (readonly) ? _(", read-only") : "");
1352 g_free(display_filename);
1353 g_free(utf8_filename);
1354 g_free(locale_filename);
1356 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1357 pos = set_cursor_position(doc->editor, pos);
1358 /* now bring the file in front */
1359 editor_goto_pos(doc->editor, pos, FALSE);
1361 /* finally, let the editor widget grab the focus so you can start coding
1362 * right away */
1363 g_idle_add(on_idle_focus, doc);
1364 return doc;
1368 /* Takes a new line separated list of filename URIs and opens each file.
1369 * length is the length of the string */
1370 void document_open_file_list(const gchar *data, gsize length)
1372 guint i;
1373 gchar *filename;
1374 gchar **list;
1376 g_return_if_fail(data != NULL);
1378 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1380 /* stop at the end or first empty item, because last item is empty but not null */
1381 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1383 filename = utils_get_path_from_uri(list[i]);
1384 if (filename == NULL)
1385 continue;
1386 document_open_file(filename, FALSE, NULL, NULL);
1387 g_free(filename);
1390 g_strfreev(list);
1395 * Opens each file in the list @a filenames.
1396 * Internally, document_open_file() is called for every list item.
1398 * @param filenames A list of filenames to load, in locale encoding.
1399 * @param readonly Whether to open the document in read-only mode.
1400 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1401 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1403 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1404 const gchar *forced_enc)
1406 const GSList *item;
1408 for (item = filenames; item != NULL; item = g_slist_next(item))
1410 document_open_file(item->data, readonly, ft, forced_enc);
1416 * Reloads the document with the specified file encoding.
1417 * @a forced_enc or @c NULL to auto-detect the file encoding.
1419 * @param doc The document to reload.
1420 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1422 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1424 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1426 gint pos = 0;
1427 GeanyDocument *new_doc;
1429 g_return_val_if_fail(doc != NULL, FALSE);
1431 /* Use cancel because the response handler would call this recursively */
1432 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1433 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1435 /* try to set the cursor to the position before reloading */
1436 pos = sci_get_current_position(doc->editor->sci);
1437 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1439 return (new_doc != NULL);
1443 /* also used for reloading when forced_enc is NULL */
1444 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1446 gchar *base_name;
1447 gboolean prompt, result = FALSE;
1449 g_return_val_if_fail(doc != NULL, FALSE);
1451 /* No need to reload "untitled" (non-file-backed) documents */
1452 if (doc->file_name == NULL)
1453 return FALSE;
1455 if (forced_enc == NULL)
1456 forced_enc = doc->encoding;
1458 base_name = g_path_get_basename(doc->file_name);
1459 /* don't prompt if file hasn't been edited at all */
1460 prompt = doc->changed || (document_can_undo(doc) || document_can_redo(doc));
1462 if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1463 doc->changed ? _("Any unsaved changes will be lost.") :
1464 _("Undo history will be lost."),
1465 _("Are you sure you want to reload '%s'?"), base_name))
1467 result = document_reload_force(doc, forced_enc);
1468 if (forced_enc != NULL)
1469 ui_update_statusbar(doc, -1);
1471 g_free(base_name);
1472 return result;
1476 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1478 #ifndef USE_GIO_FILEMON
1479 struct stat st;
1481 g_return_val_if_fail(doc != NULL, FALSE);
1483 /* stat the file to get the timestamp, otherwise on Windows the actual
1484 * timestamp can be ahead of time(NULL) */
1485 if (g_stat(locale_filename, &st) != 0)
1487 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1488 g_strerror(errno));
1489 return FALSE;
1492 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1493 #endif
1494 return TRUE;
1498 /* Sets line and column to the given position byte_pos in the document.
1499 * byte_pos is the position counted in bytes, not characters */
1500 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1502 gint i;
1503 gint line_start;
1505 /* for some reason we can use byte count instead of character count here */
1506 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1507 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1508 /* get the column in the line */
1509 *column = byte_pos - line_start;
1511 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1512 * skip one byte(i++) and decrease the column number which is based on byte count */
1513 for (i = line_start; i < (line_start + *column); i++)
1515 if (sci_get_char_at(doc->editor->sci, i) < 0)
1517 (*column)--;
1518 i++;
1524 static void replace_header_filename(GeanyDocument *doc)
1526 gchar *filebase;
1527 gchar *filename;
1528 struct Sci_TextToFind ttf;
1530 g_return_if_fail(doc != NULL);
1531 g_return_if_fail(doc->file_type != NULL);
1533 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1534 if (doc->file_type->extension)
1535 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1536 else
1537 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1539 filename = g_path_get_basename(doc->file_name);
1541 /* only search the first 3 lines */
1542 ttf.chrg.cpMin = 0;
1543 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1544 ttf.lpstrText = filebase;
1546 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1548 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1549 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1550 sci_replace_target(doc->editor->sci, filename, FALSE);
1552 g_free(filebase);
1553 g_free(filename);
1558 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1559 * you still have to call @ref document_save_file_as() to change the @a doc object.
1560 * It also stops monitoring for file changes to prevent receiving too many file change events
1561 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1563 * @param doc The current document which should be renamed.
1564 * @param new_filename The new filename in UTF-8 encoding.
1566 * @since 0.16
1568 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1570 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1571 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1572 gint result;
1574 /* stop file monitoring to avoid getting events for deleting/creating files,
1575 * it's re-setup in document_save_file_as() */
1576 document_stop_file_monitoring(doc);
1578 result = g_rename(old_locale_filename, new_locale_filename);
1579 if (result != 0)
1581 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1582 _("Error renaming file."), g_strerror(errno));
1584 g_free(old_locale_filename);
1585 g_free(new_locale_filename);
1589 static void protect_document(GeanyDocument *doc)
1591 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1592 if (!doc->priv->protected++)
1593 sci_set_readonly(doc->editor->sci, TRUE);
1595 ui_update_tab_status(doc);
1599 static void unprotect_document(GeanyDocument *doc)
1601 g_return_if_fail(doc->priv->protected > 0);
1603 if (!--doc->priv->protected && doc->readonly == FALSE)
1604 sci_set_readonly(doc->editor->sci, FALSE);
1606 ui_update_tab_status(doc);
1610 /* Return TRUE if the document doesn't have a full filename set.
1611 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1612 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1613 * new files. */
1614 gboolean document_need_save_as(GeanyDocument *doc)
1616 g_return_val_if_fail(doc != NULL, FALSE);
1618 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1623 * Saves the document, detecting the filetype.
1625 * @param doc The document for the file to save.
1626 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1627 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1629 * @see document_save_file().
1631 * @since 0.16
1633 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1635 gboolean ret;
1636 gboolean new_file;
1638 g_return_val_if_fail(doc != NULL, FALSE);
1640 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1641 if (utf8_fname != NULL)
1642 SETPTR(doc->file_name, g_strdup(utf8_fname));
1644 /* reset real path, it's retrieved again in document_save() */
1645 SETPTR(doc->real_path, NULL);
1647 /* detect filetype */
1648 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1650 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1652 document_set_filetype(doc, ft);
1653 if (document_get_current() == doc)
1655 ignore_callback = TRUE;
1656 filetypes_select_radio_item(doc->file_type);
1657 ignore_callback = FALSE;
1661 if (new_file)
1663 // assume user wants to throw away read-only setting
1664 sci_set_readonly(doc->editor->sci, FALSE);
1665 doc->readonly = FALSE;
1666 if (doc->priv->protected > 0)
1667 unprotect_document(doc);
1670 replace_header_filename(doc);
1672 ret = document_save_file(doc, TRUE);
1674 /* file monitoring support, add file monitoring after the file has been saved
1675 * to ignore any earlier events */
1676 monitor_file_setup(doc);
1677 doc->priv->file_disk_status = FILE_IGNORE;
1679 if (ret)
1680 ui_add_recent_document(doc);
1681 return ret;
1685 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1687 GError *conv_error = NULL;
1688 gchar* conv_file_contents = NULL;
1689 gsize bytes_read;
1690 gsize conv_len;
1692 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1693 g_return_val_if_fail(len != NULL, FALSE);
1695 /* try to convert it from UTF-8 to original encoding */
1696 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1697 &bytes_read, &conv_len, &conv_error);
1699 if (conv_error != NULL)
1701 gchar *text = g_strdup_printf(
1702 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1703 doc->encoding);
1704 gchar *error_text;
1706 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1708 gint line, column;
1709 gint context_len;
1710 gunichar unic;
1711 /* don't read over the doc length */
1712 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1713 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1714 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1716 /* take only one valid Unicode character from the context and discard the leftover */
1717 unic = g_utf8_get_char_validated(context, -1);
1718 context_len = g_unichar_to_utf8(unic, context);
1719 context[context_len] = '\0';
1720 get_line_column_from_pos(doc, bytes_read, &line, &column);
1722 error_text = g_strdup_printf(
1723 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1724 conv_error->message, context, line + 1, column);
1726 else
1727 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1729 geany_debug("encoding error: %s", conv_error->message);
1730 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1731 g_error_free(conv_error);
1732 g_free(text);
1733 g_free(error_text);
1734 return FALSE;
1736 else
1738 g_free(*data);
1739 *data = conv_file_contents;
1740 *len = conv_len;
1742 return TRUE;
1746 static gchar *write_data_to_disk(const gchar *locale_filename,
1747 const gchar *data, gsize len)
1749 GError *error = NULL;
1751 if (file_prefs.use_safe_file_saving)
1753 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1754 * This is the only option that handles disk space exhaustion. */
1755 if (g_file_set_contents(locale_filename, data, len, &error))
1756 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1758 else if (file_prefs.use_gio_unsafe_file_saving)
1760 GFile *fp;
1762 /* Use GIO API to save file (GVFS-safe)
1763 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1764 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1765 fp = g_file_new_for_path(locale_filename);
1766 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1767 G_FILE_CREATE_NONE, NULL, NULL, &error);
1768 g_object_unref(fp);
1770 else
1772 FILE *fp;
1773 int save_errno;
1774 gchar *display_name = g_filename_display_name(locale_filename);
1776 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1777 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1778 errno = 0;
1779 fp = g_fopen(locale_filename, "wb");
1780 if (fp == NULL)
1782 save_errno = errno;
1784 g_set_error(&error,
1785 G_FILE_ERROR,
1786 g_file_error_from_errno(save_errno),
1787 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1788 display_name,
1789 g_strerror(save_errno));
1791 else
1793 gsize bytes_written;
1795 errno = 0;
1796 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1798 if (len != bytes_written)
1800 save_errno = errno;
1802 g_set_error(&error,
1803 G_FILE_ERROR,
1804 g_file_error_from_errno(save_errno),
1805 _("Failed to write file '%s': fwrite() failed: %s"),
1806 display_name,
1807 g_strerror(save_errno));
1810 errno = 0;
1811 /* preserve the fwrite() error if any */
1812 if (fclose(fp) != 0 && error == NULL)
1814 save_errno = errno;
1816 g_set_error(&error,
1817 G_FILE_ERROR,
1818 g_file_error_from_errno(save_errno),
1819 _("Failed to close file '%s': fclose() failed: %s"),
1820 display_name,
1821 g_strerror(save_errno));
1825 g_free(display_name);
1827 if (error != NULL)
1829 gchar *msg = g_strdup(error->message);
1830 g_error_free(error);
1831 /* geany will warn about file truncation for unsafe saving below */
1832 return msg;
1834 return NULL;
1838 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1839 const gchar *data, gsize len)
1841 gchar *err;
1843 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1844 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1846 err = write_data_to_disk(locale_filename, data, len);
1847 if (err)
1848 return err;
1850 /* now the file is on disk, set real_path */
1851 if (doc->real_path == NULL)
1853 doc->real_path = tm_get_real_path(locale_filename);
1854 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1855 monitor_file_setup(doc);
1857 return NULL;
1861 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
1863 GtkWidget *bar = NULL;
1865 document_show_tab(doc);
1867 if (doc->priv->info_bars[MSG_TYPE_RELOAD])
1869 if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
1870 _("Overwrite?"),
1871 _("The file '%s' on the disk is more recent than the current buffer."),
1872 doc->file_name))
1873 return FALSE;
1874 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
1876 else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
1878 if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
1879 _("Try to resave the file?"),
1880 _("File \"%s\" was not found on disk!"),
1881 doc->file_name))
1882 return FALSE;
1883 bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
1885 else
1887 g_assert_not_reached();
1888 return FALSE;
1890 gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
1891 return TRUE;
1896 * Saves the document.
1897 * Also shows the Save As dialog if necessary.
1898 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1900 * Saving may include replacing tabs with spaces,
1901 * stripping trailing spaces and adding a final new line at the end of the file, depending
1902 * on user preferences. Then the @c "document-before-save" signal is emitted,
1903 * allowing plugins to modify the document before it is saved, and data is
1904 * actually written to disk.
1906 * On successful saving:
1907 * - GeanyDocument::real_path is set.
1908 * - The filetype is set again or auto-detected if it wasn't set yet.
1909 * - The @c "document-save" signal is emitted for plugins.
1911 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1912 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1913 * added in Geany 1.22.
1915 * @param doc The document to save.
1916 * @param force Whether to save the file even if it is not modified.
1918 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1920 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1922 gchar *errmsg;
1923 gchar *data;
1924 gsize len;
1925 gchar *locale_filename;
1926 const GeanyFilePrefs *fp;
1928 g_return_val_if_fail(doc != NULL, FALSE);
1930 if (document_need_save_as(doc))
1932 /* ensure doc is the current tab before showing the dialog */
1933 document_show_tab(doc);
1934 return dialogs_show_save_as();
1937 if (!force && !doc->changed)
1938 return FALSE;
1939 if (doc->readonly)
1941 ui_set_statusbar(TRUE,
1942 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
1943 return FALSE;
1945 document_check_disk_status(doc, TRUE);
1946 if (doc->priv->protected)
1947 return save_file_handle_infobars(doc, force);
1949 fp = project_get_file_prefs();
1950 /* replaces tabs with spaces but only if the current file is not a Makefile */
1951 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1952 editor_replace_tabs(doc->editor);
1953 /* strip trailing spaces */
1954 if (fp->strip_trailing_spaces)
1955 editor_strip_trailing_spaces(doc->editor);
1956 /* ensure the file has a newline at the end */
1957 if (fp->final_new_line)
1958 editor_ensure_final_newline(doc->editor);
1959 /* ensure newlines are consistent */
1960 if (fp->ensure_convert_new_lines)
1961 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1963 /* notify plugins which may wish to modify the document before it's saved */
1964 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1966 len = sci_get_length(doc->editor->sci) + 1;
1967 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1968 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1969 * encoding, it will be converted to doc->encoding below and this conversion
1970 * also changes the BOM */
1971 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1972 data[0] = (gchar) 0xef;
1973 data[1] = (gchar) 0xbb;
1974 data[2] = (gchar) 0xbf;
1975 sci_get_text(doc->editor->sci, len, data + 3);
1976 len += 3;
1978 else
1980 data = (gchar*) g_malloc(len);
1981 sci_get_text(doc->editor->sci, len, data);
1984 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1985 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1986 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1988 if (! save_convert_to_encoding(doc, &data, &len))
1990 g_free(data);
1991 return FALSE;
1994 else
1996 len = strlen(data);
1999 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2001 /* ignore file changed notification when the file is written */
2002 doc->priv->file_disk_status = FILE_IGNORE;
2004 /* actually write the content of data to the file on disk */
2005 errmsg = save_doc(doc, locale_filename, data, len);
2006 g_free(data);
2008 if (errmsg != NULL)
2010 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2012 if (!file_prefs.use_safe_file_saving)
2014 SETPTR(errmsg,
2015 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2017 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2018 doc->priv->file_disk_status = FILE_OK;
2019 utils_beep();
2020 g_free(locale_filename);
2021 g_free(errmsg);
2022 return FALSE;
2025 /* store the opened encoding for undo/redo */
2026 store_saved_encoding(doc);
2028 /* ignore the following things if we are quitting */
2029 if (! main_status.quitting)
2031 sci_set_savepoint(doc->editor->sci);
2033 if (file_prefs.disk_check_timeout > 0)
2034 document_update_timestamp(doc, locale_filename);
2036 /* update filetype-related things */
2037 document_set_filetype(doc, doc->file_type);
2039 document_update_tab_label(doc);
2041 msgwin_status_add(_("File %s saved."), doc->file_name);
2042 ui_update_statusbar(doc, -1);
2043 #ifdef HAVE_VTE
2044 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2045 #endif
2047 g_free(locale_filename);
2049 g_signal_emit_by_name(geany_object, "document-save", doc);
2051 return TRUE;
2055 /* special search function, used from the find entry in the toolbar
2056 * return TRUE if text was found otherwise FALSE
2057 * return also TRUE if text is empty */
2058 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2059 gboolean backwards)
2061 gint start_pos, search_pos;
2062 struct Sci_TextToFind ttf;
2064 g_return_val_if_fail(text != NULL, FALSE);
2065 g_return_val_if_fail(doc != NULL, FALSE);
2066 if (! *text)
2067 return TRUE;
2069 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2070 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
2072 /* search cursor to end or start */
2073 ttf.chrg.cpMin = start_pos;
2074 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2075 ttf.lpstrText = (gchar *)text;
2076 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2078 /* if no match, search start (or end) to cursor */
2079 if (search_pos == -1)
2081 if (backwards)
2083 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2084 ttf.chrg.cpMax = start_pos;
2086 else
2088 ttf.chrg.cpMin = 0;
2089 ttf.chrg.cpMax = start_pos + strlen(text);
2091 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2094 if (search_pos != -1)
2096 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2098 /* unfold maybe folded results */
2099 sci_ensure_line_is_visible(doc->editor->sci, line);
2101 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2102 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2104 if (! editor_line_in_view(doc->editor, line))
2105 { /* we need to force scrolling in case the cursor is outside of the current visible area
2106 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2107 * while searching */
2108 editor_scroll_to_line(doc->editor, -1, 0.3F);
2110 else
2111 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2112 return TRUE;
2114 else
2116 if (! inc)
2118 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2120 utils_beep();
2121 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2122 return FALSE;
2127 /* General search function, used from the find dialog.
2128 * Returns -1 on failure or the start position of the matching text.
2129 * Will skip past any selection, ignoring it.
2131 * @param text Text to find.
2132 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2134 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2135 GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2136 gboolean scroll, GtkWidget *parent)
2138 gint selection_end, selection_start, search_pos;
2140 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2141 if (! *text)
2142 return -1;
2144 /* Sci doesn't support searching backwards with a regex */
2145 if (flags & GEANY_FIND_REGEXP)
2146 search_backwards = FALSE;
2148 if (!original_text)
2149 original_text = text;
2151 selection_start = sci_get_selection_start(doc->editor->sci);
2152 selection_end = sci_get_selection_end(doc->editor->sci);
2153 if ((selection_end - selection_start) > 0)
2154 { /* there's a selection so go to the end */
2155 if (search_backwards)
2156 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2157 else
2158 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2161 sci_set_search_anchor(doc->editor->sci);
2162 if (search_backwards)
2163 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2164 else
2165 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2167 if (search_pos != -1)
2169 /* unfold maybe folded results */
2170 sci_ensure_line_is_visible(doc->editor->sci,
2171 sci_get_line_from_position(doc->editor->sci, search_pos));
2172 if (scroll)
2173 doc->editor->scroll_percent = 0.3F;
2175 else
2177 gint sci_len = sci_get_length(doc->editor->sci);
2179 /* if we just searched the whole text, give up searching. */
2180 if ((selection_end == 0 && ! search_backwards) ||
2181 (selection_end == sci_len && search_backwards))
2183 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2184 utils_beep();
2185 return -1;
2188 /* we searched only part of the document, so ask whether to wraparound. */
2189 if (search_prefs.always_wrap ||
2190 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2191 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2193 gint ret;
2195 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2196 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2197 if (ret == -1)
2198 { /* return to original cursor position if not found */
2199 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2201 return ret;
2204 return search_pos;
2208 /* Replaces the selection if it matches, otherwise just finds the next match.
2209 * Returns: start of replaced text, or -1 if no replacement was made
2211 * @param find_text Text to find.
2212 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2214 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2215 const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2217 gint selection_end, selection_start, search_pos;
2218 GeanyMatchInfo *match = NULL;
2220 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2222 if (! *find_text)
2223 return -1;
2225 /* Sci doesn't support searching backwards with a regex */
2226 if (flags & GEANY_FIND_REGEXP)
2227 search_backwards = FALSE;
2229 if (!original_find_text)
2230 original_find_text = find_text;
2232 selection_start = sci_get_selection_start(doc->editor->sci);
2233 selection_end = sci_get_selection_end(doc->editor->sci);
2234 if (selection_end == selection_start)
2236 /* no selection so just find the next match */
2237 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2238 return -1;
2240 /* there's a selection so go to the start before finding to search through it
2241 * this ensures there is a match */
2242 if (search_backwards)
2243 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2244 else
2245 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2247 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2248 /* return if the original selected text did not match (at the start of the selection) */
2249 if (search_pos != selection_start)
2251 if (search_pos != -1)
2252 geany_match_info_free(match);
2253 return -1;
2256 if (search_pos != -1)
2258 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2259 /* select the replacement - find text will skip past the selected text */
2260 sci_set_selection_start(doc->editor->sci, search_pos);
2261 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2262 geany_match_info_free(match);
2264 else
2266 /* no match in the selection */
2267 utils_beep();
2269 return search_pos;
2273 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2274 const gchar *original_replace_text)
2276 gchar *filename;
2278 if (count == 0)
2280 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2281 return;
2284 filename = g_path_get_basename(DOC_FILENAME(doc));
2285 ui_set_statusbar(TRUE, ngettext(
2286 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2287 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2288 count), filename, count, original_find_text, original_replace_text);
2289 g_free(filename);
2293 /* Replace all text matches in a certain range within document.
2294 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2295 * or -1 if no text was found.
2296 * scroll_to_match is whether to scroll the last replacement in view (which also
2297 * clears the selection).
2298 * Returns: the number of replacements made. */
2299 static guint
2300 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2301 GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2303 gint count = 0;
2304 struct Sci_TextToFind ttf;
2305 ScintillaObject *sci;
2307 if (new_range_end != NULL)
2308 *new_range_end = -1;
2310 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2312 if (! *find_text || doc->readonly)
2313 return 0;
2315 sci = doc->editor->sci;
2317 ttf.chrg.cpMin = start;
2318 ttf.chrg.cpMax = end;
2319 ttf.lpstrText = (gchar*)find_text;
2321 sci_start_undo_action(sci);
2322 count = search_replace_range(sci, &ttf, flags, replace_text);
2323 sci_end_undo_action(sci);
2325 if (count > 0)
2326 { /* scroll last match in view, will destroy the existing selection */
2327 if (scroll_to_match)
2328 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2330 if (new_range_end != NULL)
2331 *new_range_end = ttf.chrg.cpMax;
2333 return count;
2337 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2338 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2340 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2341 gint max_column = 0, count = 0;
2342 gboolean replaced = FALSE;
2344 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2346 if (! *find_text)
2347 return;
2349 selection_start = sci_get_selection_start(doc->editor->sci);
2350 selection_end = sci_get_selection_end(doc->editor->sci);
2351 /* do we have a selection? */
2352 if ((selection_end - selection_start) == 0)
2354 utils_beep();
2355 return;
2358 selection_mode = sci_get_selection_mode(doc->editor->sci);
2359 selected_lines = sci_get_lines_selected(doc->editor->sci);
2360 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2361 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2363 gint first_line, line;
2365 sci_start_undo_action(doc->editor->sci);
2367 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2368 /* Find the last line with chars selected (not EOL char) */
2369 last_line = sci_get_line_from_position(doc->editor->sci,
2370 selection_end - editor_get_eol_char_len(doc->editor));
2371 last_line = MAX(first_line, last_line);
2372 for (line = first_line; line < (first_line + selected_lines); line++)
2374 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2375 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2377 /* skip line if there is no selection */
2378 if (line_start != INVALID_POSITION)
2380 /* don't let document_replace_range() scroll to match to keep our selection */
2381 gint new_sel_end;
2383 count += document_replace_range(doc, find_text, replace_text, flags,
2384 line_start, line_end, FALSE, &new_sel_end);
2385 if (new_sel_end != -1)
2387 replaced = TRUE;
2388 /* this gets the greatest column within the selection after replacing */
2389 max_column = MAX(max_column,
2390 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2394 sci_end_undo_action(doc->editor->sci);
2396 else /* handle normal line selection */
2398 count += document_replace_range(doc, find_text, replace_text, flags,
2399 selection_start, selection_end, TRUE, &selection_end);
2400 if (selection_end != -1)
2401 replaced = TRUE;
2404 if (replaced)
2405 { /* update the selection for the new endpoint */
2407 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2409 /* now we can scroll to the selection and destroy it because we rebuild it later */
2410 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2412 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2413 * the highest column on the last line. The wrapped selection is completely different
2414 * from the original one, so skip the selection at all */
2415 /* TODO is there a better way to handle the wrapped selection? */
2416 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2417 { /* for keeping and adjusting the selection in multi line rectangle selection we
2418 * need the last line of the original selection and the greatest column number after
2419 * replacing and set the selection end to the last line at the greatest column */
2420 sci_set_selection_start(doc->editor->sci, selection_start);
2421 sci_set_selection_end(doc->editor->sci,
2422 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2423 sci_set_selection_mode(doc->editor->sci, selection_mode);
2426 else
2428 sci_set_selection_start(doc->editor->sci, selection_start);
2429 sci_set_selection_end(doc->editor->sci, selection_end);
2432 else /* no replacements */
2433 utils_beep();
2435 show_replace_summary(doc, count, original_find_text, original_replace_text);
2439 /* returns number of replacements made. */
2440 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2441 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2443 gint len, count;
2444 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2446 if (! *find_text)
2447 return FALSE;
2449 len = sci_get_length(doc->editor->sci);
2450 count = document_replace_range(
2451 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2453 show_replace_summary(doc, count, original_find_text, original_replace_text);
2454 return count;
2459 * Parses or re-parses the document's buffer and updates the type
2460 * keywords and symbol list.
2462 * @param doc The document.
2464 void document_update_tags(GeanyDocument *doc)
2466 guchar *buffer_ptr;
2467 gsize len;
2469 g_return_if_fail(DOC_VALID(doc));
2470 g_return_if_fail(app->tm_workspace != NULL);
2472 /* early out if it's a new file or doesn't support tags */
2473 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2475 /* We must call sidebar_update_tag_list() before returning,
2476 * to ensure that the symbol list is always updated properly (e.g.
2477 * when creating a new document with a partial filename set. */
2478 sidebar_update_tag_list(doc, FALSE);
2479 return;
2482 /* create a new TM file if there isn't one yet */
2483 if (! doc->tm_file)
2485 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2486 const gchar *name;
2488 /* lookup the name rather than using filetype name to support custom filetypes */
2489 name = tm_source_file_get_lang_name(doc->file_type->lang);
2490 doc->tm_file = tm_source_file_new(locale_filename, name);
2491 g_free(locale_filename);
2493 if (doc->tm_file)
2494 tm_workspace_add_source_file_noupdate(doc->tm_file);
2497 /* early out if there's no tm source file and we couldn't create one */
2498 if (doc->tm_file == NULL)
2500 /* We must call sidebar_update_tag_list() before returning,
2501 * to ensure that the symbol list is always updated properly (e.g.
2502 * when creating a new document with a partial filename set. */
2503 sidebar_update_tag_list(doc, FALSE);
2504 return;
2507 /* Parse Scintilla's buffer directly using TagManager
2508 * Note: this buffer *MUST NOT* be modified */
2509 len = sci_get_length(doc->editor->sci);
2510 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2511 tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2513 sidebar_update_tag_list(doc, TRUE);
2514 document_highlight_tags(doc);
2518 /* Re-highlights type keywords without re-parsing the whole document. */
2519 void document_highlight_tags(GeanyDocument *doc)
2521 GString *keywords_str;
2522 gchar *keywords;
2523 gint keyword_idx;
2525 /* some filetypes support type keywords (such as struct names), but not
2526 * necessarily all filetypes for a particular scintilla lexer. this
2527 * tells us whether the filetype supports keywords, and if so
2528 * which index to use for the scintilla keywords set. */
2529 switch (doc->file_type->id)
2531 case GEANY_FILETYPES_C:
2532 case GEANY_FILETYPES_CPP:
2533 case GEANY_FILETYPES_CS:
2534 case GEANY_FILETYPES_D:
2535 case GEANY_FILETYPES_JAVA:
2536 case GEANY_FILETYPES_OBJECTIVEC:
2537 case GEANY_FILETYPES_VALA:
2538 case GEANY_FILETYPES_RUST:
2541 /* index of the keyword set in the Scintilla lexer, for
2542 * example in LexCPP.cxx, see "cppWordLists" global array.
2543 * TODO: this magic number should be a member of the filetype */
2544 keyword_idx = 3;
2545 break;
2547 default:
2548 return; /* early out if type keywords are not supported */
2550 if (!app->tm_workspace->tags_array)
2551 return;
2553 /* get any type keywords and tell scintilla about them
2554 * this will cause the type keywords to be colourized in scintilla */
2555 keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2556 if (keywords_str)
2558 keywords = g_string_free(keywords_str, FALSE);
2559 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2560 g_free(keywords);
2561 queue_colourise(doc); /* force re-highlighting the entire document */
2566 static gboolean on_document_update_tag_list_idle(gpointer data)
2568 GeanyDocument *doc = data;
2570 if (! DOC_VALID(doc))
2571 return FALSE;
2573 if (! main_status.quitting)
2574 document_update_tags(doc);
2576 doc->priv->tag_list_update_source = 0;
2578 /* don't update the tags until another modification of the buffer */
2579 return FALSE;
2583 void document_update_tag_list_in_idle(GeanyDocument *doc)
2585 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2586 return;
2588 /* prevent "stacking up" callback handlers, we only need one to run soon */
2589 if (doc->priv->tag_list_update_source != 0)
2590 g_source_remove(doc->priv->tag_list_update_source);
2592 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2593 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2597 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2598 gboolean filetype_changed)
2600 g_return_if_fail(doc);
2601 if (type == NULL)
2602 type = filetypes[GEANY_FILETYPES_NONE];
2604 if (filetype_changed)
2606 doc->file_type = type;
2608 /* delete tm file object to force creation of a new one */
2609 if (doc->tm_file != NULL)
2611 tm_workspace_remove_source_file(doc->tm_file);
2612 tm_source_file_free(doc->tm_file);
2613 doc->tm_file = NULL;
2615 /* load tags files before highlighting (some lexers highlight global typenames) */
2616 if (type->id != GEANY_FILETYPES_NONE)
2617 symbols_global_tags_loaded(type->id);
2619 highlighting_set_styles(doc->editor->sci, type);
2620 editor_set_indentation_guides(doc->editor);
2621 build_menu_update(doc);
2622 queue_colourise(doc);
2623 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2626 document_update_tags(doc);
2630 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2631 * @param doc The document to use.
2632 * @param type The filetype. */
2633 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2635 gboolean ft_changed;
2636 GeanyFiletype *old_ft;
2638 g_return_if_fail(doc);
2639 if (type == NULL)
2640 type = filetypes[GEANY_FILETYPES_NONE];
2642 old_ft = doc->file_type;
2643 geany_debug("%s : %s (%s)",
2644 (doc->file_name != NULL) ? doc->file_name : "unknown",
2645 type->name,
2646 (doc->encoding != NULL) ? doc->encoding : "unknown");
2648 ft_changed = (doc->file_type != type); /* filetype has changed */
2649 document_load_config(doc, type, ft_changed);
2651 if (ft_changed)
2653 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2655 /* assume that if previous filetype was none and the settings are the default ones, this
2656 * is the first time the filetype is carefully set, so we should apply indent settings */
2657 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2658 doc->editor->indent_type == iprefs->type &&
2659 doc->editor->indent_width == iprefs->width)
2661 document_apply_indent_settings(doc);
2662 ui_document_show_hide(doc);
2665 sidebar_openfiles_update(doc); /* to update the icon */
2666 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2671 void document_reload_config(GeanyDocument *doc)
2673 document_load_config(doc, doc->file_type, TRUE);
2678 * Sets the encoding of a document.
2679 * This function only set the encoding of the %document, it does not any conversions. The new
2680 * encoding is used when e.g. saving the file.
2682 * @param doc The document to use.
2683 * @param new_encoding The encoding to be set for the document.
2685 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2687 if (doc == NULL || new_encoding == NULL ||
2688 utils_str_equal(new_encoding, doc->encoding))
2689 return;
2691 g_free(doc->encoding);
2692 doc->encoding = g_strdup(new_encoding);
2694 ui_update_statusbar(doc, -1);
2695 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2696 encodings_is_unicode_charset(doc->encoding));
2700 /* own Undo / Redo implementation to be able to undo / redo changes
2701 * to the encoding or the Unicode BOM (which are Scintilla independet).
2702 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2704 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2705 void document_undo_clear(GeanyDocument *doc)
2707 undo_action *a;
2709 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2711 a = g_trash_stack_pop(&doc->priv->undo_actions);
2712 if (G_LIKELY(a != NULL))
2714 switch (a->type)
2716 case UNDO_ENCODING: g_free(a->data); break;
2717 default: break;
2719 g_free(a);
2722 doc->priv->undo_actions = NULL;
2724 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2726 a = g_trash_stack_pop(&doc->priv->redo_actions);
2727 if (G_LIKELY(a != NULL))
2729 switch (a->type)
2731 case UNDO_ENCODING: g_free(a->data); break;
2732 default: break;
2734 g_free(a);
2737 doc->priv->redo_actions = NULL;
2739 if (! main_status.quitting && doc->editor != NULL)
2740 document_set_text_changed(doc, FALSE);
2744 /* note: this is called on SCN_MODIFIED notifications */
2745 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2747 undo_action *action;
2749 g_return_if_fail(doc != NULL);
2751 action = g_new0(undo_action, 1);
2752 action->type = type;
2753 action->data = data;
2755 g_trash_stack_push(&doc->priv->undo_actions, action);
2757 /* avoid unnecessary redraws */
2758 if (type != UNDO_SCINTILLA || !doc->changed)
2759 document_set_text_changed(doc, TRUE);
2761 ui_update_popup_reundo_items(doc);
2765 gboolean document_can_undo(GeanyDocument *doc)
2767 g_return_val_if_fail(doc != NULL, FALSE);
2769 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2770 return TRUE;
2771 else
2772 return FALSE;
2776 static void update_changed_state(GeanyDocument *doc)
2778 doc->changed =
2779 (sci_is_modified(doc->editor->sci) ||
2780 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2781 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2782 document_set_text_changed(doc, doc->changed);
2786 void document_undo(GeanyDocument *doc)
2788 undo_action *action;
2790 g_return_if_fail(doc != NULL);
2792 action = g_trash_stack_pop(&doc->priv->undo_actions);
2794 if (G_UNLIKELY(action == NULL))
2796 /* fallback, should not be necessary */
2797 geany_debug("%s: fallback used", G_STRFUNC);
2798 sci_undo(doc->editor->sci);
2800 else
2802 switch (action->type)
2804 case UNDO_SCINTILLA:
2806 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2808 sci_undo(doc->editor->sci);
2809 break;
2811 case UNDO_BOM:
2813 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2815 doc->has_bom = GPOINTER_TO_INT(action->data);
2816 ui_update_statusbar(doc, -1);
2817 ui_document_show_hide(doc);
2818 break;
2820 case UNDO_ENCODING:
2822 /* use the "old" encoding */
2823 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2825 document_set_encoding(doc, (const gchar*)action->data);
2827 ignore_callback = TRUE;
2828 encodings_select_radio_item((const gchar*)action->data);
2829 ignore_callback = FALSE;
2831 g_free(action->data);
2832 break;
2834 default: break;
2837 g_free(action); /* free the action which was taken from the stack */
2839 update_changed_state(doc);
2840 ui_update_popup_reundo_items(doc);
2844 gboolean document_can_redo(GeanyDocument *doc)
2846 g_return_val_if_fail(doc != NULL, FALSE);
2848 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2849 return TRUE;
2850 else
2851 return FALSE;
2855 void document_redo(GeanyDocument *doc)
2857 undo_action *action;
2859 g_return_if_fail(doc != NULL);
2861 action = g_trash_stack_pop(&doc->priv->redo_actions);
2863 if (G_UNLIKELY(action == NULL))
2865 /* fallback, should not be necessary */
2866 geany_debug("%s: fallback used", G_STRFUNC);
2867 sci_redo(doc->editor->sci);
2869 else
2871 switch (action->type)
2873 case UNDO_SCINTILLA:
2875 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2877 sci_redo(doc->editor->sci);
2878 break;
2880 case UNDO_BOM:
2882 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2884 doc->has_bom = GPOINTER_TO_INT(action->data);
2885 ui_update_statusbar(doc, -1);
2886 ui_document_show_hide(doc);
2887 break;
2889 case UNDO_ENCODING:
2891 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2893 document_set_encoding(doc, (const gchar*)action->data);
2895 ignore_callback = TRUE;
2896 encodings_select_radio_item((const gchar*)action->data);
2897 ignore_callback = FALSE;
2899 g_free(action->data);
2900 break;
2902 default: break;
2905 g_free(action); /* free the action which was taken from the stack */
2907 update_changed_state(doc);
2908 ui_update_popup_reundo_items(doc);
2912 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2914 undo_action *action;
2916 g_return_if_fail(doc != NULL);
2918 action = g_new0(undo_action, 1);
2919 action->type = type;
2920 action->data = data;
2922 g_trash_stack_push(&doc->priv->redo_actions, action);
2924 if (type != UNDO_SCINTILLA || !doc->changed)
2925 document_set_text_changed(doc, TRUE);
2927 ui_update_popup_reundo_items(doc);
2931 enum
2933 STATUS_CHANGED,
2934 STATUS_DISK_CHANGED,
2935 STATUS_READONLY
2938 static struct
2940 const gchar *name;
2941 GdkColor color;
2942 gboolean loaded;
2943 } document_status_styles[] = {
2944 { "geany-document-status-changed", {0}, FALSE },
2945 { "geany-document-status-disk-changed", {0}, FALSE },
2946 { "geany-document-status-readonly", {0}, FALSE }
2950 static gint document_get_status_id(GeanyDocument *doc)
2952 if (doc->changed)
2953 return STATUS_CHANGED;
2954 #ifdef USE_GIO_FILEMON
2955 else if (doc->priv->file_disk_status == FILE_CHANGED)
2956 #else
2957 else if (doc->priv->protected)
2958 #endif
2959 return STATUS_DISK_CHANGED;
2960 else if (doc->readonly)
2961 return STATUS_READONLY;
2963 return -1;
2967 /* returns an identifier that is to be set as a widget name or class to get it styled
2968 * depending on the document status (changed, readonly, etc.)
2969 * a NULL return value means default (unchanged) style */
2970 const gchar *document_get_status_widget_class(GeanyDocument *doc)
2972 gint status;
2974 g_return_val_if_fail(doc != NULL, NULL);
2976 status = document_get_status_id(doc);
2977 if (status < 0)
2978 return NULL;
2979 else
2980 return document_status_styles[status].name;
2985 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2986 * Returned colors are red if the document has changes, green if the document is read-only
2987 * or simply @c NULL if the document is unmodified but writable.
2989 * @param doc The document to use.
2991 * @return The color for the document or @c NULL if the default color should be used. The color
2992 * object is owned by Geany and should not be modified or freed.
2994 * @since 0.16
2996 const GdkColor *document_get_status_color(GeanyDocument *doc)
2998 gint status;
3000 g_return_val_if_fail(doc != NULL, NULL);
3002 status = document_get_status_id(doc);
3003 if (status < 0)
3004 return NULL;
3005 if (! document_status_styles[status].loaded)
3007 #if GTK_CHECK_VERSION(3, 0, 0)
3008 GdkRGBA color;
3009 GtkWidgetPath *path = gtk_widget_path_new();
3010 GtkStyleContext *ctx = gtk_style_context_new();
3011 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3012 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3013 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3014 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3015 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3016 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3017 gtk_style_context_set_path(ctx, path);
3018 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
3019 document_status_styles[status].color.red = 0xffff * color.red;
3020 document_status_styles[status].color.green = 0xffff * color.green;
3021 document_status_styles[status].color.blue = 0xffff * color.blue;
3022 document_status_styles[status].loaded = TRUE;
3023 gtk_widget_path_unref(path);
3024 g_object_unref(ctx);
3025 #else
3026 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3027 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3028 document_status_styles[status].name, NULL);
3029 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3031 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3032 document_status_styles[status].loaded = TRUE;
3033 g_free(path);
3034 #endif
3036 return &document_status_styles[status].color;
3040 /** Accessor function for @ref documents_array items.
3041 * @warning Always check the returned document is valid (@c doc->is_valid).
3042 * @param idx @c documents_array index.
3043 * @return The document, or @c NULL if @a idx is out of range.
3045 * @since 0.16
3047 GeanyDocument *document_index(gint idx)
3049 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3053 GeanyDocument *document_clone(GeanyDocument *old_doc)
3055 gchar *text;
3056 GeanyDocument *doc;
3057 ScintillaObject *old_sci;
3059 g_return_val_if_fail(old_doc, NULL);
3060 old_sci = old_doc->editor->sci;
3061 if (sci_has_selection(old_sci))
3062 text = sci_get_selection_contents(old_sci);
3063 else
3064 text = sci_get_contents(old_sci, -1);
3066 doc = document_new_file(NULL, old_doc->file_type, text);
3067 g_free(text);
3068 document_set_text_changed(doc, TRUE);
3070 /* copy file properties */
3071 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3072 doc->editor->line_breaking = old_doc->editor->line_breaking;
3073 doc->editor->auto_indent = old_doc->editor->auto_indent;
3074 editor_set_indent(doc->editor, old_doc->editor->indent_type,
3075 old_doc->editor->indent_width);
3076 doc->readonly = old_doc->readonly;
3077 doc->has_bom = old_doc->has_bom;
3078 doc->priv->protected = 0;
3079 document_set_encoding(doc, old_doc->encoding);
3080 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3081 sci_set_readonly(doc->editor->sci, doc->readonly);
3083 /* update ui */
3084 ui_document_show_hide(doc);
3085 return doc;
3089 /* @note If successful, this should always be followed up with a call to
3090 * document_close_all().
3091 * @return TRUE if all files were saved or had their changes discarded. */
3092 gboolean document_account_for_unsaved(void)
3094 guint i, p, page_count;
3096 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3097 /* iterate over documents in tabs order */
3098 for (p = 0; p < page_count; p++)
3100 GeanyDocument *doc = document_get_from_page(p);
3102 if (DOC_VALID(doc) && doc->changed)
3104 if (! dialogs_show_unsaved_file(doc))
3105 return FALSE;
3108 /* all documents should now be accounted for, so ignore any changes */
3109 foreach_document (i)
3111 documents[i]->changed = FALSE;
3113 return TRUE;
3117 static void force_close_all(void)
3119 guint i, len = documents_array->len;
3121 /* check all documents have been accounted for */
3122 for (i = 0; i < len; i++)
3124 if (documents[i]->is_valid)
3126 g_return_if_fail(!documents[i]->changed);
3129 main_status.closing_all = TRUE;
3131 foreach_document(i)
3133 document_close(documents[i]);
3136 main_status.closing_all = FALSE;
3140 gboolean document_close_all(void)
3142 if (! document_account_for_unsaved())
3143 return FALSE;
3145 force_close_all();
3147 return TRUE;
3151 /* *
3152 * Shows a message related to a document.
3154 * Use this whenever the user needs to see a document-related message,
3155 * for example when the file was externally modified or deleted.
3157 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3158 * @a response_1 response will be the default for the @c GtkInfoBar or
3159 * @c GtkDialog.
3161 * @param doc @c GeanyDocument.
3162 * @param msgtype The type of message.
3163 * @param response_cb A callback function called when there's a response.
3164 * @param btn_1 The first action area button.
3165 * @param response_1 The response for @a btn_1.
3166 * @param btn_2 The second action area button.
3167 * @param response_2 The response for @a btn_2.
3168 * @param btn_3 The third action area button.
3169 * @param response_3 The response for @a btn_3.
3170 * @param extra_text Text to show below the main message.
3171 * @param format The text format for the main message.
3172 * @param ... Used with @a format as in @c printf.
3174 * @since 1.25
3175 * */
3176 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3177 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3178 const gchar *btn_1, GtkResponseType response_1,
3179 const gchar *btn_2, GtkResponseType response_2,
3180 const gchar *btn_3, GtkResponseType response_3,
3181 const gchar *extra_text, const gchar *format, ...)
3183 va_list args;
3184 gchar *text, *markup;
3185 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3186 GtkWidget *info_widget, *parent;
3187 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook),
3188 document_get_notebook_page(doc));
3190 va_start(args, format);
3191 text = g_strdup_vprintf(format, args);
3192 va_end(args);
3194 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3195 g_free(text);
3197 info_widget = gtk_info_bar_new();
3198 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3199 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3201 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3203 if (btn_1)
3204 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3205 if (btn_2)
3206 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3207 if (btn_3)
3208 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3210 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3212 label = geany_wrap_label_new(NULL);
3213 gtk_label_set_markup(GTK_LABEL(label), markup);
3214 g_free(markup);
3216 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3218 hbox = gtk_hbox_new(FALSE, 12);
3219 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3221 switch (msgtype)
3223 case GTK_MESSAGE_INFO:
3224 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3225 break;
3226 case GTK_MESSAGE_WARNING:
3227 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3228 break;
3229 case GTK_MESSAGE_QUESTION:
3230 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3231 break;
3232 case GTK_MESSAGE_ERROR:
3233 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3234 break;
3235 default:
3236 icon = NULL;
3237 break;
3240 if (icon)
3241 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3243 if (extra_text)
3245 vbox = gtk_vbox_new(FALSE, 6);
3246 extra_label = geany_wrap_label_new(extra_text);
3247 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3248 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3249 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3251 else
3252 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3254 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3256 gtk_widget_show_all(info_widget);
3258 return info_widget;
3262 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3264 gboolean close = FALSE;
3266 // disable info bar so actions complete normally
3267 unprotect_document(doc);
3268 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3270 if (response_id == RESPONSE_DOCUMENT_RELOAD)
3272 close = doc->changed ?
3273 document_reload_prompt(doc, doc->encoding) :
3274 document_reload_force(doc, doc->encoding);
3276 else if (response_id == RESPONSE_DOCUMENT_SAVE)
3278 close = document_save_file(doc, TRUE); // force overwrite
3280 else if (response_id == GTK_RESPONSE_CANCEL)
3282 document_set_text_changed(doc, TRUE);
3283 close = TRUE;
3285 if (!close)
3287 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3288 protect_document(doc);
3289 return;
3291 gtk_widget_destroy(bar);
3295 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3297 GtkInfoBar *bar = GTK_INFO_BAR(data);
3299 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3301 switch (event->keyval)
3303 case GDK_Tab:
3304 case GDK_ISO_Left_Tab:
3306 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3307 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3308 gtk_widget_child_focus(action_area, dir);
3309 return TRUE;
3311 case GDK_Escape:
3313 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3314 return TRUE;
3316 default:
3317 return FALSE;
3322 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3323 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3325 /* automatically focus editor again on bar close */
3326 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3327 G_CONNECT_SWAPPED);
3328 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3332 static void monitor_reload_file(GeanyDocument *doc)
3334 gchar *base_name = g_path_get_basename(doc->file_name);
3336 /* show this message only once */
3337 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3339 GtkWidget *bar;
3341 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3342 _("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3343 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3344 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3345 _("Do you want to reload it?"),
3346 _("The file '%s' on the disk is more recent than the current buffer."),
3347 base_name);
3349 protect_document(doc);
3350 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3351 enable_key_intercept(doc, bar);
3353 g_free(base_name);
3357 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3358 gint response_id,
3359 GeanyDocument *doc)
3361 unprotect_document(doc);
3363 if (response_id == RESPONSE_DOCUMENT_SAVE)
3364 dialogs_show_save_as();
3366 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3370 static void monitor_resave_missing_file(GeanyDocument *doc)
3372 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3374 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3376 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3377 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3379 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3380 on_monitor_resave_missing_file_response,
3381 GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3382 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3383 NULL, GTK_RESPONSE_NONE,
3384 _("Try to resave the file?"),
3385 _("File \"%s\" was not found on disk!"),
3386 doc->file_name);
3388 protect_document(doc);
3389 document_set_text_changed(doc, TRUE);
3390 /* don't prompt more than once */
3391 SETPTR(doc->real_path, NULL);
3392 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3393 enable_key_intercept(doc, bar);
3398 /* Set force to force a disk check, otherwise it is ignored if there was a check
3399 * in the last file_prefs.disk_check_timeout seconds.
3400 * @return @c TRUE if the file has changed. */
3401 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3403 gboolean ret = FALSE;
3404 gboolean use_gio_filemon;
3405 time_t cur_time = 0;
3406 struct stat st;
3407 gchar *locale_filename;
3408 FileDiskStatus old_status;
3410 g_return_val_if_fail(doc != NULL, FALSE);
3412 /* ignore remote files and documents that have never been saved to disk */
3413 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3414 || doc->real_path == NULL || doc->priv->is_remote)
3415 return FALSE;
3417 use_gio_filemon = (doc->priv->monitor != NULL);
3419 if (use_gio_filemon)
3421 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3422 return FALSE;
3424 else
3426 cur_time = time(NULL);
3427 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3428 return FALSE;
3430 doc->priv->last_check = cur_time;
3433 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3434 if (g_stat(locale_filename, &st) != 0)
3436 monitor_resave_missing_file(doc);
3437 /* doc may be closed now */
3438 ret = TRUE;
3440 else if (! use_gio_filemon && /* ignore check when using GIO */
3441 doc->priv->mtime > cur_time)
3443 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3444 /* Note: on Windows st.st_mtime can be newer than cur_time */
3446 else if (doc->priv->mtime < st.st_mtime)
3448 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3449 doc->priv->mtime = st.st_mtime;
3450 monitor_reload_file(doc);
3451 /* doc may be closed now */
3452 ret = TRUE;
3454 g_free(locale_filename);
3456 if (DOC_VALID(doc))
3457 { /* doc can get invalid when a document was closed */
3458 old_status = doc->priv->file_disk_status;
3459 doc->priv->file_disk_status = FILE_OK;
3460 if (old_status != doc->priv->file_disk_status)
3461 ui_update_tab_status(doc);
3463 return ret;
3467 /** Compares documents by their display names.
3468 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3469 * @note 'Display name' means the base name of the document's filename.
3471 * @param a @c GeanyDocument**.
3472 * @param b @c GeanyDocument**.
3473 * @warning The arguments take the address of each document pointer.
3474 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3476 * @since 0.21
3478 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3480 GeanyDocument *doc_a = *((GeanyDocument**) a);
3481 GeanyDocument *doc_b = *((GeanyDocument**) b);
3482 gchar *base_name_a, *base_name_b;
3483 gint result;
3485 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3486 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3488 result = strcmp(base_name_a, base_name_b);
3490 g_free(base_name_a);
3491 g_free(base_name_b);
3493 return result;
3497 /** Compares documents by their tab order.
3498 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3500 * @param a @c GeanyDocument**.
3501 * @param b @c GeanyDocument**.
3502 * @warning The arguments take the address of each document pointer.
3503 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3505 * @since 0.21 (GEANY_API_VERSION 209)
3507 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3509 GeanyDocument *doc_a = *((GeanyDocument**) a);
3510 GeanyDocument *doc_b = *((GeanyDocument**) b);
3511 gint notebook_position_doc_a;
3512 gint notebook_position_doc_b;
3514 notebook_position_doc_a = document_get_notebook_page(doc_a);
3515 notebook_position_doc_b = document_get_notebook_page(doc_b);
3517 if (notebook_position_doc_a < notebook_position_doc_b)
3518 return -1;
3519 if (notebook_position_doc_a > notebook_position_doc_b)
3520 return 1;
3521 /* equality */
3522 return 0;
3526 /** Compares documents by their tab order, in reverse order.
3527 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3529 * @param a @c GeanyDocument**.
3530 * @param b @c GeanyDocument**.
3531 * @warning The arguments take the address of each document pointer.
3532 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3534 * @since 0.21 (GEANY_API_VERSION 209)
3536 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3538 GeanyDocument *doc_a = *((GeanyDocument**) a);
3539 GeanyDocument *doc_b = *((GeanyDocument**) b);
3540 gint notebook_position_doc_a;
3541 gint notebook_position_doc_b;
3543 notebook_position_doc_a = document_get_notebook_page(doc_a);
3544 notebook_position_doc_b = document_get_notebook_page(doc_b);
3546 if (notebook_position_doc_a < notebook_position_doc_b)
3547 return 1;
3548 if (notebook_position_doc_a > notebook_position_doc_b)
3549 return -1;
3550 /* equality */
3551 return 0;
3555 void document_grab_focus(GeanyDocument *doc)
3557 g_return_if_fail(doc != NULL);
3559 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));