Bump API version for new plugin entry points (oops)
[geany-mirror.git] / src / document.c
blobc2c98b3dc63f72dd0aa9e5f772efe02683ff2c96
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_stack(GTrashStack **stack);
126 static void document_undo_clear(GeanyDocument *doc);
127 static void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data);
128 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
129 static gboolean remove_page(guint page_num);
130 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
131 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
132 const gchar *btn_1, GtkResponseType response_1,
133 const gchar *btn_2, GtkResponseType response_2,
134 const gchar *btn_3, GtkResponseType response_3,
135 const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
139 * Finds a document whose @c real_path field matches the given filename.
141 * @param realname The filename to search, which should be identical to the
142 * string returned by @c tm_get_real_path().
144 * @return The matching document, or @c NULL.
145 * @note This is only really useful when passing a @c TMSourceFile::file_name.
146 * @see GeanyDocument::real_path.
147 * @see document_find_by_filename().
149 * @since 0.15
151 GEANY_API_SYMBOL
152 GeanyDocument* document_find_by_real_path(const gchar *realname)
154 guint i;
156 if (! realname)
157 return NULL; /* file doesn't exist on disk */
159 for (i = 0; i < documents_array->len; i++)
161 GeanyDocument *doc = documents[i];
163 if (! doc->is_valid || ! doc->real_path)
164 continue;
166 if (utils_filenamecmp(realname, doc->real_path) == 0)
168 return doc;
171 return NULL;
175 /* dereference symlinks, /../ junk in path and return locale encoding */
176 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
178 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
179 gchar *realname = tm_get_real_path(locale_name);
181 g_free(locale_name);
182 return realname;
187 * Finds a document with the given filename.
188 * This matches either an exact GeanyDocument::file_name string, or variant
189 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
190 * match @c "/name").
192 * @param utf8_filename The filename to search (in UTF-8 encoding).
194 * @return The matching document, or @c NULL.
195 * @see document_find_by_real_path().
197 GEANY_API_SYMBOL
198 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
200 guint i;
201 GeanyDocument *doc;
202 gchar *realname;
204 g_return_val_if_fail(utf8_filename != NULL, NULL);
206 /* First search GeanyDocument::file_name, so we can find documents with a
207 * filename set but not saved on disk, like vcdiff produces */
208 for (i = 0; i < documents_array->len; i++)
210 doc = documents[i];
212 if (! doc->is_valid || doc->file_name == NULL)
213 continue;
215 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
217 return doc;
220 /* Now try matching based on the realpath(), which is unique per file on disk */
221 realname = get_real_path_from_utf8(utf8_filename);
222 doc = document_find_by_real_path(realname);
223 g_free(realname);
224 return doc;
228 /* returns the document which has sci, or NULL. */
229 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
231 guint i;
233 g_return_val_if_fail(sci != NULL, NULL);
235 for (i = 0; i < documents_array->len; i++)
237 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
238 return documents[i];
240 return NULL;
244 /** Lookup an old document by its ID.
245 * Useful when the corresponding document may have been closed since the
246 * ID was retrieved.
247 * @param id The ID of the document to find
248 * @return @c NULL if the document is no longer open.
250 * Example:
251 * @code
252 * static guint id;
253 * GeanyDocument *doc = ...;
254 * id = doc->id; // store ID
255 * ...
256 * // time passes - the document may have been closed by now
257 * GeanyDocument *doc = document_find_by_id(id);
258 * gboolean still_open = (doc != NULL);
259 * @endcode
260 * @since 1.25. */
261 GEANY_API_SYMBOL
262 GeanyDocument *document_find_by_id(guint id)
264 guint i;
266 if (!id)
267 return NULL;
269 foreach_document(i)
271 if (documents[i]->id == id)
272 return documents[i];
274 return NULL;
278 /* gets the widget the main_widgets.notebook consider is its child for this document */
279 static GtkWidget *document_get_notebook_child(GeanyDocument *doc)
281 GtkWidget *parent;
282 GtkWidget *child;
284 g_return_val_if_fail(doc != NULL, NULL);
286 child = GTK_WIDGET(doc->editor->sci);
287 parent = gtk_widget_get_parent(child);
288 /* search for the direct notebook child, mirroring document_get_from_page() */
289 while (parent && ! GTK_IS_NOTEBOOK(parent))
291 child = parent;
292 parent = gtk_widget_get_parent(child);
295 return child;
299 /** Gets the notebook page index for a document.
300 * @param doc The document.
301 * @return The index.
302 * @since 0.19 */
303 GEANY_API_SYMBOL
304 gint document_get_notebook_page(GeanyDocument *doc)
306 GtkWidget *child = document_get_notebook_child(doc);
308 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
313 * Recursively searches a containers children until it finds a
314 * Scintilla widget, or NULL if one was not found.
316 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
318 ScintillaObject *sci = NULL;
319 GList *children, *iter;
321 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
323 children = gtk_container_get_children(GTK_CONTAINER(container));
324 for (iter = children; iter != NULL; iter = g_list_next(iter))
326 if (IS_SCINTILLA(iter->data))
328 sci = SCINTILLA(iter->data);
329 break;
331 else if (GTK_IS_CONTAINER(iter->data))
333 sci = locate_sci_in_container(iter->data);
334 if (IS_SCINTILLA(sci))
335 break;
336 sci = NULL;
339 g_list_free(children);
341 return sci;
345 /* Finds the document for the given notebook page widget */
346 GeanyDocument *document_get_from_notebook_child(GtkWidget *page)
348 ScintillaObject *sci;
350 g_return_val_if_fail(GTK_IS_BOX(page), NULL);
352 sci = locate_sci_in_container(page);
353 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
355 return document_find_by_sci(sci);
360 * Finds the document for the given notebook page @a page_num.
362 * @param page_num The notebook page number to search.
364 * @return The corresponding document for the given notebook page, or @c NULL.
366 GEANY_API_SYMBOL
367 GeanyDocument *document_get_from_page(guint page_num)
369 GtkWidget *parent;
371 if (page_num >= documents_array->len)
372 return NULL;
374 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
376 return document_get_from_notebook_child(parent);
381 * Finds the current document.
383 * @return A pointer to the current document or @c NULL if there are no opened documents.
385 GEANY_API_SYMBOL
386 GeanyDocument *document_get_current(void)
388 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
390 if (cur_page == -1)
391 return NULL;
392 else
393 return document_get_from_page((guint) cur_page);
397 void document_init_doclist(void)
399 documents_array = g_ptr_array_new();
403 void document_finalize(void)
405 guint i;
407 for (i = 0; i < documents_array->len; i++)
408 g_free(documents[i]);
409 g_ptr_array_free(documents_array, TRUE);
414 * Returns the last part of the filename of the given GeanyDocument. The result is also
415 * truncated to a maximum of @a length characters in case the filename is very long.
417 * @param doc The document to use.
418 * @param length The length of the resulting string or -1 to use a default value.
420 * @return The ellipsized last part of the filename of @a doc, should be freed when no
421 * longer needed.
423 * @since 0.17
425 /* TODO make more use of this */
426 GEANY_API_SYMBOL
427 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
429 gchar *base_name, *short_name;
431 g_return_val_if_fail(doc != NULL, NULL);
433 if (length < 0)
434 length = 30;
436 base_name = g_path_get_basename(DOC_FILENAME(doc));
437 short_name = utils_str_middle_truncate(base_name, (guint)length);
439 g_free(base_name);
441 return short_name;
445 void document_update_tab_label(GeanyDocument *doc)
447 gchar *short_name;
448 GtkWidget *parent;
450 g_return_if_fail(doc != NULL);
452 short_name = document_get_basename_for_display(doc, -1);
454 /* we need to use the event box for the tooltip, labels don't get the necessary events */
455 parent = gtk_widget_get_parent(doc->priv->tab_label);
456 parent = gtk_widget_get_parent(parent);
458 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
460 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
462 g_free(short_name);
467 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
468 * according to the document's save state.
469 * This is called by Geany mostly when opening or saving files.
471 * @param doc The document to use.
472 * @param changed Whether the document state should indicate changes have been made.
474 GEANY_API_SYMBOL
475 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
477 g_return_if_fail(doc != NULL);
479 doc->changed = changed;
481 if (! main_status.quitting)
483 ui_update_tab_status(doc);
484 ui_save_buttons_toggle(changed);
485 ui_set_window_title(doc);
486 ui_update_statusbar(doc, -1);
491 /* returns the next free place in the document list,
492 * or -1 if the documents_array is full */
493 static gint document_get_new_idx(void)
495 guint i;
497 for (i = 0; i < documents_array->len; i++)
499 if (documents[i]->editor == NULL)
501 return (gint) i;
504 return -1;
508 static void queue_colourise(GeanyDocument *doc)
510 /* Colourise the editor before it is next drawn */
511 doc->priv->colourise_needed = TRUE;
513 /* If the editor doesn't need drawing (e.g. after saving the current
514 * document), we need to force a redraw, so the expose event is triggered.
515 * This ensures we don't start colourising before all documents are opened/saved,
516 * only once the editor is drawn. */
517 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
521 #ifdef USE_GIO_FILEMON
522 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
523 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
524 GeanyDocument *doc)
526 g_return_if_fail(doc != NULL);
528 if (file_prefs.disk_check_timeout == 0)
529 return;
531 geany_debug("%s: event: %d previous file status: %d",
532 G_STRFUNC, event, doc->priv->file_disk_status);
533 switch (event)
535 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
537 if (doc->priv->file_disk_status == FILE_IGNORE)
538 doc->priv->file_disk_status = FILE_OK;
539 else
540 doc->priv->file_disk_status = FILE_CHANGED;
541 g_message("%s: FILE_CHANGED", G_STRFUNC);
542 break;
544 case G_FILE_MONITOR_EVENT_DELETED:
546 doc->priv->file_disk_status = FILE_CHANGED;
547 g_message("%s: FILE_MISSING", G_STRFUNC);
548 break;
550 default:
551 break;
553 if (doc->priv->file_disk_status != FILE_OK)
555 ui_update_tab_status(doc);
558 #endif
561 static void document_stop_file_monitoring(GeanyDocument *doc)
563 g_return_if_fail(doc != NULL);
565 if (doc->priv->monitor != NULL)
567 g_object_unref(doc->priv->monitor);
568 doc->priv->monitor = NULL;
573 static void monitor_file_setup(GeanyDocument *doc)
575 g_return_if_fail(doc != NULL);
576 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
577 * doesn't work at all for remote files and legacy polling is too slow. */
578 if (! doc->priv->is_remote)
580 #ifdef USE_GIO_FILEMON
581 gchar *locale_filename;
583 /* stop any previous monitoring */
584 document_stop_file_monitoring(doc);
586 locale_filename = utils_get_locale_from_utf8(doc->file_name);
587 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
589 /* get a file monitor and connect to the 'changed' signal */
590 GFile *file = g_file_new_for_path(locale_filename);
591 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
592 g_signal_connect(doc->priv->monitor, "changed",
593 G_CALLBACK(monitor_file_changed_cb), doc);
595 /* we set the rate limit according to the GUI pref but it's most probably not used */
596 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
598 g_object_unref(file);
600 g_free(locale_filename);
601 #endif
603 doc->priv->file_disk_status = FILE_OK;
607 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
609 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
610 if (DOC_VALID(doc))
612 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
613 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
615 if (source_widget == NULL)
616 source_widget = doc->priv->tag_tree;
618 if (focusw == source_widget)
619 gtk_widget_grab_focus(sci);
624 static gboolean on_idle_focus(gpointer doc)
626 document_try_focus(doc, NULL);
627 return FALSE;
631 /* Creates a new document and editor, adding a tab in the notebook.
632 * @return The created document */
633 static GeanyDocument *document_create(const gchar *utf8_filename)
635 GeanyDocument *doc;
636 gint new_idx;
637 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
639 if (cur_pages == 1)
641 doc = document_get_current();
642 /* remove the empty document first */
643 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
644 /* prevent immediately opening another new doc with
645 * new_document_after_close pref */
646 remove_page(0);
649 new_idx = document_get_new_idx();
650 if (new_idx == -1) /* expand the array, no free places */
652 doc = g_new0(GeanyDocument, 1);
654 new_idx = documents_array->len;
655 g_ptr_array_add(documents_array, doc);
658 doc = documents[new_idx];
660 /* initialize default document settings */
661 doc->priv = g_new0(GeanyDocumentPrivate, 1);
662 doc->id = ++doc_id_counter;
663 doc->index = new_idx;
664 doc->file_name = g_strdup(utf8_filename);
665 doc->editor = editor_create(doc);
666 #ifndef USE_GIO_FILEMON
667 doc->priv->last_check = time(NULL);
668 #endif
670 sidebar_openfiles_add(doc); /* sets doc->iter */
672 notebook_new_tab(doc);
674 /* select document in sidebar */
676 GtkTreeSelection *sel;
678 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
679 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
682 ui_document_buttons_update();
684 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
685 return doc;
690 * Closes the given document.
692 * @param doc The document to remove.
694 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
696 * @since 0.15
698 GEANY_API_SYMBOL
699 gboolean document_close(GeanyDocument *doc)
701 g_return_val_if_fail(doc, FALSE);
703 return document_remove_page(document_get_notebook_page(doc));
707 /* Call document_remove_page() instead, this is only needed for document_create()
708 * to prevent re-opening a new document when the last document is closed (if enabled). */
709 static gboolean remove_page(guint page_num)
711 GeanyDocument *doc = document_get_from_page(page_num);
713 g_return_val_if_fail(doc != NULL, FALSE);
715 if (doc->changed && ! dialogs_show_unsaved_file(doc))
716 return FALSE;
718 /* tell any plugins that the document is about to be closed */
719 g_signal_emit_by_name(geany_object, "document-close", doc);
721 /* Checking real_path makes it likely the file exists on disk */
722 if (! main_status.closing_all && doc->real_path != NULL)
723 ui_add_recent_document(doc);
725 doc->is_valid = FALSE;
726 doc->id = 0;
728 if (main_status.quitting)
730 /* we need to destroy the ScintillaWidget so our handlers on it are
731 * disconnected before we free any data they may use (like the editor).
732 * when not quitting, this is handled by removing the notebook page. */
733 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
735 else
737 notebook_remove_page(page_num);
738 sidebar_remove_document(doc);
739 navqueue_remove_file(doc->file_name);
740 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
742 g_free(doc->encoding);
743 g_free(doc->priv->saved_encoding.encoding);
744 g_free(doc->file_name);
745 g_free(doc->real_path);
746 if (doc->tm_file)
748 tm_workspace_remove_source_file(doc->tm_file);
749 tm_source_file_free(doc->tm_file);
752 if (doc->priv->tag_tree)
753 gtk_widget_destroy(doc->priv->tag_tree);
755 editor_destroy(doc->editor);
756 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
758 document_stop_file_monitoring(doc);
760 document_undo_clear(doc);
762 g_free(doc->priv);
764 /* reset document settings to defaults for re-use */
765 memset(doc, 0, sizeof(GeanyDocument));
767 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
769 sidebar_update_tag_list(NULL, FALSE);
770 ui_set_window_title(NULL);
771 ui_save_buttons_toggle(FALSE);
772 ui_update_popup_reundo_items(NULL);
773 ui_document_buttons_update();
774 build_menu_update(NULL);
776 return TRUE;
781 * Removes the given notebook tab at @a page_num and clears all related information
782 * in the document list.
784 * @param page_num The notebook page number to remove.
786 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
788 GEANY_API_SYMBOL
789 gboolean document_remove_page(guint page_num)
791 gboolean done = remove_page(page_num);
793 if (done && ui_prefs.new_document_after_close)
794 document_new_file_if_non_open();
796 return done;
800 /* used to keep a record of the unchanged document state encoding */
801 static void store_saved_encoding(GeanyDocument *doc)
803 g_free(doc->priv->saved_encoding.encoding);
804 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
805 doc->priv->saved_encoding.has_bom = doc->has_bom;
809 /* Opens a new empty document only if there are no other documents open */
810 GeanyDocument *document_new_file_if_non_open(void)
812 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
813 return document_new_file(NULL, NULL, NULL);
815 return NULL;
820 * Creates a new document.
821 * Line endings in @a text will be converted to the default setting.
822 * Afterwards, the @c "document-new" signal is emitted for plugins.
824 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
825 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
826 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
828 * @return The new document.
830 GEANY_API_SYMBOL
831 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
833 GeanyDocument *doc;
835 if (utf8_filename && g_path_is_absolute(utf8_filename))
837 gchar *tmp;
838 tmp = utils_strdupa(utf8_filename); /* work around const */
839 utils_tidy_path(tmp);
840 utf8_filename = tmp;
842 doc = document_create(utf8_filename);
844 g_assert(doc != NULL);
846 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
847 if (text)
849 GString *template = g_string_new(text);
850 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
852 sci_set_text(doc->editor->sci, template->str);
853 g_string_free(template, TRUE);
855 else
856 sci_clear_all(doc->editor->sci);
858 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
860 sci_set_undo_collection(doc->editor->sci, TRUE);
861 sci_empty_undo_buffer(doc->editor->sci);
863 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
864 /* store the opened encoding for undo/redo */
865 store_saved_encoding(doc);
867 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
868 ft = filetypes_detect_from_document(doc);
870 document_set_filetype(doc, ft); /* also re-parses tags */
872 /* now the document is fully ready, display it (see notebook_new_tab()) */
873 gtk_widget_show(document_get_notebook_child(doc));
875 ui_set_window_title(doc);
876 build_menu_update(doc);
877 document_set_text_changed(doc, FALSE);
878 ui_document_show_hide(doc); /* update the document menu */
880 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
881 /* bring it in front, jump to the start and grab the focus */
882 editor_goto_pos(doc->editor, 0, FALSE);
883 document_try_focus(doc, NULL);
885 #ifdef USE_GIO_FILEMON
886 monitor_file_setup(doc);
887 #else
888 doc->priv->mtime = time(NULL);
889 #endif
891 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
892 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
894 g_signal_emit_by_name(geany_object, "document-new", doc);
896 msgwin_status_add(_("New file \"%s\" opened."),
897 DOC_FILENAME(doc));
899 return doc;
904 * Opens a document specified by @a locale_filename.
905 * Afterwards, the @c "document-open" signal is emitted for plugins.
907 * @param locale_filename The filename of the document to load, in locale encoding.
908 * @param readonly Whether to open the document in read-only mode.
909 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
910 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
912 * @return The document opened or @c NULL.
914 GEANY_API_SYMBOL
915 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
916 GeanyFiletype *ft, const gchar *forced_enc)
918 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
922 typedef struct
924 gchar *data; /* null-terminated file data */
925 gsize len; /* string length of data */
926 gchar *enc;
927 gboolean bom;
928 time_t mtime; /* modification time, read by stat::st_mtime */
929 gboolean readonly;
930 } FileData;
933 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
934 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
935 FileData *filedata, const gchar *forced_enc)
937 GError *err = NULL;
938 struct stat st;
940 filedata->data = NULL;
941 filedata->len = 0;
942 filedata->enc = NULL;
943 filedata->bom = FALSE;
944 filedata->readonly = FALSE;
946 if (g_stat(locale_filename, &st) != 0)
948 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
949 display_filename, g_strerror(errno));
950 return FALSE;
953 filedata->mtime = st.st_mtime;
955 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
957 ui_set_statusbar(TRUE, "%s", err->message);
958 g_error_free(err);
959 return FALSE;
962 filedata->len = (gsize) st.st_size;
963 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
964 &filedata->enc, &filedata->bom, &filedata->readonly))
966 if (forced_enc)
968 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
969 display_filename, forced_enc);
971 else
973 ui_set_statusbar(TRUE,
974 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
975 display_filename);
977 g_free(filedata->data);
978 return FALSE;
981 if (filedata->readonly)
983 const gchar *warn_msg = _(
984 "The file \"%s\" could not be opened properly and has been truncated. " \
985 "This can occur if the file contains a NULL byte. " \
986 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
988 if (main_status.main_window_realized)
989 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
991 ui_set_statusbar(TRUE, warn_msg, display_filename);
994 return TRUE;
998 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
999 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1000 * if cl_options.goto_column is set.
1002 * returns the new position which may have changed */
1003 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1005 if (cl_options.goto_line >= 0)
1006 { /* goto line which was specified on command line and then undefine the line */
1007 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1008 editor->scroll_percent = 0.5F;
1009 cl_options.goto_line = -1;
1011 else if (pos > 0)
1013 sci_set_current_position(editor->sci, pos, FALSE);
1014 editor->scroll_percent = 0.5F;
1017 if (cl_options.goto_column >= 0)
1018 { /* goto column which was specified on command line and then undefine the column */
1020 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1021 sci_set_current_position(editor->sci, new_pos, FALSE);
1022 editor->scroll_percent = 0.5F;
1023 cl_options.goto_column = -1;
1024 return new_pos;
1026 return sci_get_current_position(editor->sci);
1030 /* Count lines that start with some hard tabs then a soft tab. */
1031 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1033 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1034 ScintillaObject *sci = editor->sci;
1035 gsize count = 0;
1036 struct Sci_TextToFind ttf;
1037 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1038 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1040 g_free(soft_tab);
1042 ttf.chrg.cpMin = 0;
1043 ttf.chrg.cpMax = sci_get_length(sci);
1044 ttf.lpstrText = regex;
1045 while (1)
1047 gint pos;
1049 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1050 if (pos == -1)
1051 break; /* no more matches */
1052 count++;
1053 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1055 g_free(regex);
1056 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1057 return count > sci_get_line_count(sci) * 0.02;
1061 /* Detect the indent type based on counting the leading indent characters for each line.
1062 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1063 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1065 GeanyEditor *editor = doc->editor;
1066 ScintillaObject *sci = editor->sci;
1067 gint line, line_count;
1068 gsize tabs = 0, spaces = 0;
1070 if (detect_tabs_and_spaces(editor))
1072 *type_ = GEANY_INDENT_TYPE_BOTH;
1073 return TRUE;
1076 line_count = sci_get_line_count(sci);
1077 for (line = 0; line < line_count; line++)
1079 gint pos = sci_get_position_from_line(sci, line);
1080 gchar c;
1082 /* most code will have indent total <= 24, otherwise it's more likely to be
1083 * alignment than indentation */
1084 if (sci_get_line_indentation(sci, line) > 24)
1085 continue;
1087 c = sci_get_char_at(sci, pos);
1088 if (c == '\t')
1089 tabs++;
1090 /* check for at least 2 spaces */
1091 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1092 spaces++;
1094 if (spaces == 0 && tabs == 0)
1095 return FALSE;
1097 /* the factors may need to be tweaked */
1098 if (spaces > tabs * 4)
1099 *type_ = GEANY_INDENT_TYPE_SPACES;
1100 else if (tabs > spaces * 4)
1101 *type_ = GEANY_INDENT_TYPE_TABS;
1102 else
1103 *type_ = GEANY_INDENT_TYPE_BOTH;
1105 return TRUE;
1109 /* Detect the indent width based on counting the leading indent characters for each line.
1110 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1111 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1113 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1114 ScintillaObject *sci = editor->sci;
1115 gint line, line_count;
1116 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1117 gint count, width, i;
1119 /* can't easily detect the supposed width of a tab, guess the default is OK */
1120 if (type == GEANY_INDENT_TYPE_TABS)
1121 return FALSE;
1123 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1124 sci_set_tab_width(sci, 8);
1126 line_count = sci_get_line_count(sci);
1127 for (line = 0; line < line_count; line++)
1129 gint pos = sci_get_line_indent_position(sci, line);
1131 /* We probably don't have style info yet, because we're generally called just after
1132 * the document got created, so we can't use highlighting_is_code_style().
1133 * That's not good, but the assumption below that concerning lines start with an
1134 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1135 * without removing too much legitimate lines. */
1136 if (sci_get_char_at(sci, pos) == '*')
1137 continue;
1139 width = sci_get_line_indentation(sci, line);
1140 /* most code will have indent total <= 24, otherwise it's more likely to be
1141 * alignment than indentation */
1142 if (width > 24)
1143 continue;
1144 /* < 2 is no indentation */
1145 if (width < 2)
1146 continue;
1148 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1150 if ((width % (i + 2)) == 0)
1151 widths[i]++;
1154 count = 0;
1155 width = iprefs->width;
1156 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1158 /* give large indents higher weight not to be fooled by spurious indents */
1159 if (widths[i] >= count * 1.5)
1161 width = i + 2;
1162 count = widths[i];
1166 if (count == 0)
1167 return FALSE;
1169 *width_ = width;
1170 return TRUE;
1174 /* same as detect_indent_width() but uses editor's indent type */
1175 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1177 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1181 void document_apply_indent_settings(GeanyDocument *doc)
1183 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1184 GeanyIndentType type = iprefs->type;
1185 gint width = iprefs->width;
1187 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1189 if (type != iprefs->type)
1191 const gchar *name = NULL;
1193 switch (type)
1195 case GEANY_INDENT_TYPE_SPACES:
1196 name = _("Spaces");
1197 break;
1198 case GEANY_INDENT_TYPE_TABS:
1199 name = _("Tabs");
1200 break;
1201 case GEANY_INDENT_TYPE_BOTH:
1202 name = _("Tabs and Spaces");
1203 break;
1205 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1206 * and Spaces), the second one is the filename */
1207 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1208 DOC_FILENAME(doc));
1211 else if (doc->file_type->indent_type > -1)
1212 type = doc->file_type->indent_type;
1214 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1216 if (width != iprefs->width)
1218 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1219 DOC_FILENAME(doc));
1222 else if (doc->file_type->indent_width > -1)
1223 width = doc->file_type->indent_width;
1225 editor_set_indent(doc->editor, type, width);
1229 void document_show_tab(GeanyDocument *doc)
1231 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1232 document_get_notebook_page(doc));
1236 /* To open a new file, set doc to NULL; filename should be locale encoded.
1237 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1238 * pos is the cursor position, which can be overridden by --line and --column.
1239 * forced_enc can be NULL to detect the file encoding.
1240 * Returns: doc of the opened file or NULL if an error occurred. */
1241 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1242 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1244 gint editor_mode;
1245 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1246 gchar *utf8_filename = NULL;
1247 gchar *display_filename = NULL;
1248 gchar *locale_filename = NULL;
1249 GeanyFiletype *use_ft;
1250 FileData filedata;
1251 UndoReloadData *undo_reload_data;
1252 gboolean add_undo_reload_action;
1254 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1256 if (reload)
1258 utf8_filename = g_strdup(doc->file_name);
1259 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1261 else
1263 /* filename must not be NULL when opening a file */
1264 g_return_val_if_fail(filename, NULL);
1266 #ifdef G_OS_WIN32
1267 /* if filename is a shortcut, try to resolve it */
1268 locale_filename = win32_get_shortcut_target(filename);
1269 #else
1270 locale_filename = g_strdup(filename);
1271 #endif
1272 /* remove relative junk */
1273 utils_tidy_path(locale_filename);
1275 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1276 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1278 /* if file is already open, switch to it and go */
1279 doc = document_find_by_filename(utf8_filename);
1280 if (doc != NULL)
1282 ui_add_recent_document(doc); /* either add or reorder recent item */
1283 /* show the doc before reload dialog */
1284 document_show_tab(doc);
1285 document_check_disk_status(doc, TRUE); /* force a file changed check */
1288 if (reload || doc == NULL)
1289 { /* doc possibly changed */
1290 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1292 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1294 g_free(display_filename);
1295 g_free(utf8_filename);
1296 g_free(locale_filename);
1297 return NULL;
1300 if (! reload)
1302 doc = document_create(utf8_filename);
1303 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1305 /* file exists on disk, set real_path */
1306 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1308 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1309 monitor_file_setup(doc);
1312 if (! reload || ! file_prefs.keep_edit_history_on_reload)
1314 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1315 sci_empty_undo_buffer(doc->editor->sci);
1316 undo_reload_data = NULL;
1318 else
1320 undo_reload_data = (UndoReloadData*) g_malloc(sizeof(UndoReloadData));
1322 /* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1323 * this reload. To do that, we keep collecting undo actions during
1324 * reloading, and at the end add an UNDO_RELOAD action that performs
1325 * all these actions in bulk. To keep track of how many undo actions
1326 * were added during this time, we compare the current undo-stack height
1327 * with its height at the end of the process. Note that g_trash_stack_height()
1328 * is O(N), which is a little ugly, but this seems like the most maintainable
1329 * option. */
1330 undo_reload_data->actions_count = g_trash_stack_height(&doc->priv->undo_actions);
1332 /* We use add_undo_reload_action to track any changes to the document that
1333 * require adding an undo action to revert the reload, but that do not
1334 * generate an undo action themselves. */
1335 add_undo_reload_action = FALSE;
1338 /* add the text to the ScintillaObject */
1339 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1340 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1341 queue_colourise(doc); /* Ensure the document gets colourised. */
1343 /* detect & set line endings */
1344 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1345 if (undo_reload_data)
1347 undo_reload_data->eol_mode = editor_get_eol_char_mode(doc->editor);
1348 /* Force adding an undo-reload action if the EOL mode changed. */
1349 if (editor_mode != undo_reload_data->eol_mode)
1350 add_undo_reload_action = TRUE;
1352 sci_set_eol_mode(doc->editor->sci, editor_mode);
1353 g_free(filedata.data);
1355 sci_set_undo_collection(doc->editor->sci, TRUE);
1357 /* If reloading and the current and new encodings or BOM states differ,
1358 * add appropriate undo actions. */
1359 if (undo_reload_data)
1361 if (! utils_str_equal(doc->encoding, filedata.enc))
1362 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
1363 if (doc->has_bom != filedata.bom)
1364 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
1367 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1368 g_free(doc->encoding); /* if reloading, free old encoding */
1369 doc->encoding = filedata.enc;
1370 doc->has_bom = filedata.bom;
1371 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1373 doc->readonly = readonly || filedata.readonly;
1374 sci_set_readonly(doc->editor->sci, doc->readonly);
1375 doc->priv->protected = 0;
1377 /* update line number margin width */
1378 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1379 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1381 if (! reload)
1384 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1385 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1386 doc->editor);
1388 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1390 else
1391 { /* reloading */
1392 if (undo_reload_data)
1394 /* Calculate the number of undo actions that are part of the reloading
1395 * process, and add the UNDO_RELOAD action. */
1396 undo_reload_data->actions_count =
1397 g_trash_stack_height(&doc->priv->undo_actions) - undo_reload_data->actions_count;
1399 /* We only add an undo-reload action if the document has actually changed.
1400 * At the time of writing, this condition is moot because sci_set_text
1401 * generates an undo action even when the text hasn't really changed, so
1402 * actions_count is always greater than zero. In the future this might change.
1403 * It's arguable whether we should add an undo-reload action unconditionally,
1404 * especially since it's possible (if unlikely) that there had only
1405 * been "invisible" changes to the document, such as changes in encoding and
1406 * EOL mode, but for the time being that's how we roll. */
1407 if (undo_reload_data->actions_count > 0 || add_undo_reload_action)
1408 document_undo_add(doc, UNDO_RELOAD, undo_reload_data);
1409 else
1410 g_free(undo_reload_data);
1412 /* We didn't save the document per-se, but its contents are now
1413 * synchronized with the file on disk, hence set a save point here.
1414 * We need to do this in this case only, because we don't clear
1415 * Scintilla's undo stack. */
1416 sci_set_savepoint(doc->editor->sci);
1418 else
1419 document_undo_clear(doc);
1421 use_ft = ft;
1423 /* update taglist, typedef keywords and build menu if necessary */
1424 document_set_filetype(doc, use_ft);
1426 /* set indentation settings after setting the filetype */
1427 if (reload)
1428 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1429 else
1430 document_apply_indent_settings(doc);
1432 document_set_text_changed(doc, FALSE); /* also updates tab state */
1433 ui_document_show_hide(doc); /* update the document menu */
1435 /* finally add current file to recent files menu, but not the files from the last session */
1436 if (! main_status.opening_session_files)
1437 ui_add_recent_document(doc);
1439 if (reload)
1441 g_signal_emit_by_name(geany_object, "document-reload", doc);
1442 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1444 else
1446 g_signal_emit_by_name(geany_object, "document-open", doc);
1447 /* For translators: this is the status window message for opening a file. %d is the number
1448 * of the newly opened file, %s indicates whether the file is opened read-only
1449 * (it is replaced with the string ", read-only"). */
1450 msgwin_status_add(_("File %s opened(%d%s)."),
1451 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1452 (readonly) ? _(", read-only") : "");
1455 /* now the document is fully ready, display it (see notebook_new_tab()) */
1456 gtk_widget_show(document_get_notebook_child(doc));
1459 g_free(display_filename);
1460 g_free(utf8_filename);
1461 g_free(locale_filename);
1463 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1464 pos = set_cursor_position(doc->editor, pos);
1465 /* now bring the file in front */
1466 editor_goto_pos(doc->editor, pos, FALSE);
1468 /* finally, let the editor widget grab the focus so you can start coding
1469 * right away */
1470 g_idle_add(on_idle_focus, doc);
1471 return doc;
1475 /* Takes a new line separated list of filename URIs and opens each file.
1476 * length is the length of the string */
1477 void document_open_file_list(const gchar *data, gsize length)
1479 guint i;
1480 gchar *filename;
1481 gchar **list;
1483 g_return_if_fail(data != NULL);
1485 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1487 /* stop at the end or first empty item, because last item is empty but not null */
1488 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1490 filename = utils_get_path_from_uri(list[i]);
1491 if (filename == NULL)
1492 continue;
1493 document_open_file(filename, FALSE, NULL, NULL);
1494 g_free(filename);
1497 g_strfreev(list);
1502 * Opens each file in the list @a filenames.
1503 * Internally, document_open_file() is called for every list item.
1505 * @param filenames A list of filenames to load, in locale encoding.
1506 * @param readonly Whether to open the document in read-only mode.
1507 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1508 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1510 GEANY_API_SYMBOL
1511 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1512 const gchar *forced_enc)
1514 const GSList *item;
1516 for (item = filenames; item != NULL; item = g_slist_next(item))
1518 document_open_file(item->data, readonly, ft, forced_enc);
1524 * Reloads the document with the specified file encoding.
1525 * @a forced_enc or @c NULL to auto-detect the file encoding.
1527 * @param doc The document to reload.
1528 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1530 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1532 GEANY_API_SYMBOL
1533 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1535 gint pos = 0;
1536 GeanyDocument *new_doc;
1538 g_return_val_if_fail(doc != NULL, FALSE);
1540 /* Use cancel because the response handler would call this recursively */
1541 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1542 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1544 /* try to set the cursor to the position before reloading */
1545 pos = sci_get_current_position(doc->editor->sci);
1546 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1548 return (new_doc != NULL);
1552 /* also used for reloading when forced_enc is NULL */
1553 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1555 gchar *base_name;
1556 gboolean prompt, result = FALSE;
1558 g_return_val_if_fail(doc != NULL, FALSE);
1560 /* No need to reload "untitled" (non-file-backed) documents */
1561 if (doc->file_name == NULL)
1562 return FALSE;
1564 if (forced_enc == NULL)
1565 forced_enc = doc->encoding;
1567 base_name = g_path_get_basename(doc->file_name);
1568 /* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1569 prompt = !file_prefs.keep_edit_history_on_reload &&
1570 (doc->changed || (document_can_undo(doc) || document_can_redo(doc)));
1572 if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1573 doc->changed ? _("Any unsaved changes will be lost.") :
1574 _("Undo history will be lost."),
1575 _("Are you sure you want to reload '%s'?"), base_name))
1577 result = document_reload_force(doc, forced_enc);
1578 if (forced_enc != NULL)
1579 ui_update_statusbar(doc, -1);
1581 g_free(base_name);
1582 return result;
1586 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1588 #ifndef USE_GIO_FILEMON
1589 struct stat st;
1591 g_return_val_if_fail(doc != NULL, FALSE);
1593 /* stat the file to get the timestamp, otherwise on Windows the actual
1594 * timestamp can be ahead of time(NULL) */
1595 if (g_stat(locale_filename, &st) != 0)
1597 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1598 g_strerror(errno));
1599 return FALSE;
1602 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1603 #endif
1604 return TRUE;
1608 /* Sets line and column to the given position byte_pos in the document.
1609 * byte_pos is the position counted in bytes, not characters */
1610 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1612 gint i;
1613 gint line_start;
1615 /* for some reason we can use byte count instead of character count here */
1616 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1617 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1618 /* get the column in the line */
1619 *column = byte_pos - line_start;
1621 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1622 * skip one byte(i++) and decrease the column number which is based on byte count */
1623 for (i = line_start; i < (line_start + *column); i++)
1625 if (sci_get_char_at(doc->editor->sci, i) < 0)
1627 (*column)--;
1628 i++;
1634 static void replace_header_filename(GeanyDocument *doc)
1636 gchar *filebase;
1637 gchar *filename;
1638 struct Sci_TextToFind ttf;
1640 g_return_if_fail(doc != NULL);
1641 g_return_if_fail(doc->file_type != NULL);
1643 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1644 if (doc->file_type->extension)
1645 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1646 else
1647 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1649 filename = g_path_get_basename(doc->file_name);
1651 /* only search the first 3 lines */
1652 ttf.chrg.cpMin = 0;
1653 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1654 ttf.lpstrText = filebase;
1656 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1658 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1659 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1660 sci_replace_target(doc->editor->sci, filename, FALSE);
1662 g_free(filebase);
1663 g_free(filename);
1668 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1669 * you still have to call @ref document_save_file_as() to change the @a doc object.
1670 * It also stops monitoring for file changes to prevent receiving too many file change events
1671 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1673 * @param doc The current document which should be renamed.
1674 * @param new_filename The new filename in UTF-8 encoding.
1676 * @since 0.16
1678 GEANY_API_SYMBOL
1679 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1681 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1682 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1683 gint result;
1685 /* stop file monitoring to avoid getting events for deleting/creating files,
1686 * it's re-setup in document_save_file_as() */
1687 document_stop_file_monitoring(doc);
1689 result = g_rename(old_locale_filename, new_locale_filename);
1690 if (result != 0)
1692 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1693 _("Error renaming file."), g_strerror(errno));
1695 g_free(old_locale_filename);
1696 g_free(new_locale_filename);
1700 static void protect_document(GeanyDocument *doc)
1702 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1703 if (!doc->priv->protected++)
1704 sci_set_readonly(doc->editor->sci, TRUE);
1706 ui_update_tab_status(doc);
1710 static void unprotect_document(GeanyDocument *doc)
1712 g_return_if_fail(doc->priv->protected > 0);
1714 if (!--doc->priv->protected && doc->readonly == FALSE)
1715 sci_set_readonly(doc->editor->sci, FALSE);
1717 ui_update_tab_status(doc);
1721 /* Return TRUE if the document doesn't have a full filename set.
1722 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1723 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1724 * new files. */
1725 gboolean document_need_save_as(GeanyDocument *doc)
1727 g_return_val_if_fail(doc != NULL, FALSE);
1729 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1734 * Saves the document, detecting the filetype.
1736 * @param doc The document for the file to save.
1737 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1738 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1740 * @see document_save_file().
1742 * @since 0.16
1744 GEANY_API_SYMBOL
1745 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1747 gboolean ret;
1748 gboolean new_file;
1750 g_return_val_if_fail(doc != NULL, FALSE);
1752 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1753 if (utf8_fname != NULL)
1754 SETPTR(doc->file_name, g_strdup(utf8_fname));
1756 /* reset real path, it's retrieved again in document_save() */
1757 SETPTR(doc->real_path, NULL);
1759 /* detect filetype */
1760 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1762 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1764 document_set_filetype(doc, ft);
1765 if (document_get_current() == doc)
1767 ignore_callback = TRUE;
1768 filetypes_select_radio_item(doc->file_type);
1769 ignore_callback = FALSE;
1773 if (new_file)
1775 // assume user wants to throw away read-only setting
1776 sci_set_readonly(doc->editor->sci, FALSE);
1777 doc->readonly = FALSE;
1778 if (doc->priv->protected > 0)
1779 unprotect_document(doc);
1782 replace_header_filename(doc);
1784 ret = document_save_file(doc, TRUE);
1786 /* file monitoring support, add file monitoring after the file has been saved
1787 * to ignore any earlier events */
1788 monitor_file_setup(doc);
1789 doc->priv->file_disk_status = FILE_IGNORE;
1791 if (ret)
1792 ui_add_recent_document(doc);
1793 return ret;
1797 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1799 GError *conv_error = NULL;
1800 gchar* conv_file_contents = NULL;
1801 gsize bytes_read;
1802 gsize conv_len;
1804 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1805 g_return_val_if_fail(len != NULL, FALSE);
1807 /* try to convert it from UTF-8 to original encoding */
1808 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1809 &bytes_read, &conv_len, &conv_error);
1811 if (conv_error != NULL)
1813 gchar *text = g_strdup_printf(
1814 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1815 doc->encoding);
1816 gchar *error_text;
1818 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1820 gint line, column;
1821 gint context_len;
1822 gunichar unic;
1823 /* don't read over the doc length */
1824 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1825 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1826 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1828 /* take only one valid Unicode character from the context and discard the leftover */
1829 unic = g_utf8_get_char_validated(context, -1);
1830 context_len = g_unichar_to_utf8(unic, context);
1831 context[context_len] = '\0';
1832 get_line_column_from_pos(doc, bytes_read, &line, &column);
1834 error_text = g_strdup_printf(
1835 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1836 conv_error->message, context, line + 1, column);
1838 else
1839 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1841 geany_debug("encoding error: %s", conv_error->message);
1842 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1843 g_error_free(conv_error);
1844 g_free(text);
1845 g_free(error_text);
1846 return FALSE;
1848 else
1850 g_free(*data);
1851 *data = conv_file_contents;
1852 *len = conv_len;
1854 return TRUE;
1858 static gchar *write_data_to_disk(const gchar *locale_filename,
1859 const gchar *data, gsize len)
1861 GError *error = NULL;
1863 if (file_prefs.use_safe_file_saving)
1865 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1866 * This is the only option that handles disk space exhaustion. */
1867 if (g_file_set_contents(locale_filename, data, len, &error))
1868 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1870 else if (file_prefs.use_gio_unsafe_file_saving)
1872 GFile *fp;
1874 /* Use GIO API to save file (GVFS-safe)
1875 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1876 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1877 fp = g_file_new_for_path(locale_filename);
1878 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1879 G_FILE_CREATE_NONE, NULL, NULL, &error);
1880 g_object_unref(fp);
1882 else
1884 FILE *fp;
1885 int save_errno;
1886 gchar *display_name = g_filename_display_name(locale_filename);
1888 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1889 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1890 errno = 0;
1891 fp = g_fopen(locale_filename, "wb");
1892 if (fp == NULL)
1894 save_errno = errno;
1896 g_set_error(&error,
1897 G_FILE_ERROR,
1898 g_file_error_from_errno(save_errno),
1899 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1900 display_name,
1901 g_strerror(save_errno));
1903 else
1905 gsize bytes_written;
1907 errno = 0;
1908 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1910 if (len != bytes_written)
1912 save_errno = errno;
1914 g_set_error(&error,
1915 G_FILE_ERROR,
1916 g_file_error_from_errno(save_errno),
1917 _("Failed to write file '%s': fwrite() failed: %s"),
1918 display_name,
1919 g_strerror(save_errno));
1922 errno = 0;
1923 /* preserve the fwrite() error if any */
1924 if (fclose(fp) != 0 && error == NULL)
1926 save_errno = errno;
1928 g_set_error(&error,
1929 G_FILE_ERROR,
1930 g_file_error_from_errno(save_errno),
1931 _("Failed to close file '%s': fclose() failed: %s"),
1932 display_name,
1933 g_strerror(save_errno));
1937 g_free(display_name);
1939 if (error != NULL)
1941 gchar *msg = g_strdup(error->message);
1942 g_error_free(error);
1943 /* geany will warn about file truncation for unsafe saving below */
1944 return msg;
1946 return NULL;
1950 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1951 const gchar *data, gsize len)
1953 gchar *err;
1955 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1956 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1958 err = write_data_to_disk(locale_filename, data, len);
1959 if (err)
1960 return err;
1962 /* now the file is on disk, set real_path */
1963 if (doc->real_path == NULL)
1965 doc->real_path = tm_get_real_path(locale_filename);
1966 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1967 monitor_file_setup(doc);
1969 return NULL;
1973 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
1975 GtkWidget *bar = NULL;
1977 document_show_tab(doc);
1979 if (doc->priv->info_bars[MSG_TYPE_RELOAD])
1981 if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
1982 _("Overwrite?"),
1983 _("The file '%s' on the disk is more recent than the current buffer."),
1984 doc->file_name))
1985 return FALSE;
1986 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
1988 else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
1990 if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
1991 _("Try to resave the file?"),
1992 _("File \"%s\" was not found on disk!"),
1993 doc->file_name))
1994 return FALSE;
1995 bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
1997 else
1999 g_assert_not_reached();
2000 return FALSE;
2002 gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
2003 return TRUE;
2008 * Saves the document.
2009 * Also shows the Save As dialog if necessary.
2010 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2012 * Saving may include replacing tabs with spaces,
2013 * stripping trailing spaces and adding a final new line at the end of the file, depending
2014 * on user preferences. Then the @c "document-before-save" signal is emitted,
2015 * allowing plugins to modify the document before it is saved, and data is
2016 * actually written to disk.
2018 * On successful saving:
2019 * - GeanyDocument::real_path is set.
2020 * - The filetype is set again or auto-detected if it wasn't set yet.
2021 * - The @c "document-save" signal is emitted for plugins.
2023 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
2024 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2025 * added in Geany 1.22.
2027 * @param doc The document to save.
2028 * @param force Whether to save the file even if it is not modified.
2030 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2032 GEANY_API_SYMBOL
2033 gboolean document_save_file(GeanyDocument *doc, gboolean force)
2035 gchar *errmsg;
2036 gchar *data;
2037 gsize len;
2038 gchar *locale_filename;
2039 const GeanyFilePrefs *fp;
2041 g_return_val_if_fail(doc != NULL, FALSE);
2043 if (document_need_save_as(doc))
2045 /* ensure doc is the current tab before showing the dialog */
2046 document_show_tab(doc);
2047 return dialogs_show_save_as();
2050 if (!force && !doc->changed)
2051 return FALSE;
2052 if (doc->readonly)
2054 ui_set_statusbar(TRUE,
2055 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
2056 return FALSE;
2058 document_check_disk_status(doc, TRUE);
2059 if (doc->priv->protected)
2060 return save_file_handle_infobars(doc, force);
2062 fp = project_get_file_prefs();
2063 /* replaces tabs with spaces but only if the current file is not a Makefile */
2064 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
2065 editor_replace_tabs(doc->editor, TRUE);
2066 /* strip trailing spaces */
2067 if (fp->strip_trailing_spaces)
2068 editor_strip_trailing_spaces(doc->editor, TRUE);
2069 /* ensure the file has a newline at the end */
2070 if (fp->final_new_line)
2071 editor_ensure_final_newline(doc->editor);
2072 /* ensure newlines are consistent */
2073 if (fp->ensure_convert_new_lines)
2074 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
2076 /* notify plugins which may wish to modify the document before it's saved */
2077 g_signal_emit_by_name(geany_object, "document-before-save", doc);
2079 len = sci_get_length(doc->editor->sci) + 1;
2080 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
2081 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2082 * encoding, it will be converted to doc->encoding below and this conversion
2083 * also changes the BOM */
2084 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
2085 data[0] = (gchar) 0xef;
2086 data[1] = (gchar) 0xbb;
2087 data[2] = (gchar) 0xbf;
2088 sci_get_text(doc->editor->sci, len, data + 3);
2089 len += 3;
2091 else
2093 data = (gchar*) g_malloc(len);
2094 sci_get_text(doc->editor->sci, len, data);
2097 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2098 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
2099 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
2101 if (! save_convert_to_encoding(doc, &data, &len))
2103 g_free(data);
2104 return FALSE;
2107 else
2109 len = strlen(data);
2112 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2114 /* ignore file changed notification when the file is written */
2115 doc->priv->file_disk_status = FILE_IGNORE;
2117 /* actually write the content of data to the file on disk */
2118 errmsg = save_doc(doc, locale_filename, data, len);
2119 g_free(data);
2121 if (errmsg != NULL)
2123 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2125 if (!file_prefs.use_safe_file_saving)
2127 SETPTR(errmsg,
2128 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2130 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2131 doc->priv->file_disk_status = FILE_OK;
2132 utils_beep();
2133 g_free(locale_filename);
2134 g_free(errmsg);
2135 return FALSE;
2138 /* store the opened encoding for undo/redo */
2139 store_saved_encoding(doc);
2141 /* ignore the following things if we are quitting */
2142 if (! main_status.quitting)
2144 sci_set_savepoint(doc->editor->sci);
2146 if (file_prefs.disk_check_timeout > 0)
2147 document_update_timestamp(doc, locale_filename);
2149 /* update filetype-related things */
2150 document_set_filetype(doc, doc->file_type);
2152 document_update_tab_label(doc);
2154 msgwin_status_add(_("File %s saved."), doc->file_name);
2155 ui_update_statusbar(doc, -1);
2156 #ifdef HAVE_VTE
2157 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2158 #endif
2160 g_free(locale_filename);
2162 g_signal_emit_by_name(geany_object, "document-save", doc);
2164 return TRUE;
2168 /* special search function, used from the find entry in the toolbar
2169 * return TRUE if text was found otherwise FALSE
2170 * return also TRUE if text is empty */
2171 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2172 gboolean backwards)
2174 gint start_pos, search_pos;
2175 struct Sci_TextToFind ttf;
2177 g_return_val_if_fail(text != NULL, FALSE);
2178 g_return_val_if_fail(doc != NULL, FALSE);
2179 if (! *text)
2180 return TRUE;
2182 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2183 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
2185 /* search cursor to end or start */
2186 ttf.chrg.cpMin = start_pos;
2187 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2188 ttf.lpstrText = (gchar *)text;
2189 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2191 /* if no match, search start (or end) to cursor */
2192 if (search_pos == -1)
2194 if (backwards)
2196 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2197 ttf.chrg.cpMax = start_pos;
2199 else
2201 ttf.chrg.cpMin = 0;
2202 ttf.chrg.cpMax = start_pos + strlen(text);
2204 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2207 if (search_pos != -1)
2209 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2211 /* unfold maybe folded results */
2212 sci_ensure_line_is_visible(doc->editor->sci, line);
2214 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2215 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2217 if (! editor_line_in_view(doc->editor, line))
2218 { /* we need to force scrolling in case the cursor is outside of the current visible area
2219 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2220 * while searching */
2221 editor_scroll_to_line(doc->editor, -1, 0.3F);
2223 else
2224 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2225 return TRUE;
2227 else
2229 if (! inc)
2231 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2233 utils_beep();
2234 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2235 return FALSE;
2240 /* General search function, used from the find dialog.
2241 * Returns -1 on failure or the start position of the matching text.
2242 * Will skip past any selection, ignoring it.
2244 * @param text Text to find.
2245 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2247 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2248 GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2249 gboolean scroll, GtkWidget *parent)
2251 gint selection_end, selection_start, search_pos;
2253 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2254 if (! *text)
2255 return -1;
2257 /* Sci doesn't support searching backwards with a regex */
2258 if (flags & GEANY_FIND_REGEXP)
2259 search_backwards = FALSE;
2261 if (!original_text)
2262 original_text = text;
2264 selection_start = sci_get_selection_start(doc->editor->sci);
2265 selection_end = sci_get_selection_end(doc->editor->sci);
2266 if ((selection_end - selection_start) > 0)
2267 { /* there's a selection so go to the end */
2268 if (search_backwards)
2269 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2270 else
2271 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2274 sci_set_search_anchor(doc->editor->sci);
2275 if (search_backwards)
2276 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2277 else
2278 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2280 if (search_pos != -1)
2282 /* unfold maybe folded results */
2283 sci_ensure_line_is_visible(doc->editor->sci,
2284 sci_get_line_from_position(doc->editor->sci, search_pos));
2285 if (scroll)
2286 doc->editor->scroll_percent = 0.3F;
2288 else
2290 gint sci_len = sci_get_length(doc->editor->sci);
2292 /* if we just searched the whole text, give up searching. */
2293 if ((selection_end == 0 && ! search_backwards) ||
2294 (selection_end == sci_len && search_backwards))
2296 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2297 utils_beep();
2298 return -1;
2301 /* we searched only part of the document, so ask whether to wraparound. */
2302 if (search_prefs.always_wrap ||
2303 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2304 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2306 gint ret;
2308 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2309 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2310 if (ret == -1)
2311 { /* return to original cursor position if not found */
2312 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2314 return ret;
2317 return search_pos;
2321 /* Replaces the selection if it matches, otherwise just finds the next match.
2322 * Returns: start of replaced text, or -1 if no replacement was made
2324 * @param find_text Text to find.
2325 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2327 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2328 const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2330 gint selection_end, selection_start, search_pos;
2331 GeanyMatchInfo *match = NULL;
2333 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2335 if (! *find_text)
2336 return -1;
2338 /* Sci doesn't support searching backwards with a regex */
2339 if (flags & GEANY_FIND_REGEXP)
2340 search_backwards = FALSE;
2342 if (!original_find_text)
2343 original_find_text = find_text;
2345 selection_start = sci_get_selection_start(doc->editor->sci);
2346 selection_end = sci_get_selection_end(doc->editor->sci);
2347 if (selection_end == selection_start)
2349 /* no selection so just find the next match */
2350 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2351 return -1;
2353 /* there's a selection so go to the start before finding to search through it
2354 * this ensures there is a match */
2355 if (search_backwards)
2356 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2357 else
2358 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2360 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2361 /* return if the original selected text did not match (at the start of the selection) */
2362 if (search_pos != selection_start)
2364 if (search_pos != -1)
2365 geany_match_info_free(match);
2366 return -1;
2369 if (search_pos != -1)
2371 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2372 /* select the replacement - find text will skip past the selected text */
2373 sci_set_selection_start(doc->editor->sci, search_pos);
2374 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2375 geany_match_info_free(match);
2377 else
2379 /* no match in the selection */
2380 utils_beep();
2382 return search_pos;
2386 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2387 const gchar *original_replace_text)
2389 gchar *filename;
2391 if (count == 0)
2393 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2394 return;
2397 filename = g_path_get_basename(DOC_FILENAME(doc));
2398 ui_set_statusbar(TRUE, ngettext(
2399 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2400 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2401 count), filename, count, original_find_text, original_replace_text);
2402 g_free(filename);
2406 /* Replace all text matches in a certain range within document.
2407 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2408 * or -1 if no text was found.
2409 * scroll_to_match is whether to scroll the last replacement in view (which also
2410 * clears the selection).
2411 * Returns: the number of replacements made. */
2412 static guint
2413 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2414 GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2416 gint count = 0;
2417 struct Sci_TextToFind ttf;
2418 ScintillaObject *sci;
2420 if (new_range_end != NULL)
2421 *new_range_end = -1;
2423 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2425 if (! *find_text || doc->readonly)
2426 return 0;
2428 sci = doc->editor->sci;
2430 ttf.chrg.cpMin = start;
2431 ttf.chrg.cpMax = end;
2432 ttf.lpstrText = (gchar*)find_text;
2434 sci_start_undo_action(sci);
2435 count = search_replace_range(sci, &ttf, flags, replace_text);
2436 sci_end_undo_action(sci);
2438 if (count > 0)
2439 { /* scroll last match in view, will destroy the existing selection */
2440 if (scroll_to_match)
2441 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2443 if (new_range_end != NULL)
2444 *new_range_end = ttf.chrg.cpMax;
2446 return count;
2450 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2451 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2453 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2454 gint max_column = 0, count = 0;
2455 gboolean replaced = FALSE;
2457 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2459 if (! *find_text)
2460 return;
2462 selection_start = sci_get_selection_start(doc->editor->sci);
2463 selection_end = sci_get_selection_end(doc->editor->sci);
2464 /* do we have a selection? */
2465 if ((selection_end - selection_start) == 0)
2467 utils_beep();
2468 return;
2471 selection_mode = sci_get_selection_mode(doc->editor->sci);
2472 selected_lines = sci_get_lines_selected(doc->editor->sci);
2473 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2474 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2476 gint first_line, line;
2478 sci_start_undo_action(doc->editor->sci);
2480 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2481 /* Find the last line with chars selected (not EOL char) */
2482 last_line = sci_get_line_from_position(doc->editor->sci,
2483 selection_end - editor_get_eol_char_len(doc->editor));
2484 last_line = MAX(first_line, last_line);
2485 for (line = first_line; line < (first_line + selected_lines); line++)
2487 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2488 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2490 /* skip line if there is no selection */
2491 if (line_start != INVALID_POSITION)
2493 /* don't let document_replace_range() scroll to match to keep our selection */
2494 gint new_sel_end;
2496 count += document_replace_range(doc, find_text, replace_text, flags,
2497 line_start, line_end, FALSE, &new_sel_end);
2498 if (new_sel_end != -1)
2500 replaced = TRUE;
2501 /* this gets the greatest column within the selection after replacing */
2502 max_column = MAX(max_column,
2503 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2507 sci_end_undo_action(doc->editor->sci);
2509 else /* handle normal line selection */
2511 count += document_replace_range(doc, find_text, replace_text, flags,
2512 selection_start, selection_end, TRUE, &selection_end);
2513 if (selection_end != -1)
2514 replaced = TRUE;
2517 if (replaced)
2518 { /* update the selection for the new endpoint */
2520 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2522 /* now we can scroll to the selection and destroy it because we rebuild it later */
2523 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2525 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2526 * the highest column on the last line. The wrapped selection is completely different
2527 * from the original one, so skip the selection at all */
2528 /* TODO is there a better way to handle the wrapped selection? */
2529 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2530 { /* for keeping and adjusting the selection in multi line rectangle selection we
2531 * need the last line of the original selection and the greatest column number after
2532 * replacing and set the selection end to the last line at the greatest column */
2533 sci_set_selection_start(doc->editor->sci, selection_start);
2534 sci_set_selection_end(doc->editor->sci,
2535 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2536 sci_set_selection_mode(doc->editor->sci, selection_mode);
2539 else
2541 sci_set_selection_start(doc->editor->sci, selection_start);
2542 sci_set_selection_end(doc->editor->sci, selection_end);
2545 else /* no replacements */
2546 utils_beep();
2548 show_replace_summary(doc, count, original_find_text, original_replace_text);
2552 /* returns number of replacements made. */
2553 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2554 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2556 gint len, count;
2557 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2559 if (! *find_text)
2560 return FALSE;
2562 len = sci_get_length(doc->editor->sci);
2563 count = document_replace_range(
2564 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2566 show_replace_summary(doc, count, original_find_text, original_replace_text);
2567 return count;
2572 * Parses or re-parses the document's buffer and updates the type
2573 * keywords and symbol list.
2575 * @param doc The document.
2577 void document_update_tags(GeanyDocument *doc)
2579 guchar *buffer_ptr;
2580 gsize len;
2582 g_return_if_fail(DOC_VALID(doc));
2583 g_return_if_fail(app->tm_workspace != NULL);
2585 /* early out if it's a new file or doesn't support tags */
2586 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2588 /* We must call sidebar_update_tag_list() before returning,
2589 * to ensure that the symbol list is always updated properly (e.g.
2590 * when creating a new document with a partial filename set. */
2591 sidebar_update_tag_list(doc, FALSE);
2592 return;
2595 /* create a new TM file if there isn't one yet */
2596 if (! doc->tm_file)
2598 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2599 const gchar *name;
2601 /* lookup the name rather than using filetype name to support custom filetypes */
2602 name = tm_source_file_get_lang_name(doc->file_type->lang);
2603 doc->tm_file = tm_source_file_new(locale_filename, name);
2604 g_free(locale_filename);
2606 if (doc->tm_file)
2607 tm_workspace_add_source_file_noupdate(doc->tm_file);
2610 /* early out if there's no tm source file and we couldn't create one */
2611 if (doc->tm_file == NULL)
2613 /* We must call sidebar_update_tag_list() before returning,
2614 * to ensure that the symbol list is always updated properly (e.g.
2615 * when creating a new document with a partial filename set. */
2616 sidebar_update_tag_list(doc, FALSE);
2617 return;
2620 /* Parse Scintilla's buffer directly using TagManager
2621 * Note: this buffer *MUST NOT* be modified */
2622 len = sci_get_length(doc->editor->sci);
2623 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2624 tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2626 sidebar_update_tag_list(doc, TRUE);
2627 document_highlight_tags(doc);
2631 /* Re-highlights type keywords without re-parsing the whole document. */
2632 void document_highlight_tags(GeanyDocument *doc)
2634 GString *keywords_str;
2635 gchar *keywords;
2636 gint keyword_idx;
2638 /* some filetypes support type keywords (such as struct names), but not
2639 * necessarily all filetypes for a particular scintilla lexer. this
2640 * tells us whether the filetype supports keywords, and if so
2641 * which index to use for the scintilla keywords set. */
2642 switch (doc->file_type->id)
2644 case GEANY_FILETYPES_C:
2645 case GEANY_FILETYPES_CPP:
2646 case GEANY_FILETYPES_CS:
2647 case GEANY_FILETYPES_D:
2648 case GEANY_FILETYPES_JAVA:
2649 case GEANY_FILETYPES_OBJECTIVEC:
2650 case GEANY_FILETYPES_VALA:
2651 case GEANY_FILETYPES_RUST:
2652 case GEANY_FILETYPES_GO:
2655 /* index of the keyword set in the Scintilla lexer, for
2656 * example in LexCPP.cxx, see "cppWordLists" global array.
2657 * TODO: this magic number should be a member of the filetype */
2658 keyword_idx = 3;
2659 break;
2661 default:
2662 return; /* early out if type keywords are not supported */
2664 if (!app->tm_workspace->tags_array)
2665 return;
2667 /* get any type keywords and tell scintilla about them
2668 * this will cause the type keywords to be colourized in scintilla */
2669 keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2670 if (keywords_str)
2672 keywords = g_string_free(keywords_str, FALSE);
2673 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2674 g_free(keywords);
2675 queue_colourise(doc); /* force re-highlighting the entire document */
2680 static gboolean on_document_update_tag_list_idle(gpointer data)
2682 GeanyDocument *doc = data;
2684 if (! DOC_VALID(doc))
2685 return FALSE;
2687 if (! main_status.quitting)
2688 document_update_tags(doc);
2690 doc->priv->tag_list_update_source = 0;
2692 /* don't update the tags until another modification of the buffer */
2693 return FALSE;
2697 void document_update_tag_list_in_idle(GeanyDocument *doc)
2699 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2700 return;
2702 /* prevent "stacking up" callback handlers, we only need one to run soon */
2703 if (doc->priv->tag_list_update_source != 0)
2704 g_source_remove(doc->priv->tag_list_update_source);
2706 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2707 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2711 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2712 gboolean filetype_changed)
2714 g_return_if_fail(doc);
2715 if (type == NULL)
2716 type = filetypes[GEANY_FILETYPES_NONE];
2718 if (filetype_changed)
2720 doc->file_type = type;
2722 /* delete tm file object to force creation of a new one */
2723 if (doc->tm_file != NULL)
2725 tm_workspace_remove_source_file(doc->tm_file);
2726 tm_source_file_free(doc->tm_file);
2727 doc->tm_file = NULL;
2729 /* load tags files before highlighting (some lexers highlight global typenames) */
2730 if (type->id != GEANY_FILETYPES_NONE)
2731 symbols_global_tags_loaded(type->id);
2733 highlighting_set_styles(doc->editor->sci, type);
2734 editor_set_indentation_guides(doc->editor);
2735 build_menu_update(doc);
2736 queue_colourise(doc);
2737 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2740 document_update_tags(doc);
2744 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2745 * @param doc The document to use.
2746 * @param type The filetype. */
2747 GEANY_API_SYMBOL
2748 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2750 gboolean ft_changed;
2751 GeanyFiletype *old_ft;
2753 g_return_if_fail(doc);
2754 if (type == NULL)
2755 type = filetypes[GEANY_FILETYPES_NONE];
2757 old_ft = doc->file_type;
2758 geany_debug("%s : %s (%s)",
2759 (doc->file_name != NULL) ? doc->file_name : "unknown",
2760 type->name,
2761 (doc->encoding != NULL) ? doc->encoding : "unknown");
2763 ft_changed = (doc->file_type != type); /* filetype has changed */
2764 document_load_config(doc, type, ft_changed);
2766 if (ft_changed)
2768 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2770 /* assume that if previous filetype was none and the settings are the default ones, this
2771 * is the first time the filetype is carefully set, so we should apply indent settings */
2772 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2773 doc->editor->indent_type == iprefs->type &&
2774 doc->editor->indent_width == iprefs->width)
2776 document_apply_indent_settings(doc);
2777 ui_document_show_hide(doc);
2780 sidebar_openfiles_update(doc); /* to update the icon */
2781 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2786 void document_reload_config(GeanyDocument *doc)
2788 document_load_config(doc, doc->file_type, TRUE);
2793 * Sets the encoding of a document.
2794 * This function only set the encoding of the %document, it does not any conversions. The new
2795 * encoding is used when e.g. saving the file.
2797 * @param doc The document to use.
2798 * @param new_encoding The encoding to be set for the document.
2800 GEANY_API_SYMBOL
2801 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2803 if (doc == NULL || new_encoding == NULL ||
2804 utils_str_equal(new_encoding, doc->encoding))
2805 return;
2807 g_free(doc->encoding);
2808 doc->encoding = g_strdup(new_encoding);
2810 ui_update_statusbar(doc, -1);
2811 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2812 encodings_is_unicode_charset(doc->encoding));
2816 /* own Undo / Redo implementation to be able to undo / redo changes
2817 * to the encoding or the Unicode BOM (which are Scintilla independet).
2818 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2820 /* Clears an Undo or Redo buffer. */
2821 void document_undo_clear_stack(GTrashStack **stack)
2823 undo_action *a;
2825 while (g_trash_stack_height(stack) > 0)
2827 a = g_trash_stack_pop(stack);
2828 if (G_LIKELY(a != NULL))
2830 switch (a->type)
2832 case UNDO_ENCODING:
2833 case UNDO_RELOAD:
2834 g_free(a->data); break;
2835 default: break;
2837 g_free(a);
2840 *stack = NULL;
2843 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2844 void document_undo_clear(GeanyDocument *doc)
2846 document_undo_clear_stack(&doc->priv->undo_actions);
2847 document_undo_clear_stack(&doc->priv->redo_actions);
2849 if (! main_status.quitting && doc->editor != NULL)
2850 document_set_text_changed(doc, FALSE);
2854 /* Adds an undo action without clearing the redo stack. This function should
2855 * not be called directly, generally (use document_undo_add() instead), but is
2856 * used by document_redo() in order not to erase the redo stack while moving
2857 * an action from the redo stack to the undo stack. */
2858 void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data)
2860 undo_action *action;
2862 g_return_if_fail(doc != NULL);
2864 action = g_new0(undo_action, 1);
2865 action->type = type;
2866 action->data = data;
2868 g_trash_stack_push(&doc->priv->undo_actions, action);
2870 /* avoid unnecessary redraws */
2871 if (type != UNDO_SCINTILLA || !doc->changed)
2872 document_set_text_changed(doc, TRUE);
2874 ui_update_popup_reundo_items(doc);
2877 /* note: this is called on SCN_MODIFIED notifications */
2878 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2880 /* Clear the redo actions stack before adding the undo action. */
2881 document_undo_clear_stack(&doc->priv->redo_actions);
2883 document_undo_add_internal(doc, type, data);
2887 gboolean document_can_undo(GeanyDocument *doc)
2889 g_return_val_if_fail(doc != NULL, FALSE);
2891 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2892 return TRUE;
2893 else
2894 return FALSE;
2898 static void update_changed_state(GeanyDocument *doc)
2900 doc->changed =
2901 (sci_is_modified(doc->editor->sci) ||
2902 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2903 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2904 document_set_text_changed(doc, doc->changed);
2908 void document_undo(GeanyDocument *doc)
2910 undo_action *action;
2912 g_return_if_fail(doc != NULL);
2914 action = g_trash_stack_pop(&doc->priv->undo_actions);
2916 if (G_UNLIKELY(action == NULL))
2918 /* fallback, should not be necessary */
2919 geany_debug("%s: fallback used", G_STRFUNC);
2920 sci_undo(doc->editor->sci);
2922 else
2924 switch (action->type)
2926 case UNDO_SCINTILLA:
2928 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2930 sci_undo(doc->editor->sci);
2931 break;
2933 case UNDO_BOM:
2935 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2937 doc->has_bom = GPOINTER_TO_INT(action->data);
2938 ui_update_statusbar(doc, -1);
2939 ui_document_show_hide(doc);
2940 break;
2942 case UNDO_ENCODING:
2944 /* use the "old" encoding */
2945 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2947 document_set_encoding(doc, (const gchar*)action->data);
2949 ignore_callback = TRUE;
2950 encodings_select_radio_item((const gchar*)action->data);
2951 ignore_callback = FALSE;
2953 g_free(action->data);
2954 break;
2956 case UNDO_RELOAD:
2958 UndoReloadData *data = (UndoReloadData*)action->data;
2959 gint eol_mode = data->eol_mode;
2960 guint i;
2962 /* We reuse 'data' for the redo action, so read the current EOL mode
2963 * into it before proceeding. */
2964 data->eol_mode = editor_get_eol_char_mode(doc->editor);
2966 /* Undo the rest of the actions which are part of the reloading process. */
2967 for (i = 0; i < data->actions_count; i++)
2968 document_undo(doc);
2970 /* Restore the previous EOL mode. */
2971 sci_set_eol_mode(doc->editor->sci, eol_mode);
2972 /* This might affect the status bar and document menu, so update them. */
2973 ui_update_statusbar(doc, -1);
2974 ui_document_show_hide(doc);
2976 document_redo_add(doc, UNDO_RELOAD, data);
2977 break;
2979 default: break;
2982 g_free(action); /* free the action which was taken from the stack */
2984 update_changed_state(doc);
2985 ui_update_popup_reundo_items(doc);
2989 gboolean document_can_redo(GeanyDocument *doc)
2991 g_return_val_if_fail(doc != NULL, FALSE);
2993 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2994 return TRUE;
2995 else
2996 return FALSE;
3000 void document_redo(GeanyDocument *doc)
3002 undo_action *action;
3004 g_return_if_fail(doc != NULL);
3006 action = g_trash_stack_pop(&doc->priv->redo_actions);
3008 if (G_UNLIKELY(action == NULL))
3010 /* fallback, should not be necessary */
3011 geany_debug("%s: fallback used", G_STRFUNC);
3012 sci_redo(doc->editor->sci);
3014 else
3016 switch (action->type)
3018 case UNDO_SCINTILLA:
3020 document_undo_add_internal(doc, UNDO_SCINTILLA, NULL);
3022 sci_redo(doc->editor->sci);
3023 break;
3025 case UNDO_BOM:
3027 document_undo_add_internal(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3029 doc->has_bom = GPOINTER_TO_INT(action->data);
3030 ui_update_statusbar(doc, -1);
3031 ui_document_show_hide(doc);
3032 break;
3034 case UNDO_ENCODING:
3036 document_undo_add_internal(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3038 document_set_encoding(doc, (const gchar*)action->data);
3040 ignore_callback = TRUE;
3041 encodings_select_radio_item((const gchar*)action->data);
3042 ignore_callback = FALSE;
3044 g_free(action->data);
3045 break;
3047 case UNDO_RELOAD:
3049 UndoReloadData *data = (UndoReloadData*)action->data;
3050 gint eol_mode = data->eol_mode;
3051 guint i;
3053 /* We reuse 'data' for the undo action, so read the current EOL mode
3054 * into it before proceeding. */
3055 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3057 /* Redo the rest of the actions which are part of the reloading process. */
3058 for (i = 0; i < data->actions_count; i++)
3059 document_redo(doc);
3061 /* Restore the previous EOL mode. */
3062 sci_set_eol_mode(doc->editor->sci, eol_mode);
3063 /* This might affect the status bar and document menu, so update them. */
3064 ui_update_statusbar(doc, -1);
3065 ui_document_show_hide(doc);
3067 document_undo_add_internal(doc, UNDO_RELOAD, data);
3068 break;
3070 default: break;
3073 g_free(action); /* free the action which was taken from the stack */
3075 update_changed_state(doc);
3076 ui_update_popup_reundo_items(doc);
3080 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
3082 undo_action *action;
3084 g_return_if_fail(doc != NULL);
3086 action = g_new0(undo_action, 1);
3087 action->type = type;
3088 action->data = data;
3090 g_trash_stack_push(&doc->priv->redo_actions, action);
3092 if (type != UNDO_SCINTILLA || !doc->changed)
3093 document_set_text_changed(doc, TRUE);
3095 ui_update_popup_reundo_items(doc);
3099 enum
3101 STATUS_CHANGED,
3102 STATUS_DISK_CHANGED,
3103 STATUS_READONLY
3106 static struct
3108 const gchar *name;
3109 GdkColor color;
3110 gboolean loaded;
3111 } document_status_styles[] = {
3112 { "geany-document-status-changed", {0}, FALSE },
3113 { "geany-document-status-disk-changed", {0}, FALSE },
3114 { "geany-document-status-readonly", {0}, FALSE }
3118 static gint document_get_status_id(GeanyDocument *doc)
3120 if (doc->changed)
3121 return STATUS_CHANGED;
3122 #ifdef USE_GIO_FILEMON
3123 else if (doc->priv->file_disk_status == FILE_CHANGED)
3124 #else
3125 else if (doc->priv->protected)
3126 #endif
3127 return STATUS_DISK_CHANGED;
3128 else if (doc->readonly)
3129 return STATUS_READONLY;
3131 return -1;
3135 /* returns an identifier that is to be set as a widget name or class to get it styled
3136 * depending on the document status (changed, readonly, etc.)
3137 * a NULL return value means default (unchanged) style */
3138 const gchar *document_get_status_widget_class(GeanyDocument *doc)
3140 gint status;
3142 g_return_val_if_fail(doc != NULL, NULL);
3144 status = document_get_status_id(doc);
3145 if (status < 0)
3146 return NULL;
3147 else
3148 return document_status_styles[status].name;
3153 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
3154 * Returned colors are red if the document has changes, green if the document is read-only
3155 * or simply @c NULL if the document is unmodified but writable.
3157 * @param doc The document to use.
3159 * @return The color for the document or @c NULL if the default color should be used. The color
3160 * object is owned by Geany and should not be modified or freed.
3162 * @since 0.16
3164 GEANY_API_SYMBOL
3165 const GdkColor *document_get_status_color(GeanyDocument *doc)
3167 gint status;
3169 g_return_val_if_fail(doc != NULL, NULL);
3171 status = document_get_status_id(doc);
3172 if (status < 0)
3173 return NULL;
3174 if (! document_status_styles[status].loaded)
3176 #if GTK_CHECK_VERSION(3, 0, 0)
3177 GdkRGBA color;
3178 GtkWidgetPath *path = gtk_widget_path_new();
3179 GtkStyleContext *ctx = gtk_style_context_new();
3180 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3181 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3182 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3183 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3184 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3185 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3186 gtk_style_context_set_path(ctx, path);
3187 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
3188 document_status_styles[status].color.red = 0xffff * color.red;
3189 document_status_styles[status].color.green = 0xffff * color.green;
3190 document_status_styles[status].color.blue = 0xffff * color.blue;
3191 document_status_styles[status].loaded = TRUE;
3192 gtk_widget_path_unref(path);
3193 g_object_unref(ctx);
3194 #else
3195 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3196 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3197 document_status_styles[status].name, NULL);
3198 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3200 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3201 document_status_styles[status].loaded = TRUE;
3202 g_free(path);
3203 #endif
3205 return &document_status_styles[status].color;
3209 /** Accessor function for @ref documents_array items.
3210 * @warning Always check the returned document is valid (@c doc->is_valid).
3211 * @param idx @c documents_array index.
3212 * @return The document, or @c NULL if @a idx is out of range.
3214 * @since 0.16
3216 GEANY_API_SYMBOL
3217 GeanyDocument *document_index(gint idx)
3219 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3223 GeanyDocument *document_clone(GeanyDocument *old_doc)
3225 gchar *text;
3226 GeanyDocument *doc;
3227 ScintillaObject *old_sci;
3229 g_return_val_if_fail(old_doc, NULL);
3230 old_sci = old_doc->editor->sci;
3231 if (sci_has_selection(old_sci))
3232 text = sci_get_selection_contents(old_sci);
3233 else
3234 text = sci_get_contents(old_sci, -1);
3236 doc = document_new_file(NULL, old_doc->file_type, text);
3237 g_free(text);
3238 document_set_text_changed(doc, TRUE);
3240 /* copy file properties */
3241 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3242 doc->editor->line_breaking = old_doc->editor->line_breaking;
3243 doc->editor->auto_indent = old_doc->editor->auto_indent;
3244 editor_set_indent(doc->editor, old_doc->editor->indent_type,
3245 old_doc->editor->indent_width);
3246 doc->readonly = old_doc->readonly;
3247 doc->has_bom = old_doc->has_bom;
3248 doc->priv->protected = 0;
3249 document_set_encoding(doc, old_doc->encoding);
3250 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3251 sci_set_readonly(doc->editor->sci, doc->readonly);
3253 /* update ui */
3254 ui_document_show_hide(doc);
3255 return doc;
3259 /* @note If successful, this should always be followed up with a call to
3260 * document_close_all().
3261 * @return TRUE if all files were saved or had their changes discarded. */
3262 gboolean document_account_for_unsaved(void)
3264 guint i, p, page_count;
3266 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3267 /* iterate over documents in tabs order */
3268 for (p = 0; p < page_count; p++)
3270 GeanyDocument *doc = document_get_from_page(p);
3272 if (DOC_VALID(doc) && doc->changed)
3274 if (! dialogs_show_unsaved_file(doc))
3275 return FALSE;
3278 /* all documents should now be accounted for, so ignore any changes */
3279 foreach_document (i)
3281 documents[i]->changed = FALSE;
3283 return TRUE;
3287 static void force_close_all(void)
3289 guint i, len = documents_array->len;
3291 /* check all documents have been accounted for */
3292 for (i = 0; i < len; i++)
3294 if (documents[i]->is_valid)
3296 g_return_if_fail(!documents[i]->changed);
3299 main_status.closing_all = TRUE;
3301 foreach_document(i)
3303 document_close(documents[i]);
3306 main_status.closing_all = FALSE;
3310 gboolean document_close_all(void)
3312 if (! document_account_for_unsaved())
3313 return FALSE;
3315 force_close_all();
3317 return TRUE;
3321 /* *
3322 * Shows a message related to a document.
3324 * Use this whenever the user needs to see a document-related message,
3325 * for example when the file was externally modified or deleted.
3327 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3328 * @a response_1 response will be the default for the @c GtkInfoBar or
3329 * @c GtkDialog.
3331 * @param doc @c GeanyDocument.
3332 * @param msgtype The type of message.
3333 * @param response_cb A callback function called when there's a response.
3334 * @param btn_1 The first action area button.
3335 * @param response_1 The response for @a btn_1.
3336 * @param btn_2 The second action area button.
3337 * @param response_2 The response for @a btn_2.
3338 * @param btn_3 The third action area button.
3339 * @param response_3 The response for @a btn_3.
3340 * @param extra_text Text to show below the main message.
3341 * @param format The text format for the main message.
3342 * @param ... Used with @a format as in @c printf.
3344 * @since 1.25
3345 * */
3346 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3347 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3348 const gchar *btn_1, GtkResponseType response_1,
3349 const gchar *btn_2, GtkResponseType response_2,
3350 const gchar *btn_3, GtkResponseType response_3,
3351 const gchar *extra_text, const gchar *format, ...)
3353 va_list args;
3354 gchar *text, *markup;
3355 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3356 GtkWidget *info_widget, *parent;
3357 parent = document_get_notebook_child(doc);
3359 va_start(args, format);
3360 text = g_strdup_vprintf(format, args);
3361 va_end(args);
3363 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3364 g_free(text);
3366 info_widget = gtk_info_bar_new();
3367 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3368 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3370 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3372 if (btn_1)
3373 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3374 if (btn_2)
3375 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3376 if (btn_3)
3377 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3379 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3381 label = geany_wrap_label_new(NULL);
3382 gtk_label_set_markup(GTK_LABEL(label), markup);
3383 g_free(markup);
3385 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3387 hbox = gtk_hbox_new(FALSE, 12);
3388 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3390 switch (msgtype)
3392 case GTK_MESSAGE_INFO:
3393 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3394 break;
3395 case GTK_MESSAGE_WARNING:
3396 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3397 break;
3398 case GTK_MESSAGE_QUESTION:
3399 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3400 break;
3401 case GTK_MESSAGE_ERROR:
3402 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3403 break;
3404 default:
3405 icon = NULL;
3406 break;
3409 if (icon)
3410 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3412 if (extra_text)
3414 vbox = gtk_vbox_new(FALSE, 6);
3415 extra_label = geany_wrap_label_new(extra_text);
3416 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3417 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3418 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3420 else
3421 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3423 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3425 gtk_widget_show_all(info_widget);
3427 return info_widget;
3431 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3433 gboolean close = FALSE;
3435 // disable info bar so actions complete normally
3436 unprotect_document(doc);
3437 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3439 if (response_id == RESPONSE_DOCUMENT_RELOAD)
3441 close = doc->changed ?
3442 document_reload_prompt(doc, doc->encoding) :
3443 document_reload_force(doc, doc->encoding);
3445 else if (response_id == RESPONSE_DOCUMENT_SAVE)
3447 close = document_save_file(doc, TRUE); // force overwrite
3449 else if (response_id == GTK_RESPONSE_CANCEL)
3451 document_set_text_changed(doc, TRUE);
3452 close = TRUE;
3454 if (!close)
3456 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3457 protect_document(doc);
3458 return;
3460 gtk_widget_destroy(bar);
3464 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3466 GtkInfoBar *bar = GTK_INFO_BAR(data);
3468 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3470 switch (event->keyval)
3472 case GDK_Tab:
3473 case GDK_ISO_Left_Tab:
3475 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3476 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3477 gtk_widget_child_focus(action_area, dir);
3478 return TRUE;
3480 case GDK_Escape:
3482 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3483 return TRUE;
3485 default:
3486 return FALSE;
3491 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3492 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3494 /* automatically focus editor again on bar close */
3495 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3496 G_CONNECT_SWAPPED);
3497 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3501 static void monitor_reload_file(GeanyDocument *doc)
3503 gchar *base_name = g_path_get_basename(doc->file_name);
3505 /* show this message only once */
3506 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3508 GtkWidget *bar;
3510 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3511 _("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3512 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3513 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3514 _("Do you want to reload it?"),
3515 _("The file '%s' on the disk is more recent than the current buffer."),
3516 base_name);
3518 protect_document(doc);
3519 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3520 enable_key_intercept(doc, bar);
3522 g_free(base_name);
3526 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3527 gint response_id,
3528 GeanyDocument *doc)
3530 gboolean close = TRUE;
3532 unprotect_document(doc);
3534 if (response_id == RESPONSE_DOCUMENT_SAVE)
3535 close = dialogs_show_save_as();
3537 if (close)
3539 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3540 gtk_widget_destroy(bar);
3542 else
3544 /* protect back the document if save didn't occur */
3545 protect_document(doc);
3550 static void monitor_resave_missing_file(GeanyDocument *doc)
3552 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3554 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3556 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3557 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3559 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3560 on_monitor_resave_missing_file_response,
3561 GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3562 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3563 NULL, GTK_RESPONSE_NONE,
3564 _("Try to resave the file?"),
3565 _("File \"%s\" was not found on disk!"),
3566 doc->file_name);
3568 protect_document(doc);
3569 document_set_text_changed(doc, TRUE);
3570 /* don't prompt more than once */
3571 SETPTR(doc->real_path, NULL);
3572 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3573 enable_key_intercept(doc, bar);
3578 /* Set force to force a disk check, otherwise it is ignored if there was a check
3579 * in the last file_prefs.disk_check_timeout seconds.
3580 * @return @c TRUE if the file has changed. */
3581 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3583 gboolean ret = FALSE;
3584 gboolean use_gio_filemon;
3585 time_t cur_time = 0;
3586 struct stat st;
3587 gchar *locale_filename;
3588 FileDiskStatus old_status;
3590 g_return_val_if_fail(doc != NULL, FALSE);
3592 /* ignore remote files and documents that have never been saved to disk */
3593 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3594 || doc->real_path == NULL || doc->priv->is_remote)
3595 return FALSE;
3597 use_gio_filemon = (doc->priv->monitor != NULL);
3599 if (use_gio_filemon)
3601 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3602 return FALSE;
3604 else
3606 cur_time = time(NULL);
3607 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3608 return FALSE;
3610 doc->priv->last_check = cur_time;
3613 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3614 if (g_stat(locale_filename, &st) != 0)
3616 monitor_resave_missing_file(doc);
3617 /* doc may be closed now */
3618 ret = TRUE;
3620 else if (! use_gio_filemon && /* ignore check when using GIO */
3621 doc->priv->mtime > cur_time)
3623 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3624 /* Note: on Windows st.st_mtime can be newer than cur_time */
3626 else if (doc->priv->mtime < st.st_mtime)
3628 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3629 doc->priv->mtime = st.st_mtime;
3630 monitor_reload_file(doc);
3631 /* doc may be closed now */
3632 ret = TRUE;
3634 g_free(locale_filename);
3636 if (DOC_VALID(doc))
3637 { /* doc can get invalid when a document was closed */
3638 old_status = doc->priv->file_disk_status;
3639 doc->priv->file_disk_status = FILE_OK;
3640 if (old_status != doc->priv->file_disk_status)
3641 ui_update_tab_status(doc);
3643 return ret;
3647 /** Compares documents by their display names.
3648 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3649 * @note 'Display name' means the base name of the document's filename.
3651 * @param a @c GeanyDocument**.
3652 * @param b @c GeanyDocument**.
3653 * @warning The arguments take the address of each document pointer.
3654 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3656 * @since 0.21
3658 GEANY_API_SYMBOL
3659 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3661 GeanyDocument *doc_a = *((GeanyDocument**) a);
3662 GeanyDocument *doc_b = *((GeanyDocument**) b);
3663 gchar *base_name_a, *base_name_b;
3664 gint result;
3666 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3667 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3669 result = strcmp(base_name_a, base_name_b);
3671 g_free(base_name_a);
3672 g_free(base_name_b);
3674 return result;
3678 /** Compares documents by their tab order.
3679 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3681 * @param a @c GeanyDocument**.
3682 * @param b @c GeanyDocument**.
3683 * @warning The arguments take the address of each document pointer.
3684 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3686 * @since 0.21 (GEANY_API_VERSION 209)
3688 GEANY_API_SYMBOL
3689 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3691 GeanyDocument *doc_a = *((GeanyDocument**) a);
3692 GeanyDocument *doc_b = *((GeanyDocument**) b);
3693 gint notebook_position_doc_a;
3694 gint notebook_position_doc_b;
3696 notebook_position_doc_a = document_get_notebook_page(doc_a);
3697 notebook_position_doc_b = document_get_notebook_page(doc_b);
3699 if (notebook_position_doc_a < notebook_position_doc_b)
3700 return -1;
3701 if (notebook_position_doc_a > notebook_position_doc_b)
3702 return 1;
3703 /* equality */
3704 return 0;
3708 /** Compares documents by their tab order, in reverse order.
3709 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3711 * @param a @c GeanyDocument**.
3712 * @param b @c GeanyDocument**.
3713 * @warning The arguments take the address of each document pointer.
3714 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3716 * @since 0.21 (GEANY_API_VERSION 209)
3718 GEANY_API_SYMBOL
3719 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3721 return -1 * document_compare_by_tab_order(a, b);
3725 void document_grab_focus(GeanyDocument *doc)
3727 g_return_if_fail(doc != NULL);
3729 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));