Merge pull request #621 from techee/remote_mtime
[geany-mirror.git] / src / document.c
blobef863392bc5cc0e1ce0f2ba5402421ae54a738ae
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>
84 #define USE_GIO_FILE_OPERATIONS (!file_prefs.use_safe_file_saving && file_prefs.use_gio_unsafe_file_saving)
87 GeanyFilePrefs file_prefs;
90 /** Dynamic array of GeanyDocument pointers.
91 * Once a pointer is added to this, it is never freed. This means the same document pointer
92 * can represent a different document later on, or it may have been closed and become invalid.
93 * For this reason, you should use document_find_by_id() instead of storing
94 * document pointers over time if there is a chance the user can close the
95 * document.
97 * @warning You must check @c GeanyDocument::is_valid when iterating over this array.
98 * This is done automatically if you use the foreach_document() macro.
100 * @note
101 * Never assume that the order of document pointers is the same as the order of notebook tabs.
102 * One reason is that notebook tabs can be reordered.
103 * Use @c document_get_from_page() to lookup a document from a notebook tab number.
105 * @see documents. */
106 GPtrArray *documents_array = NULL;
109 /* an undo action, also used for redo actions */
110 typedef struct
112 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
113 guint type; /* to identify the action */
114 gpointer *data; /* the old value (before the change), in case of a redo action
115 * it contains the new value */
116 } undo_action;
118 /* Custom document info bar response IDs */
119 enum
121 RESPONSE_DOCUMENT_RELOAD = 1,
122 RESPONSE_DOCUMENT_SAVE,
126 static guint doc_id_counter = 0;
129 static void document_undo_clear_stack(GTrashStack **stack);
130 static void document_undo_clear(GeanyDocument *doc);
131 static void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data);
132 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
133 static gboolean remove_page(guint page_num);
134 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
135 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
136 const gchar *btn_1, GtkResponseType response_1,
137 const gchar *btn_2, GtkResponseType response_2,
138 const gchar *btn_3, GtkResponseType response_3,
139 const gchar *extra_text, const gchar *format, ...) G_GNUC_PRINTF(11, 12);
143 * Finds a document whose @c real_path field matches the given filename.
145 * @param realname The filename to search, which should be identical to the
146 * string returned by @c tm_get_real_path().
148 * @return The matching document, or @c NULL.
149 * @note This is only really useful when passing a @c TMSourceFile::file_name.
150 * @see GeanyDocument::real_path.
151 * @see document_find_by_filename().
153 * @since 0.15
155 GEANY_API_SYMBOL
156 GeanyDocument* document_find_by_real_path(const gchar *realname)
158 guint i;
160 if (! realname)
161 return NULL; /* file doesn't exist on disk */
163 for (i = 0; i < documents_array->len; i++)
165 GeanyDocument *doc = documents[i];
167 if (! doc->is_valid || ! doc->real_path)
168 continue;
170 if (utils_filenamecmp(realname, doc->real_path) == 0)
172 return doc;
175 return NULL;
179 /* dereference symlinks, /../ junk in path and return locale encoding */
180 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
182 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
183 gchar *realname = tm_get_real_path(locale_name);
185 g_free(locale_name);
186 return realname;
191 * Finds a document with the given filename.
192 * This matches either an exact GeanyDocument::file_name string, or variant
193 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
194 * match @c "/name").
196 * @param utf8_filename The filename to search (in UTF-8 encoding).
198 * @return The matching document, or @c NULL.
199 * @see document_find_by_real_path().
201 GEANY_API_SYMBOL
202 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
204 guint i;
205 GeanyDocument *doc;
206 gchar *realname;
208 g_return_val_if_fail(utf8_filename != NULL, NULL);
210 /* First search GeanyDocument::file_name, so we can find documents with a
211 * filename set but not saved on disk, like vcdiff produces */
212 for (i = 0; i < documents_array->len; i++)
214 doc = documents[i];
216 if (! doc->is_valid || doc->file_name == NULL)
217 continue;
219 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
221 return doc;
224 /* Now try matching based on the realpath(), which is unique per file on disk */
225 realname = get_real_path_from_utf8(utf8_filename);
226 doc = document_find_by_real_path(realname);
227 g_free(realname);
228 return doc;
232 /* returns the document which has sci, or NULL. */
233 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
235 guint i;
237 g_return_val_if_fail(sci != NULL, NULL);
239 for (i = 0; i < documents_array->len; i++)
241 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
242 return documents[i];
244 return NULL;
248 /** Lookup an old document by its ID.
249 * Useful when the corresponding document may have been closed since the
250 * ID was retrieved.
251 * @param id The ID of the document to find
252 * @return @c NULL if the document is no longer open.
254 * Example:
255 * @code
256 * static guint id;
257 * GeanyDocument *doc = ...;
258 * id = doc->id; // store ID
259 * ...
260 * // time passes - the document may have been closed by now
261 * GeanyDocument *doc = document_find_by_id(id);
262 * gboolean still_open = (doc != NULL);
263 * @endcode
264 * @since 1.25. */
265 GEANY_API_SYMBOL
266 GeanyDocument *document_find_by_id(guint id)
268 guint i;
270 if (!id)
271 return NULL;
273 foreach_document(i)
275 if (documents[i]->id == id)
276 return documents[i];
278 return NULL;
282 /* gets the widget the main_widgets.notebook consider is its child for this document */
283 static GtkWidget *document_get_notebook_child(GeanyDocument *doc)
285 GtkWidget *parent;
286 GtkWidget *child;
288 g_return_val_if_fail(doc != NULL, NULL);
290 child = GTK_WIDGET(doc->editor->sci);
291 parent = gtk_widget_get_parent(child);
292 /* search for the direct notebook child, mirroring document_get_from_page() */
293 while (parent && ! GTK_IS_NOTEBOOK(parent))
295 child = parent;
296 parent = gtk_widget_get_parent(child);
299 return child;
303 /** Gets the notebook page index for a document.
304 * @param doc The document.
305 * @return The index.
306 * @since 0.19 */
307 GEANY_API_SYMBOL
308 gint document_get_notebook_page(GeanyDocument *doc)
310 GtkWidget *child = document_get_notebook_child(doc);
312 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook), child);
317 * Recursively searches a containers children until it finds a
318 * Scintilla widget, or NULL if one was not found.
320 static ScintillaObject *locate_sci_in_container(GtkWidget *container)
322 ScintillaObject *sci = NULL;
323 GList *children, *iter;
325 g_return_val_if_fail(GTK_IS_CONTAINER(container), NULL);
327 children = gtk_container_get_children(GTK_CONTAINER(container));
328 for (iter = children; iter != NULL; iter = g_list_next(iter))
330 if (IS_SCINTILLA(iter->data))
332 sci = SCINTILLA(iter->data);
333 break;
335 else if (GTK_IS_CONTAINER(iter->data))
337 sci = locate_sci_in_container(iter->data);
338 if (IS_SCINTILLA(sci))
339 break;
340 sci = NULL;
343 g_list_free(children);
345 return sci;
349 /* Finds the document for the given notebook page widget */
350 GeanyDocument *document_get_from_notebook_child(GtkWidget *page)
352 ScintillaObject *sci;
354 g_return_val_if_fail(GTK_IS_BOX(page), NULL);
356 sci = locate_sci_in_container(page);
357 g_return_val_if_fail(IS_SCINTILLA(sci), NULL);
359 return document_find_by_sci(sci);
364 * Finds the document for the given notebook page @a page_num.
366 * @param page_num The notebook page number to search.
368 * @return The corresponding document for the given notebook page, or @c NULL.
370 GEANY_API_SYMBOL
371 GeanyDocument *document_get_from_page(guint page_num)
373 GtkWidget *parent;
375 if (page_num >= documents_array->len)
376 return NULL;
378 parent = gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
380 return document_get_from_notebook_child(parent);
385 * Finds the current document.
387 * @return A pointer to the current document or @c NULL if there are no opened documents.
389 GEANY_API_SYMBOL
390 GeanyDocument *document_get_current(void)
392 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
394 if (cur_page == -1)
395 return NULL;
396 else
397 return document_get_from_page((guint) cur_page);
401 void document_init_doclist(void)
403 documents_array = g_ptr_array_new();
407 void document_finalize(void)
409 guint i;
411 for (i = 0; i < documents_array->len; i++)
412 g_free(documents[i]);
413 g_ptr_array_free(documents_array, TRUE);
418 * Returns the last part of the filename of the given GeanyDocument. The result is also
419 * truncated to a maximum of @a length characters in case the filename is very long.
421 * @param doc The document to use.
422 * @param length The length of the resulting string or -1 to use a default value.
424 * @return The ellipsized last part of the filename of @a doc, should be freed when no
425 * longer needed.
427 * @since 0.17
429 /* TODO make more use of this */
430 GEANY_API_SYMBOL
431 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
433 gchar *base_name, *short_name;
435 g_return_val_if_fail(doc != NULL, NULL);
437 if (length < 0)
438 length = 30;
440 base_name = g_path_get_basename(DOC_FILENAME(doc));
441 short_name = utils_str_middle_truncate(base_name, (guint)length);
443 g_free(base_name);
445 return short_name;
449 void document_update_tab_label(GeanyDocument *doc)
451 gchar *short_name;
452 GtkWidget *parent;
454 g_return_if_fail(doc != NULL);
456 short_name = document_get_basename_for_display(doc, -1);
458 /* we need to use the event box for the tooltip, labels don't get the necessary events */
459 parent = gtk_widget_get_parent(doc->priv->tab_label);
460 parent = gtk_widget_get_parent(parent);
462 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
464 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
466 g_free(short_name);
471 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
472 * according to the document's save state.
473 * This is called by Geany mostly when opening or saving files.
475 * @param doc The document to use.
476 * @param changed Whether the document state should indicate changes have been made.
478 GEANY_API_SYMBOL
479 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
481 g_return_if_fail(doc != NULL);
483 doc->changed = changed;
485 if (! main_status.quitting)
487 ui_update_tab_status(doc);
488 ui_save_buttons_toggle(changed);
489 ui_set_window_title(doc);
490 ui_update_statusbar(doc, -1);
495 /* returns the next free place in the document list,
496 * or -1 if the documents_array is full */
497 static gint document_get_new_idx(void)
499 guint i;
501 for (i = 0; i < documents_array->len; i++)
503 if (documents[i]->editor == NULL)
505 return (gint) i;
508 return -1;
512 static void queue_colourise(GeanyDocument *doc)
514 /* Colourise the editor before it is next drawn */
515 doc->priv->colourise_needed = TRUE;
517 /* If the editor doesn't need drawing (e.g. after saving the current
518 * document), we need to force a redraw, so the expose event is triggered.
519 * This ensures we don't start colourising before all documents are opened/saved,
520 * only once the editor is drawn. */
521 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
525 #ifdef USE_GIO_FILEMON
526 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
527 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
528 GeanyDocument *doc)
530 g_return_if_fail(doc != NULL);
532 if (file_prefs.disk_check_timeout == 0)
533 return;
535 geany_debug("%s: event: %d previous file status: %d",
536 G_STRFUNC, event, doc->priv->file_disk_status);
537 switch (event)
539 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
541 if (doc->priv->file_disk_status == FILE_IGNORE)
542 doc->priv->file_disk_status = FILE_OK;
543 else
544 doc->priv->file_disk_status = FILE_CHANGED;
545 g_message("%s: FILE_CHANGED", G_STRFUNC);
546 break;
548 case G_FILE_MONITOR_EVENT_DELETED:
550 doc->priv->file_disk_status = FILE_CHANGED;
551 g_message("%s: FILE_MISSING", G_STRFUNC);
552 break;
554 default:
555 break;
557 if (doc->priv->file_disk_status != FILE_OK)
559 ui_update_tab_status(doc);
562 #endif
565 static void document_stop_file_monitoring(GeanyDocument *doc)
567 g_return_if_fail(doc != NULL);
569 if (doc->priv->monitor != NULL)
571 g_object_unref(doc->priv->monitor);
572 doc->priv->monitor = NULL;
577 static void monitor_file_setup(GeanyDocument *doc)
579 g_return_if_fail(doc != NULL);
580 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
581 * doesn't work at all for remote files and legacy polling is too slow. */
582 if (! doc->priv->is_remote)
584 #ifdef USE_GIO_FILEMON
585 gchar *locale_filename;
587 /* stop any previous monitoring */
588 document_stop_file_monitoring(doc);
590 locale_filename = utils_get_locale_from_utf8(doc->file_name);
591 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
593 /* get a file monitor and connect to the 'changed' signal */
594 GFile *file = g_file_new_for_path(locale_filename);
595 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
596 g_signal_connect(doc->priv->monitor, "changed",
597 G_CALLBACK(monitor_file_changed_cb), doc);
599 /* we set the rate limit according to the GUI pref but it's most probably not used */
600 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
602 g_object_unref(file);
604 g_free(locale_filename);
605 #endif
607 doc->priv->file_disk_status = FILE_OK;
611 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
613 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
614 if (DOC_VALID(doc))
616 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
617 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
619 if (source_widget == NULL)
620 source_widget = doc->priv->tag_tree;
622 if (focusw == source_widget)
623 gtk_widget_grab_focus(sci);
628 static gboolean on_idle_focus(gpointer doc)
630 document_try_focus(doc, NULL);
631 return FALSE;
635 /* Creates a new document and editor, adding a tab in the notebook.
636 * @return The created document */
637 static GeanyDocument *document_create(const gchar *utf8_filename)
639 GeanyDocument *doc;
640 gint new_idx;
641 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
643 if (cur_pages == 1)
645 doc = document_get_current();
646 /* remove the empty document first */
647 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
648 /* prevent immediately opening another new doc with
649 * new_document_after_close pref */
650 remove_page(0);
653 new_idx = document_get_new_idx();
654 if (new_idx == -1) /* expand the array, no free places */
656 doc = g_new0(GeanyDocument, 1);
658 new_idx = documents_array->len;
659 g_ptr_array_add(documents_array, doc);
662 doc = documents[new_idx];
664 /* initialize default document settings */
665 doc->priv = g_new0(GeanyDocumentPrivate, 1);
666 doc->id = ++doc_id_counter;
667 doc->index = new_idx;
668 doc->file_name = g_strdup(utf8_filename);
669 doc->editor = editor_create(doc);
670 #ifndef USE_GIO_FILEMON
671 doc->priv->last_check = time(NULL);
672 #endif
674 sidebar_openfiles_add(doc); /* sets doc->iter */
676 notebook_new_tab(doc);
678 /* select document in sidebar */
680 GtkTreeSelection *sel;
682 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
683 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
686 ui_document_buttons_update();
688 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
689 return doc;
694 * Closes the given document.
696 * @param doc The document to remove.
698 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
700 * @since 0.15
702 GEANY_API_SYMBOL
703 gboolean document_close(GeanyDocument *doc)
705 g_return_val_if_fail(doc, FALSE);
707 return document_remove_page(document_get_notebook_page(doc));
711 /* Call document_remove_page() instead, this is only needed for document_create()
712 * to prevent re-opening a new document when the last document is closed (if enabled). */
713 static gboolean remove_page(guint page_num)
715 GeanyDocument *doc = document_get_from_page(page_num);
717 g_return_val_if_fail(doc != NULL, FALSE);
719 if (doc->changed && ! dialogs_show_unsaved_file(doc))
720 return FALSE;
722 /* tell any plugins that the document is about to be closed */
723 g_signal_emit_by_name(geany_object, "document-close", doc);
725 /* Checking real_path makes it likely the file exists on disk */
726 if (! main_status.closing_all && doc->real_path != NULL)
727 ui_add_recent_document(doc);
729 doc->is_valid = FALSE;
730 doc->id = 0;
732 if (main_status.quitting)
734 /* we need to destroy the ScintillaWidget so our handlers on it are
735 * disconnected before we free any data they may use (like the editor).
736 * when not quitting, this is handled by removing the notebook page. */
737 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets.notebook), page_num);
739 else
741 notebook_remove_page(page_num);
742 sidebar_remove_document(doc);
743 navqueue_remove_file(doc->file_name);
744 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
746 g_free(doc->encoding);
747 g_free(doc->priv->saved_encoding.encoding);
748 g_free(doc->file_name);
749 g_free(doc->real_path);
750 if (doc->tm_file)
752 tm_workspace_remove_source_file(doc->tm_file);
753 tm_source_file_free(doc->tm_file);
756 if (doc->priv->tag_tree)
757 gtk_widget_destroy(doc->priv->tag_tree);
759 editor_destroy(doc->editor);
760 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
762 document_stop_file_monitoring(doc);
764 document_undo_clear(doc);
766 g_free(doc->priv);
768 /* reset document settings to defaults for re-use */
769 memset(doc, 0, sizeof(GeanyDocument));
771 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
773 sidebar_update_tag_list(NULL, FALSE);
774 ui_set_window_title(NULL);
775 ui_save_buttons_toggle(FALSE);
776 ui_update_popup_reundo_items(NULL);
777 ui_document_buttons_update();
778 build_menu_update(NULL);
780 return TRUE;
785 * Removes the given notebook tab at @a page_num and clears all related information
786 * in the document list.
788 * @param page_num The notebook page number to remove.
790 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
792 GEANY_API_SYMBOL
793 gboolean document_remove_page(guint page_num)
795 gboolean done = remove_page(page_num);
797 if (done && ui_prefs.new_document_after_close)
798 document_new_file_if_non_open();
800 return done;
804 /* used to keep a record of the unchanged document state encoding */
805 static void store_saved_encoding(GeanyDocument *doc)
807 g_free(doc->priv->saved_encoding.encoding);
808 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
809 doc->priv->saved_encoding.has_bom = doc->has_bom;
813 /* Opens a new empty document only if there are no other documents open */
814 GeanyDocument *document_new_file_if_non_open(void)
816 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
817 return document_new_file(NULL, NULL, NULL);
819 return NULL;
824 * Creates a new document.
825 * Line endings in @a text will be converted to the default setting.
826 * Afterwards, the @c "document-new" signal is emitted for plugins.
828 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
829 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
830 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
832 * @return The new document.
834 GEANY_API_SYMBOL
835 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
837 GeanyDocument *doc;
839 if (utf8_filename && g_path_is_absolute(utf8_filename))
841 gchar *tmp;
842 tmp = utils_strdupa(utf8_filename); /* work around const */
843 utils_tidy_path(tmp);
844 utf8_filename = tmp;
846 doc = document_create(utf8_filename);
848 g_assert(doc != NULL);
850 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
851 if (text)
853 GString *template = g_string_new(text);
854 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
856 sci_set_text(doc->editor->sci, template->str);
857 g_string_free(template, TRUE);
859 else
860 sci_clear_all(doc->editor->sci);
862 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
864 sci_set_undo_collection(doc->editor->sci, TRUE);
865 sci_empty_undo_buffer(doc->editor->sci);
867 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
868 /* store the opened encoding for undo/redo */
869 store_saved_encoding(doc);
871 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
872 ft = filetypes_detect_from_document(doc);
874 document_set_filetype(doc, ft); /* also re-parses tags */
876 /* now the document is fully ready, display it (see notebook_new_tab()) */
877 gtk_widget_show(document_get_notebook_child(doc));
879 ui_set_window_title(doc);
880 build_menu_update(doc);
881 document_set_text_changed(doc, FALSE);
882 ui_document_show_hide(doc); /* update the document menu */
884 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
885 /* bring it in front, jump to the start and grab the focus */
886 editor_goto_pos(doc->editor, 0, FALSE);
887 document_try_focus(doc, NULL);
889 #ifdef USE_GIO_FILEMON
890 monitor_file_setup(doc);
891 #else
892 doc->priv->mtime = 0;
893 #endif
895 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
896 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
898 g_signal_emit_by_name(geany_object, "document-new", doc);
900 msgwin_status_add(_("New file \"%s\" opened."),
901 DOC_FILENAME(doc));
903 return doc;
908 * Opens a document specified by @a locale_filename.
909 * Afterwards, the @c "document-open" signal is emitted for plugins.
911 * @param locale_filename The filename of the document to load, in locale encoding.
912 * @param readonly Whether to open the document in read-only mode.
913 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
914 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
916 * @return The document opened or @c NULL.
918 GEANY_API_SYMBOL
919 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
920 GeanyFiletype *ft, const gchar *forced_enc)
922 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
926 typedef struct
928 gchar *data; /* null-terminated file data */
929 gsize len; /* string length of data */
930 gchar *enc;
931 gboolean bom;
932 time_t mtime; /* modification time, read by stat::st_mtime */
933 gboolean readonly;
934 } FileData;
937 static gboolean get_mtime(const gchar *locale_filename, time_t *time)
939 GError *error = NULL;
940 const gchar *err_msg = NULL;
942 if (USE_GIO_FILE_OPERATIONS)
944 GFile *file = g_file_new_for_path(locale_filename);
945 GFileInfo *info = g_file_query_info(file, G_FILE_ATTRIBUTE_TIME_MODIFIED, G_FILE_QUERY_INFO_NONE, NULL, &error);
947 if (info)
949 GTimeVal timeval;
951 g_file_info_get_modification_time(info, &timeval);
952 g_object_unref(info);
953 *time = timeval.tv_sec;
955 else if (error)
956 err_msg = error->message;
958 g_object_unref(file);
960 else
962 GStatBuf st;
964 if (g_stat(locale_filename, &st) == 0)
965 *time = st.st_mtime;
966 else
967 err_msg = g_strerror(errno);
970 if (err_msg)
972 gchar *utf8_filename = utils_get_utf8_from_locale(locale_filename);
974 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
975 utf8_filename, err_msg);
976 g_free(utf8_filename);
979 if (error)
980 g_error_free(error);
982 return err_msg == NULL;
986 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
987 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
988 FileData *filedata, const gchar *forced_enc)
990 GError *err = NULL;
992 filedata->data = NULL;
993 filedata->len = 0;
994 filedata->enc = NULL;
995 filedata->bom = FALSE;
996 filedata->readonly = FALSE;
998 if (!get_mtime(locale_filename, &filedata->mtime))
999 return FALSE;
1001 if (USE_GIO_FILE_OPERATIONS)
1003 GFile *file = g_file_new_for_path(locale_filename);
1005 g_file_load_contents(file, NULL, &filedata->data, &filedata->len, NULL, &err);
1006 g_object_unref(file);
1008 else
1009 g_file_get_contents(locale_filename, &filedata->data, &filedata->len, &err);
1011 if (err)
1013 ui_set_statusbar(TRUE, "%s", err->message);
1014 g_error_free(err);
1015 return FALSE;
1018 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
1019 &filedata->enc, &filedata->bom, &filedata->readonly))
1021 if (forced_enc)
1023 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1024 display_filename, forced_enc);
1026 else
1028 ui_set_statusbar(TRUE,
1029 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1030 display_filename);
1032 g_free(filedata->data);
1033 return FALSE;
1036 if (filedata->readonly)
1038 const gchar *warn_msg = _(
1039 "The file \"%s\" could not be opened properly and has been truncated. " \
1040 "This can occur if the file contains a NULL byte. " \
1041 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1043 if (main_status.main_window_realized)
1044 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
1046 ui_set_statusbar(TRUE, warn_msg, display_filename);
1049 return TRUE;
1053 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1054 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1055 * if cl_options.goto_column is set.
1057 * returns the new position which may have changed */
1058 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1060 if (cl_options.goto_line >= 0)
1061 { /* goto line which was specified on command line and then undefine the line */
1062 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1063 editor->scroll_percent = 0.5F;
1064 cl_options.goto_line = -1;
1066 else if (pos > 0)
1068 sci_set_current_position(editor->sci, pos, FALSE);
1069 editor->scroll_percent = 0.5F;
1072 if (cl_options.goto_column >= 0)
1073 { /* goto column which was specified on command line and then undefine the column */
1075 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1076 sci_set_current_position(editor->sci, new_pos, FALSE);
1077 editor->scroll_percent = 0.5F;
1078 cl_options.goto_column = -1;
1079 return new_pos;
1081 return sci_get_current_position(editor->sci);
1085 /* Count lines that start with some hard tabs then a soft tab. */
1086 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1088 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1089 ScintillaObject *sci = editor->sci;
1090 gsize count = 0;
1091 struct Sci_TextToFind ttf;
1092 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
1093 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1095 g_free(soft_tab);
1097 ttf.chrg.cpMin = 0;
1098 ttf.chrg.cpMax = sci_get_length(sci);
1099 ttf.lpstrText = regex;
1100 while (1)
1102 gint pos;
1104 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1105 if (pos == -1)
1106 break; /* no more matches */
1107 count++;
1108 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1110 g_free(regex);
1111 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1112 return count > sci_get_line_count(sci) * 0.02;
1116 /* Detect the indent type based on counting the leading indent characters for each line.
1117 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1118 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
1120 GeanyEditor *editor = doc->editor;
1121 ScintillaObject *sci = editor->sci;
1122 gint line, line_count;
1123 gsize tabs = 0, spaces = 0;
1125 if (detect_tabs_and_spaces(editor))
1127 *type_ = GEANY_INDENT_TYPE_BOTH;
1128 return TRUE;
1131 line_count = sci_get_line_count(sci);
1132 for (line = 0; line < line_count; line++)
1134 gint pos = sci_get_position_from_line(sci, line);
1135 gchar c;
1137 /* most code will have indent total <= 24, otherwise it's more likely to be
1138 * alignment than indentation */
1139 if (sci_get_line_indentation(sci, line) > 24)
1140 continue;
1142 c = sci_get_char_at(sci, pos);
1143 if (c == '\t')
1144 tabs++;
1145 /* check for at least 2 spaces */
1146 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
1147 spaces++;
1149 if (spaces == 0 && tabs == 0)
1150 return FALSE;
1152 /* the factors may need to be tweaked */
1153 if (spaces > tabs * 4)
1154 *type_ = GEANY_INDENT_TYPE_SPACES;
1155 else if (tabs > spaces * 4)
1156 *type_ = GEANY_INDENT_TYPE_TABS;
1157 else
1158 *type_ = GEANY_INDENT_TYPE_BOTH;
1160 return TRUE;
1164 /* Detect the indent width based on counting the leading indent characters for each line.
1165 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1166 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
1168 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1169 ScintillaObject *sci = editor->sci;
1170 gint line, line_count;
1171 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
1172 gint count, width, i;
1174 /* can't easily detect the supposed width of a tab, guess the default is OK */
1175 if (type == GEANY_INDENT_TYPE_TABS)
1176 return FALSE;
1178 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1179 sci_set_tab_width(sci, 8);
1181 line_count = sci_get_line_count(sci);
1182 for (line = 0; line < line_count; line++)
1184 gint pos = sci_get_line_indent_position(sci, line);
1186 /* We probably don't have style info yet, because we're generally called just after
1187 * the document got created, so we can't use highlighting_is_code_style().
1188 * That's not good, but the assumption below that concerning lines start with an
1189 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1190 * without removing too much legitimate lines. */
1191 if (sci_get_char_at(sci, pos) == '*')
1192 continue;
1194 width = sci_get_line_indentation(sci, line);
1195 /* most code will have indent total <= 24, otherwise it's more likely to be
1196 * alignment than indentation */
1197 if (width > 24)
1198 continue;
1199 /* < 2 is no indentation */
1200 if (width < 2)
1201 continue;
1203 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1205 if ((width % (i + 2)) == 0)
1206 widths[i]++;
1209 count = 0;
1210 width = iprefs->width;
1211 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
1213 /* give large indents higher weight not to be fooled by spurious indents */
1214 if (widths[i] >= count * 1.5)
1216 width = i + 2;
1217 count = widths[i];
1221 if (count == 0)
1222 return FALSE;
1224 *width_ = width;
1225 return TRUE;
1229 /* same as detect_indent_width() but uses editor's indent type */
1230 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1232 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1236 void document_apply_indent_settings(GeanyDocument *doc)
1238 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1239 GeanyIndentType type = iprefs->type;
1240 gint width = iprefs->width;
1242 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1244 if (type != iprefs->type)
1246 const gchar *name = NULL;
1248 switch (type)
1250 case GEANY_INDENT_TYPE_SPACES:
1251 name = _("Spaces");
1252 break;
1253 case GEANY_INDENT_TYPE_TABS:
1254 name = _("Tabs");
1255 break;
1256 case GEANY_INDENT_TYPE_BOTH:
1257 name = _("Tabs and Spaces");
1258 break;
1260 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1261 * and Spaces), the second one is the filename */
1262 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1263 DOC_FILENAME(doc));
1266 else if (doc->file_type->indent_type > -1)
1267 type = doc->file_type->indent_type;
1269 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1271 if (width != iprefs->width)
1273 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1274 DOC_FILENAME(doc));
1277 else if (doc->file_type->indent_width > -1)
1278 width = doc->file_type->indent_width;
1280 editor_set_indent(doc->editor, type, width);
1284 void document_show_tab(GeanyDocument *doc)
1286 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1287 document_get_notebook_page(doc));
1291 /* To open a new file, set doc to NULL; filename should be locale encoded.
1292 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1293 * pos is the cursor position, which can be overridden by --line and --column.
1294 * forced_enc can be NULL to detect the file encoding.
1295 * Returns: doc of the opened file or NULL if an error occurred. */
1296 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1297 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1299 gint editor_mode;
1300 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1301 gchar *utf8_filename = NULL;
1302 gchar *display_filename = NULL;
1303 gchar *locale_filename = NULL;
1304 GeanyFiletype *use_ft;
1305 FileData filedata;
1306 UndoReloadData *undo_reload_data;
1307 gboolean add_undo_reload_action;
1309 g_return_val_if_fail(doc == NULL || doc->is_valid, NULL);
1311 if (reload)
1313 utf8_filename = g_strdup(doc->file_name);
1314 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1316 else
1318 /* filename must not be NULL when opening a file */
1319 g_return_val_if_fail(filename, NULL);
1321 #ifdef G_OS_WIN32
1322 /* if filename is a shortcut, try to resolve it */
1323 locale_filename = win32_get_shortcut_target(filename);
1324 #else
1325 locale_filename = g_strdup(filename);
1326 #endif
1327 /* remove relative junk */
1328 utils_tidy_path(locale_filename);
1330 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1331 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1333 /* if file is already open, switch to it and go */
1334 doc = document_find_by_filename(utf8_filename);
1335 if (doc != NULL)
1337 ui_add_recent_document(doc); /* either add or reorder recent item */
1338 /* show the doc before reload dialog */
1339 document_show_tab(doc);
1340 document_check_disk_status(doc, TRUE); /* force a file changed check */
1343 if (reload || doc == NULL)
1344 { /* doc possibly changed */
1345 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1347 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1349 g_free(display_filename);
1350 g_free(utf8_filename);
1351 g_free(locale_filename);
1352 return NULL;
1355 if (! reload)
1357 doc = document_create(utf8_filename);
1358 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1360 /* file exists on disk, set real_path */
1361 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1363 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1364 monitor_file_setup(doc);
1367 if (! reload || ! file_prefs.keep_edit_history_on_reload)
1369 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1370 sci_empty_undo_buffer(doc->editor->sci);
1371 undo_reload_data = NULL;
1373 else
1375 undo_reload_data = (UndoReloadData*) g_malloc(sizeof(UndoReloadData));
1377 /* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1378 * this reload. To do that, we keep collecting undo actions during
1379 * reloading, and at the end add an UNDO_RELOAD action that performs
1380 * all these actions in bulk. To keep track of how many undo actions
1381 * were added during this time, we compare the current undo-stack height
1382 * with its height at the end of the process. Note that g_trash_stack_height()
1383 * is O(N), which is a little ugly, but this seems like the most maintainable
1384 * option. */
1385 undo_reload_data->actions_count = g_trash_stack_height(&doc->priv->undo_actions);
1387 /* We use add_undo_reload_action to track any changes to the document that
1388 * require adding an undo action to revert the reload, but that do not
1389 * generate an undo action themselves. */
1390 add_undo_reload_action = FALSE;
1393 /* add the text to the ScintillaObject */
1394 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1395 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1396 queue_colourise(doc); /* Ensure the document gets colourised. */
1398 /* detect & set line endings */
1399 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1400 if (undo_reload_data)
1402 undo_reload_data->eol_mode = editor_get_eol_char_mode(doc->editor);
1403 /* Force adding an undo-reload action if the EOL mode changed. */
1404 if (editor_mode != undo_reload_data->eol_mode)
1405 add_undo_reload_action = TRUE;
1407 sci_set_eol_mode(doc->editor->sci, editor_mode);
1408 g_free(filedata.data);
1410 sci_set_undo_collection(doc->editor->sci, TRUE);
1412 /* If reloading and the current and new encodings or BOM states differ,
1413 * add appropriate undo actions. */
1414 if (undo_reload_data)
1416 if (! utils_str_equal(doc->encoding, filedata.enc))
1417 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
1418 if (doc->has_bom != filedata.bom)
1419 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
1422 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1423 g_free(doc->encoding); /* if reloading, free old encoding */
1424 doc->encoding = filedata.enc;
1425 doc->has_bom = filedata.bom;
1426 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1428 doc->readonly = readonly || filedata.readonly;
1429 sci_set_readonly(doc->editor->sci, doc->readonly);
1430 doc->priv->protected = 0;
1432 /* update line number margin width */
1433 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1434 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin);
1436 if (! reload)
1439 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1440 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1441 doc->editor);
1443 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1445 else
1446 { /* reloading */
1447 if (undo_reload_data)
1449 /* Calculate the number of undo actions that are part of the reloading
1450 * process, and add the UNDO_RELOAD action. */
1451 undo_reload_data->actions_count =
1452 g_trash_stack_height(&doc->priv->undo_actions) - undo_reload_data->actions_count;
1454 /* We only add an undo-reload action if the document has actually changed.
1455 * At the time of writing, this condition is moot because sci_set_text
1456 * generates an undo action even when the text hasn't really changed, so
1457 * actions_count is always greater than zero. In the future this might change.
1458 * It's arguable whether we should add an undo-reload action unconditionally,
1459 * especially since it's possible (if unlikely) that there had only
1460 * been "invisible" changes to the document, such as changes in encoding and
1461 * EOL mode, but for the time being that's how we roll. */
1462 if (undo_reload_data->actions_count > 0 || add_undo_reload_action)
1463 document_undo_add(doc, UNDO_RELOAD, undo_reload_data);
1464 else
1465 g_free(undo_reload_data);
1467 /* We didn't save the document per-se, but its contents are now
1468 * synchronized with the file on disk, hence set a save point here.
1469 * We need to do this in this case only, because we don't clear
1470 * Scintilla's undo stack. */
1471 sci_set_savepoint(doc->editor->sci);
1473 else
1474 document_undo_clear(doc);
1476 use_ft = ft;
1478 /* update taglist, typedef keywords and build menu if necessary */
1479 document_set_filetype(doc, use_ft);
1481 /* set indentation settings after setting the filetype */
1482 if (reload)
1483 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1484 else
1485 document_apply_indent_settings(doc);
1487 document_set_text_changed(doc, FALSE); /* also updates tab state */
1488 ui_document_show_hide(doc); /* update the document menu */
1490 /* finally add current file to recent files menu, but not the files from the last session */
1491 if (! main_status.opening_session_files)
1492 ui_add_recent_document(doc);
1494 if (reload)
1496 g_signal_emit_by_name(geany_object, "document-reload", doc);
1497 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1499 else
1501 g_signal_emit_by_name(geany_object, "document-open", doc);
1502 /* For translators: this is the status window message for opening a file. %d is the number
1503 * of the newly opened file, %s indicates whether the file is opened read-only
1504 * (it is replaced with the string ", read-only"). */
1505 msgwin_status_add(_("File %s opened(%d%s)."),
1506 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1507 (readonly) ? _(", read-only") : "");
1510 /* now the document is fully ready, display it (see notebook_new_tab()) */
1511 gtk_widget_show(document_get_notebook_child(doc));
1514 g_free(display_filename);
1515 g_free(utf8_filename);
1516 g_free(locale_filename);
1518 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1519 pos = set_cursor_position(doc->editor, pos);
1520 /* now bring the file in front */
1521 editor_goto_pos(doc->editor, pos, FALSE);
1523 /* finally, let the editor widget grab the focus so you can start coding
1524 * right away */
1525 g_idle_add(on_idle_focus, doc);
1526 return doc;
1530 /* Takes a new line separated list of filename URIs and opens each file.
1531 * length is the length of the string */
1532 void document_open_file_list(const gchar *data, gsize length)
1534 guint i;
1535 gchar *filename;
1536 gchar **list;
1538 g_return_if_fail(data != NULL);
1540 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1542 /* stop at the end or first empty item, because last item is empty but not null */
1543 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1545 filename = utils_get_path_from_uri(list[i]);
1546 if (filename == NULL)
1547 continue;
1548 document_open_file(filename, FALSE, NULL, NULL);
1549 g_free(filename);
1552 g_strfreev(list);
1557 * Opens each file in the list @a filenames.
1558 * Internally, document_open_file() is called for every list item.
1560 * @param filenames A list of filenames to load, in locale encoding.
1561 * @param readonly Whether to open the document in read-only mode.
1562 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1563 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1565 GEANY_API_SYMBOL
1566 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1567 const gchar *forced_enc)
1569 const GSList *item;
1571 for (item = filenames; item != NULL; item = g_slist_next(item))
1573 document_open_file(item->data, readonly, ft, forced_enc);
1579 * Reloads the document with the specified file encoding.
1580 * @a forced_enc or @c NULL to auto-detect the file encoding.
1582 * @param doc The document to reload.
1583 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1585 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1587 GEANY_API_SYMBOL
1588 gboolean document_reload_force(GeanyDocument *doc, const gchar *forced_enc)
1590 gint pos = 0;
1591 GeanyDocument *new_doc;
1593 g_return_val_if_fail(doc != NULL, FALSE);
1595 /* Use cancel because the response handler would call this recursively */
1596 if (doc->priv->info_bars[MSG_TYPE_RELOAD] != NULL)
1597 gtk_info_bar_response(GTK_INFO_BAR(doc->priv->info_bars[MSG_TYPE_RELOAD]), GTK_RESPONSE_CANCEL);
1599 /* try to set the cursor to the position before reloading */
1600 pos = sci_get_current_position(doc->editor->sci);
1601 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1603 return (new_doc != NULL);
1607 /* also used for reloading when forced_enc is NULL */
1608 gboolean document_reload_prompt(GeanyDocument *doc, const gchar *forced_enc)
1610 gchar *base_name;
1611 gboolean prompt, result = FALSE;
1613 g_return_val_if_fail(doc != NULL, FALSE);
1615 /* No need to reload "untitled" (non-file-backed) documents */
1616 if (doc->file_name == NULL)
1617 return FALSE;
1619 if (forced_enc == NULL)
1620 forced_enc = doc->encoding;
1622 base_name = g_path_get_basename(doc->file_name);
1623 /* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1624 prompt = !file_prefs.keep_edit_history_on_reload &&
1625 (doc->changed || (document_can_undo(doc) || document_can_redo(doc)));
1627 if (!prompt || dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
1628 doc->changed ? _("Any unsaved changes will be lost.") :
1629 _("Undo history will be lost."),
1630 _("Are you sure you want to reload '%s'?"), base_name))
1632 result = document_reload_force(doc, forced_enc);
1633 if (forced_enc != NULL)
1634 ui_update_statusbar(doc, -1);
1636 g_free(base_name);
1637 return result;
1641 static void document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1643 #ifndef USE_GIO_FILEMON
1644 g_return_if_fail(doc != NULL);
1646 get_mtime(locale_filename, &doc->priv->mtime); /* get the modification time from file and keep it */
1647 #endif
1651 /* Sets line and column to the given position byte_pos in the document.
1652 * byte_pos is the position counted in bytes, not characters */
1653 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1655 gint i;
1656 gint line_start;
1658 /* for some reason we can use byte count instead of character count here */
1659 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1660 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1661 /* get the column in the line */
1662 *column = byte_pos - line_start;
1664 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1665 * skip one byte(i++) and decrease the column number which is based on byte count */
1666 for (i = line_start; i < (line_start + *column); i++)
1668 if (sci_get_char_at(doc->editor->sci, i) < 0)
1670 (*column)--;
1671 i++;
1677 static void replace_header_filename(GeanyDocument *doc)
1679 gchar *filebase;
1680 gchar *filename;
1681 struct Sci_TextToFind ttf;
1683 g_return_if_fail(doc != NULL);
1684 g_return_if_fail(doc->file_type != NULL);
1686 filebase = g_regex_escape_string(GEANY_STRING_UNTITLED, -1);
1687 if (doc->file_type->extension)
1688 SETPTR(filebase, g_strconcat("\\b", filebase, "\\.\\w+", NULL));
1689 else
1690 SETPTR(filebase, g_strconcat("\\b", filebase, "\\b", NULL));
1692 filename = g_path_get_basename(doc->file_name);
1694 /* only search the first 3 lines */
1695 ttf.chrg.cpMin = 0;
1696 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 4);
1697 ttf.lpstrText = filebase;
1699 if (search_find_text(doc->editor->sci, GEANY_FIND_MATCHCASE | GEANY_FIND_REGEXP, &ttf, NULL) != -1)
1701 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1702 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1703 sci_replace_target(doc->editor->sci, filename, FALSE);
1705 g_free(filebase);
1706 g_free(filename);
1711 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1712 * you still have to call @ref document_save_file_as() to change the @a doc object.
1713 * It also stops monitoring for file changes to prevent receiving too many file change events
1714 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1716 * @param doc The current document which should be renamed.
1717 * @param new_filename The new filename in UTF-8 encoding.
1719 * @since 0.16
1721 GEANY_API_SYMBOL
1722 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1724 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1725 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1726 gint result;
1728 /* stop file monitoring to avoid getting events for deleting/creating files,
1729 * it's re-setup in document_save_file_as() */
1730 document_stop_file_monitoring(doc);
1732 result = g_rename(old_locale_filename, new_locale_filename);
1733 if (result != 0)
1735 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1736 _("Error renaming file."), g_strerror(errno));
1738 g_free(old_locale_filename);
1739 g_free(new_locale_filename);
1743 static void protect_document(GeanyDocument *doc)
1745 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1746 if (!doc->priv->protected++)
1747 sci_set_readonly(doc->editor->sci, TRUE);
1749 ui_update_tab_status(doc);
1753 static void unprotect_document(GeanyDocument *doc)
1755 g_return_if_fail(doc->priv->protected > 0);
1757 if (!--doc->priv->protected && doc->readonly == FALSE)
1758 sci_set_readonly(doc->editor->sci, FALSE);
1760 ui_update_tab_status(doc);
1764 /* Return TRUE if the document doesn't have a full filename set.
1765 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1766 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1767 * new files. */
1768 gboolean document_need_save_as(GeanyDocument *doc)
1770 g_return_val_if_fail(doc != NULL, FALSE);
1772 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1777 * Saves the document, detecting the filetype.
1779 * @param doc The document for the file to save.
1780 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1781 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1783 * @see document_save_file().
1785 * @since 0.16
1787 GEANY_API_SYMBOL
1788 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1790 gboolean ret;
1791 gboolean new_file;
1793 g_return_val_if_fail(doc != NULL, FALSE);
1795 new_file = document_need_save_as(doc) || (utf8_fname != NULL && strcmp(doc->file_name, utf8_fname) != 0);
1796 if (utf8_fname != NULL)
1797 SETPTR(doc->file_name, g_strdup(utf8_fname));
1799 /* reset real path, it's retrieved again in document_save() */
1800 SETPTR(doc->real_path, NULL);
1802 /* detect filetype */
1803 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1805 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1807 document_set_filetype(doc, ft);
1808 if (document_get_current() == doc)
1810 ignore_callback = TRUE;
1811 filetypes_select_radio_item(doc->file_type);
1812 ignore_callback = FALSE;
1816 if (new_file)
1818 // assume user wants to throw away read-only setting
1819 sci_set_readonly(doc->editor->sci, FALSE);
1820 doc->readonly = FALSE;
1821 if (doc->priv->protected > 0)
1822 unprotect_document(doc);
1825 replace_header_filename(doc);
1827 ret = document_save_file(doc, TRUE);
1829 /* file monitoring support, add file monitoring after the file has been saved
1830 * to ignore any earlier events */
1831 monitor_file_setup(doc);
1832 doc->priv->file_disk_status = FILE_IGNORE;
1834 if (ret)
1835 ui_add_recent_document(doc);
1836 return ret;
1840 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1842 GError *conv_error = NULL;
1843 gchar* conv_file_contents = NULL;
1844 gsize bytes_read;
1845 gsize conv_len;
1847 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1848 g_return_val_if_fail(len != NULL, FALSE);
1850 /* try to convert it from UTF-8 to original encoding */
1851 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1852 &bytes_read, &conv_len, &conv_error);
1854 if (conv_error != NULL)
1856 gchar *text = g_strdup_printf(
1857 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1858 doc->encoding);
1859 gchar *error_text;
1861 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1863 gint line, column;
1864 gint context_len;
1865 gunichar unic;
1866 /* don't read over the doc length */
1867 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1868 gchar context[7]; /* read 6 bytes from Sci + '\0' */
1869 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1871 /* take only one valid Unicode character from the context and discard the leftover */
1872 unic = g_utf8_get_char_validated(context, -1);
1873 context_len = g_unichar_to_utf8(unic, context);
1874 context[context_len] = '\0';
1875 get_line_column_from_pos(doc, bytes_read, &line, &column);
1877 error_text = g_strdup_printf(
1878 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1879 conv_error->message, context, line + 1, column);
1881 else
1882 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1884 geany_debug("encoding error: %s", conv_error->message);
1885 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1886 g_error_free(conv_error);
1887 g_free(text);
1888 g_free(error_text);
1889 return FALSE;
1891 else
1893 g_free(*data);
1894 *data = conv_file_contents;
1895 *len = conv_len;
1897 return TRUE;
1901 static gchar *write_data_to_disk(const gchar *locale_filename,
1902 const gchar *data, gsize len)
1904 GError *error = NULL;
1906 if (file_prefs.use_safe_file_saving)
1908 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1909 * This is the only option that handles disk space exhaustion. */
1910 if (g_file_set_contents(locale_filename, data, len, &error))
1911 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1913 else if (USE_GIO_FILE_OPERATIONS)
1915 GFile *fp;
1917 /* Use GIO API to save file (GVFS-safe)
1918 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1919 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1920 fp = g_file_new_for_path(locale_filename);
1921 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1922 G_FILE_CREATE_NONE, NULL, NULL, &error);
1923 g_object_unref(fp);
1925 else
1927 FILE *fp;
1928 int save_errno;
1929 gchar *display_name = g_filename_display_name(locale_filename);
1931 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1932 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1933 errno = 0;
1934 fp = g_fopen(locale_filename, "wb");
1935 if (fp == NULL)
1937 save_errno = errno;
1939 g_set_error(&error,
1940 G_FILE_ERROR,
1941 g_file_error_from_errno(save_errno),
1942 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1943 display_name,
1944 g_strerror(save_errno));
1946 else
1948 gsize bytes_written;
1950 errno = 0;
1951 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1953 if (len != bytes_written)
1955 save_errno = errno;
1957 g_set_error(&error,
1958 G_FILE_ERROR,
1959 g_file_error_from_errno(save_errno),
1960 _("Failed to write file '%s': fwrite() failed: %s"),
1961 display_name,
1962 g_strerror(save_errno));
1965 errno = 0;
1966 /* preserve the fwrite() error if any */
1967 if (fclose(fp) != 0 && error == NULL)
1969 save_errno = errno;
1971 g_set_error(&error,
1972 G_FILE_ERROR,
1973 g_file_error_from_errno(save_errno),
1974 _("Failed to close file '%s': fclose() failed: %s"),
1975 display_name,
1976 g_strerror(save_errno));
1980 g_free(display_name);
1982 if (error != NULL)
1984 gchar *msg = g_strdup(error->message);
1985 g_error_free(error);
1986 /* geany will warn about file truncation for unsafe saving below */
1987 return msg;
1989 return NULL;
1993 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1994 const gchar *data, gsize len)
1996 gchar *err;
1998 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1999 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
2001 err = write_data_to_disk(locale_filename, data, len);
2002 if (err)
2003 return err;
2005 /* now the file is on disk, set real_path */
2006 if (doc->real_path == NULL)
2008 doc->real_path = tm_get_real_path(locale_filename);
2009 doc->priv->is_remote = utils_is_remote_path(locale_filename);
2010 monitor_file_setup(doc);
2012 return NULL;
2016 static gboolean save_file_handle_infobars(GeanyDocument *doc, gboolean force)
2018 GtkWidget *bar = NULL;
2020 document_show_tab(doc);
2022 if (doc->priv->info_bars[MSG_TYPE_RELOAD])
2024 if (!dialogs_show_question_full(NULL, _("_Overwrite"), GTK_STOCK_CANCEL,
2025 _("Overwrite?"),
2026 _("The file '%s' on the disk is more recent than the current buffer."),
2027 doc->file_name))
2028 return FALSE;
2029 bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
2031 else if (doc->priv->info_bars[MSG_TYPE_RESAVE])
2033 if (!dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
2034 _("Try to resave the file?"),
2035 _("File \"%s\" was not found on disk!"),
2036 doc->file_name))
2037 return FALSE;
2038 bar = doc->priv->info_bars[MSG_TYPE_RESAVE];
2040 else
2042 g_assert_not_reached();
2043 return FALSE;
2045 gtk_info_bar_response(GTK_INFO_BAR(bar), RESPONSE_DOCUMENT_SAVE);
2046 return TRUE;
2051 * Saves the document.
2052 * Also shows the Save As dialog if necessary.
2053 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2055 * Saving may include replacing tabs with spaces,
2056 * stripping trailing spaces and adding a final new line at the end of the file, depending
2057 * on user preferences. Then the @c "document-before-save" signal is emitted,
2058 * allowing plugins to modify the document before it is saved, and data is
2059 * actually written to disk.
2061 * On successful saving:
2062 * - GeanyDocument::real_path is set.
2063 * - The filetype is set again or auto-detected if it wasn't set yet.
2064 * - The @c "document-save" signal is emitted for plugins.
2066 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
2067 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2068 * added in Geany 1.22.
2070 * @param doc The document to save.
2071 * @param force Whether to save the file even if it is not modified.
2073 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2075 GEANY_API_SYMBOL
2076 gboolean document_save_file(GeanyDocument *doc, gboolean force)
2078 gchar *errmsg;
2079 gchar *data;
2080 gsize len;
2081 gchar *locale_filename;
2082 const GeanyFilePrefs *fp;
2084 g_return_val_if_fail(doc != NULL, FALSE);
2086 if (document_need_save_as(doc))
2088 /* ensure doc is the current tab before showing the dialog */
2089 document_show_tab(doc);
2090 return dialogs_show_save_as();
2093 if (!force && !doc->changed)
2094 return FALSE;
2095 if (doc->readonly)
2097 ui_set_statusbar(TRUE,
2098 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc));
2099 return FALSE;
2101 document_check_disk_status(doc, TRUE);
2102 if (doc->priv->protected)
2103 return save_file_handle_infobars(doc, force);
2105 fp = project_get_file_prefs();
2106 /* replaces tabs with spaces but only if the current file is not a Makefile */
2107 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
2108 editor_replace_tabs(doc->editor, TRUE);
2109 /* strip trailing spaces */
2110 if (fp->strip_trailing_spaces)
2111 editor_strip_trailing_spaces(doc->editor, TRUE);
2112 /* ensure the file has a newline at the end */
2113 if (fp->final_new_line)
2114 editor_ensure_final_newline(doc->editor);
2115 /* ensure newlines are consistent */
2116 if (fp->ensure_convert_new_lines)
2117 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
2119 /* notify plugins which may wish to modify the document before it's saved */
2120 g_signal_emit_by_name(geany_object, "document-before-save", doc);
2122 len = sci_get_length(doc->editor->sci) + 1;
2123 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
2124 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2125 * encoding, it will be converted to doc->encoding below and this conversion
2126 * also changes the BOM */
2127 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
2128 data[0] = (gchar) 0xef;
2129 data[1] = (gchar) 0xbb;
2130 data[2] = (gchar) 0xbf;
2131 sci_get_text(doc->editor->sci, len, data + 3);
2132 len += 3;
2134 else
2136 data = (gchar*) g_malloc(len);
2137 sci_get_text(doc->editor->sci, len, data);
2140 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2141 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
2142 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
2144 if (! save_convert_to_encoding(doc, &data, &len))
2146 g_free(data);
2147 return FALSE;
2150 else
2152 len = strlen(data);
2155 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2157 /* ignore file changed notification when the file is written */
2158 doc->priv->file_disk_status = FILE_IGNORE;
2160 /* actually write the content of data to the file on disk */
2161 errmsg = save_doc(doc, locale_filename, data, len);
2162 g_free(data);
2164 if (errmsg != NULL)
2166 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
2168 if (!file_prefs.use_safe_file_saving)
2170 SETPTR(errmsg,
2171 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
2173 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
2174 doc->priv->file_disk_status = FILE_OK;
2175 utils_beep();
2176 g_free(locale_filename);
2177 g_free(errmsg);
2178 return FALSE;
2181 /* store the opened encoding for undo/redo */
2182 store_saved_encoding(doc);
2184 /* ignore the following things if we are quitting */
2185 if (! main_status.quitting)
2187 sci_set_savepoint(doc->editor->sci);
2189 if (file_prefs.disk_check_timeout > 0)
2190 document_update_timestamp(doc, locale_filename);
2192 /* update filetype-related things */
2193 document_set_filetype(doc, doc->file_type);
2195 document_update_tab_label(doc);
2197 msgwin_status_add(_("File %s saved."), doc->file_name);
2198 ui_update_statusbar(doc, -1);
2199 #ifdef HAVE_VTE
2200 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
2201 #endif
2203 g_free(locale_filename);
2205 g_signal_emit_by_name(geany_object, "document-save", doc);
2207 return TRUE;
2211 /* special search function, used from the find entry in the toolbar
2212 * return TRUE if text was found otherwise FALSE
2213 * return also TRUE if text is empty */
2214 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gboolean inc,
2215 gboolean backwards)
2217 gint start_pos, search_pos;
2218 struct Sci_TextToFind ttf;
2220 g_return_val_if_fail(text != NULL, FALSE);
2221 g_return_val_if_fail(doc != NULL, FALSE);
2222 if (! *text)
2223 return TRUE;
2225 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
2226 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
2228 /* search cursor to end or start */
2229 ttf.chrg.cpMin = start_pos;
2230 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
2231 ttf.lpstrText = (gchar *)text;
2232 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2234 /* if no match, search start (or end) to cursor */
2235 if (search_pos == -1)
2237 if (backwards)
2239 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
2240 ttf.chrg.cpMax = start_pos;
2242 else
2244 ttf.chrg.cpMin = 0;
2245 ttf.chrg.cpMax = start_pos + strlen(text);
2247 search_pos = sci_find_text(doc->editor->sci, 0, &ttf);
2250 if (search_pos != -1)
2252 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
2254 /* unfold maybe folded results */
2255 sci_ensure_line_is_visible(doc->editor->sci, line);
2257 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
2258 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
2260 if (! editor_line_in_view(doc->editor, line))
2261 { /* we need to force scrolling in case the cursor is outside of the current visible area
2262 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2263 * while searching */
2264 editor_scroll_to_line(doc->editor, -1, 0.3F);
2266 else
2267 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
2268 return TRUE;
2270 else
2272 if (! inc)
2274 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
2276 utils_beep();
2277 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
2278 return FALSE;
2283 /* General search function, used from the find dialog.
2284 * Returns -1 on failure or the start position of the matching text.
2285 * Will skip past any selection, ignoring it.
2287 * @param text Text to find.
2288 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2290 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
2291 GeanyFindFlags flags, gboolean search_backwards, GeanyMatchInfo **match_,
2292 gboolean scroll, GtkWidget *parent)
2294 gint selection_end, selection_start, search_pos;
2296 g_return_val_if_fail(doc != NULL && text != NULL, -1);
2297 if (! *text)
2298 return -1;
2300 /* Sci doesn't support searching backwards with a regex */
2301 if (flags & GEANY_FIND_REGEXP)
2302 search_backwards = FALSE;
2304 if (!original_text)
2305 original_text = text;
2307 selection_start = sci_get_selection_start(doc->editor->sci);
2308 selection_end = sci_get_selection_end(doc->editor->sci);
2309 if ((selection_end - selection_start) > 0)
2310 { /* there's a selection so go to the end */
2311 if (search_backwards)
2312 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2313 else
2314 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2317 sci_set_search_anchor(doc->editor->sci);
2318 if (search_backwards)
2319 search_pos = search_find_prev(doc->editor->sci, text, flags, match_);
2320 else
2321 search_pos = search_find_next(doc->editor->sci, text, flags, match_);
2323 if (search_pos != -1)
2325 /* unfold maybe folded results */
2326 sci_ensure_line_is_visible(doc->editor->sci,
2327 sci_get_line_from_position(doc->editor->sci, search_pos));
2328 if (scroll)
2329 doc->editor->scroll_percent = 0.3F;
2331 else
2333 gint sci_len = sci_get_length(doc->editor->sci);
2335 /* if we just searched the whole text, give up searching. */
2336 if ((selection_end == 0 && ! search_backwards) ||
2337 (selection_end == sci_len && search_backwards))
2339 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
2340 utils_beep();
2341 return -1;
2344 /* we searched only part of the document, so ask whether to wraparound. */
2345 if (search_prefs.always_wrap ||
2346 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
2347 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
2349 gint ret;
2351 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
2352 ret = document_find_text(doc, text, original_text, flags, search_backwards, match_, scroll, parent);
2353 if (ret == -1)
2354 { /* return to original cursor position if not found */
2355 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
2357 return ret;
2360 return search_pos;
2364 /* Replaces the selection if it matches, otherwise just finds the next match.
2365 * Returns: start of replaced text, or -1 if no replacement was made
2367 * @param find_text Text to find.
2368 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2370 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
2371 const gchar *replace_text, GeanyFindFlags flags, gboolean search_backwards)
2373 gint selection_end, selection_start, search_pos;
2374 GeanyMatchInfo *match = NULL;
2376 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2378 if (! *find_text)
2379 return -1;
2381 /* Sci doesn't support searching backwards with a regex */
2382 if (flags & GEANY_FIND_REGEXP)
2383 search_backwards = FALSE;
2385 if (!original_find_text)
2386 original_find_text = find_text;
2388 selection_start = sci_get_selection_start(doc->editor->sci);
2389 selection_end = sci_get_selection_end(doc->editor->sci);
2390 if (selection_end == selection_start)
2392 /* no selection so just find the next match */
2393 document_find_text(doc, find_text, original_find_text, flags, search_backwards, NULL, TRUE, NULL);
2394 return -1;
2396 /* there's a selection so go to the start before finding to search through it
2397 * this ensures there is a match */
2398 if (search_backwards)
2399 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2400 else
2401 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2403 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, &match, TRUE, NULL);
2404 /* return if the original selected text did not match (at the start of the selection) */
2405 if (search_pos != selection_start)
2407 if (search_pos != -1)
2408 geany_match_info_free(match);
2409 return -1;
2412 if (search_pos != -1)
2414 gint replace_len = search_replace_match(doc->editor->sci, match, replace_text);
2415 /* select the replacement - find text will skip past the selected text */
2416 sci_set_selection_start(doc->editor->sci, search_pos);
2417 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2418 geany_match_info_free(match);
2420 else
2422 /* no match in the selection */
2423 utils_beep();
2425 return search_pos;
2429 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2430 const gchar *original_replace_text)
2432 gchar *filename;
2434 if (count == 0)
2436 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2437 return;
2440 filename = g_path_get_basename(DOC_FILENAME(doc));
2441 ui_set_statusbar(TRUE, ngettext(
2442 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2443 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2444 count), filename, count, original_find_text, original_replace_text);
2445 g_free(filename);
2449 /* Replace all text matches in a certain range within document.
2450 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2451 * or -1 if no text was found.
2452 * scroll_to_match is whether to scroll the last replacement in view (which also
2453 * clears the selection).
2454 * Returns: the number of replacements made. */
2455 static guint
2456 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2457 GeanyFindFlags flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2459 gint count = 0;
2460 struct Sci_TextToFind ttf;
2461 ScintillaObject *sci;
2463 if (new_range_end != NULL)
2464 *new_range_end = -1;
2466 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2468 if (! *find_text || doc->readonly)
2469 return 0;
2471 sci = doc->editor->sci;
2473 ttf.chrg.cpMin = start;
2474 ttf.chrg.cpMax = end;
2475 ttf.lpstrText = (gchar*)find_text;
2477 sci_start_undo_action(sci);
2478 count = search_replace_range(sci, &ttf, flags, replace_text);
2479 sci_end_undo_action(sci);
2481 if (count > 0)
2482 { /* scroll last match in view, will destroy the existing selection */
2483 if (scroll_to_match)
2484 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2486 if (new_range_end != NULL)
2487 *new_range_end = ttf.chrg.cpMax;
2489 return count;
2493 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2494 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2496 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2497 gint max_column = 0, count = 0;
2498 gboolean replaced = FALSE;
2500 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2502 if (! *find_text)
2503 return;
2505 selection_start = sci_get_selection_start(doc->editor->sci);
2506 selection_end = sci_get_selection_end(doc->editor->sci);
2507 /* do we have a selection? */
2508 if ((selection_end - selection_start) == 0)
2510 utils_beep();
2511 return;
2514 selection_mode = sci_get_selection_mode(doc->editor->sci);
2515 selected_lines = sci_get_lines_selected(doc->editor->sci);
2516 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2517 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2519 gint first_line, line;
2521 sci_start_undo_action(doc->editor->sci);
2523 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2524 /* Find the last line with chars selected (not EOL char) */
2525 last_line = sci_get_line_from_position(doc->editor->sci,
2526 selection_end - editor_get_eol_char_len(doc->editor));
2527 last_line = MAX(first_line, last_line);
2528 for (line = first_line; line < (first_line + selected_lines); line++)
2530 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2531 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2533 /* skip line if there is no selection */
2534 if (line_start != INVALID_POSITION)
2536 /* don't let document_replace_range() scroll to match to keep our selection */
2537 gint new_sel_end;
2539 count += document_replace_range(doc, find_text, replace_text, flags,
2540 line_start, line_end, FALSE, &new_sel_end);
2541 if (new_sel_end != -1)
2543 replaced = TRUE;
2544 /* this gets the greatest column within the selection after replacing */
2545 max_column = MAX(max_column,
2546 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2550 sci_end_undo_action(doc->editor->sci);
2552 else /* handle normal line selection */
2554 count += document_replace_range(doc, find_text, replace_text, flags,
2555 selection_start, selection_end, TRUE, &selection_end);
2556 if (selection_end != -1)
2557 replaced = TRUE;
2560 if (replaced)
2561 { /* update the selection for the new endpoint */
2563 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2565 /* now we can scroll to the selection and destroy it because we rebuild it later */
2566 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2568 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2569 * the highest column on the last line. The wrapped selection is completely different
2570 * from the original one, so skip the selection at all */
2571 /* TODO is there a better way to handle the wrapped selection? */
2572 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2573 { /* for keeping and adjusting the selection in multi line rectangle selection we
2574 * need the last line of the original selection and the greatest column number after
2575 * replacing and set the selection end to the last line at the greatest column */
2576 sci_set_selection_start(doc->editor->sci, selection_start);
2577 sci_set_selection_end(doc->editor->sci,
2578 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2579 sci_set_selection_mode(doc->editor->sci, selection_mode);
2582 else
2584 sci_set_selection_start(doc->editor->sci, selection_start);
2585 sci_set_selection_end(doc->editor->sci, selection_end);
2588 else /* no replacements */
2589 utils_beep();
2591 show_replace_summary(doc, count, original_find_text, original_replace_text);
2595 /* returns number of replacements made. */
2596 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2597 const gchar *original_find_text, const gchar *original_replace_text, GeanyFindFlags flags)
2599 gint len, count;
2600 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2602 if (! *find_text)
2603 return FALSE;
2605 len = sci_get_length(doc->editor->sci);
2606 count = document_replace_range(
2607 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2609 show_replace_summary(doc, count, original_find_text, original_replace_text);
2610 return count;
2615 * Parses or re-parses the document's buffer and updates the type
2616 * keywords and symbol list.
2618 * @param doc The document.
2620 void document_update_tags(GeanyDocument *doc)
2622 guchar *buffer_ptr;
2623 gsize len;
2625 g_return_if_fail(DOC_VALID(doc));
2626 g_return_if_fail(app->tm_workspace != NULL);
2628 /* early out if it's a new file or doesn't support tags */
2629 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2631 /* We must call sidebar_update_tag_list() before returning,
2632 * to ensure that the symbol list is always updated properly (e.g.
2633 * when creating a new document with a partial filename set. */
2634 sidebar_update_tag_list(doc, FALSE);
2635 return;
2638 /* create a new TM file if there isn't one yet */
2639 if (! doc->tm_file)
2641 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2642 const gchar *name;
2644 /* lookup the name rather than using filetype name to support custom filetypes */
2645 name = tm_source_file_get_lang_name(doc->file_type->lang);
2646 doc->tm_file = tm_source_file_new(locale_filename, name);
2647 g_free(locale_filename);
2649 if (doc->tm_file)
2650 tm_workspace_add_source_file_noupdate(doc->tm_file);
2653 /* early out if there's no tm source file and we couldn't create one */
2654 if (doc->tm_file == NULL)
2656 /* We must call sidebar_update_tag_list() before returning,
2657 * to ensure that the symbol list is always updated properly (e.g.
2658 * when creating a new document with a partial filename set. */
2659 sidebar_update_tag_list(doc, FALSE);
2660 return;
2663 /* Parse Scintilla's buffer directly using TagManager
2664 * Note: this buffer *MUST NOT* be modified */
2665 len = sci_get_length(doc->editor->sci);
2666 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2667 tm_workspace_update_source_file_buffer(doc->tm_file, buffer_ptr, len);
2669 sidebar_update_tag_list(doc, TRUE);
2670 document_highlight_tags(doc);
2674 /* Re-highlights type keywords without re-parsing the whole document. */
2675 void document_highlight_tags(GeanyDocument *doc)
2677 GString *keywords_str;
2678 gchar *keywords;
2679 gint keyword_idx;
2681 /* some filetypes support type keywords (such as struct names), but not
2682 * necessarily all filetypes for a particular scintilla lexer. this
2683 * tells us whether the filetype supports keywords, and if so
2684 * which index to use for the scintilla keywords set. */
2685 switch (doc->file_type->id)
2687 case GEANY_FILETYPES_C:
2688 case GEANY_FILETYPES_CPP:
2689 case GEANY_FILETYPES_CS:
2690 case GEANY_FILETYPES_D:
2691 case GEANY_FILETYPES_JAVA:
2692 case GEANY_FILETYPES_OBJECTIVEC:
2693 case GEANY_FILETYPES_VALA:
2694 case GEANY_FILETYPES_RUST:
2695 case GEANY_FILETYPES_GO:
2698 /* index of the keyword set in the Scintilla lexer, for
2699 * example in LexCPP.cxx, see "cppWordLists" global array.
2700 * TODO: this magic number should be a member of the filetype */
2701 keyword_idx = 3;
2702 break;
2704 default:
2705 return; /* early out if type keywords are not supported */
2707 if (!app->tm_workspace->tags_array)
2708 return;
2710 /* get any type keywords and tell scintilla about them
2711 * this will cause the type keywords to be colourized in scintilla */
2712 keywords_str = symbols_find_typenames_as_string(doc->file_type->lang, FALSE);
2713 if (keywords_str)
2715 keywords = g_string_free(keywords_str, FALSE);
2716 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2717 g_free(keywords);
2718 queue_colourise(doc); /* force re-highlighting the entire document */
2723 static gboolean on_document_update_tag_list_idle(gpointer data)
2725 GeanyDocument *doc = data;
2727 if (! DOC_VALID(doc))
2728 return FALSE;
2730 if (! main_status.quitting)
2731 document_update_tags(doc);
2733 doc->priv->tag_list_update_source = 0;
2735 /* don't update the tags until another modification of the buffer */
2736 return FALSE;
2740 void document_update_tag_list_in_idle(GeanyDocument *doc)
2742 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2743 return;
2745 /* prevent "stacking up" callback handlers, we only need one to run soon */
2746 if (doc->priv->tag_list_update_source != 0)
2747 g_source_remove(doc->priv->tag_list_update_source);
2749 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2750 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2754 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2755 gboolean filetype_changed)
2757 g_return_if_fail(doc);
2758 if (type == NULL)
2759 type = filetypes[GEANY_FILETYPES_NONE];
2761 if (filetype_changed)
2763 doc->file_type = type;
2765 /* delete tm file object to force creation of a new one */
2766 if (doc->tm_file != NULL)
2768 tm_workspace_remove_source_file(doc->tm_file);
2769 tm_source_file_free(doc->tm_file);
2770 doc->tm_file = NULL;
2772 /* load tags files before highlighting (some lexers highlight global typenames) */
2773 if (type->id != GEANY_FILETYPES_NONE)
2774 symbols_global_tags_loaded(type->id);
2776 highlighting_set_styles(doc->editor->sci, type);
2777 editor_set_indentation_guides(doc->editor);
2778 build_menu_update(doc);
2779 queue_colourise(doc);
2780 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2783 document_update_tags(doc);
2787 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2788 * @param doc The document to use.
2789 * @param type The filetype. */
2790 GEANY_API_SYMBOL
2791 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2793 gboolean ft_changed;
2794 GeanyFiletype *old_ft;
2796 g_return_if_fail(doc);
2797 if (type == NULL)
2798 type = filetypes[GEANY_FILETYPES_NONE];
2800 old_ft = doc->file_type;
2801 geany_debug("%s : %s (%s)",
2802 (doc->file_name != NULL) ? doc->file_name : "unknown",
2803 type->name,
2804 (doc->encoding != NULL) ? doc->encoding : "unknown");
2806 ft_changed = (doc->file_type != type); /* filetype has changed */
2807 document_load_config(doc, type, ft_changed);
2809 if (ft_changed)
2811 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2813 /* assume that if previous filetype was none and the settings are the default ones, this
2814 * is the first time the filetype is carefully set, so we should apply indent settings */
2815 if ((! old_ft || old_ft->id == GEANY_FILETYPES_NONE) &&
2816 doc->editor->indent_type == iprefs->type &&
2817 doc->editor->indent_width == iprefs->width)
2819 document_apply_indent_settings(doc);
2820 ui_document_show_hide(doc);
2823 sidebar_openfiles_update(doc); /* to update the icon */
2824 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2829 void document_reload_config(GeanyDocument *doc)
2831 document_load_config(doc, doc->file_type, TRUE);
2836 * Sets the encoding of a document.
2837 * This function only set the encoding of the %document, it does not any conversions. The new
2838 * encoding is used when e.g. saving the file.
2840 * @param doc The document to use.
2841 * @param new_encoding The encoding to be set for the document.
2843 GEANY_API_SYMBOL
2844 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2846 if (doc == NULL || new_encoding == NULL ||
2847 utils_str_equal(new_encoding, doc->encoding))
2848 return;
2850 g_free(doc->encoding);
2851 doc->encoding = g_strdup(new_encoding);
2853 ui_update_statusbar(doc, -1);
2854 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2855 encodings_is_unicode_charset(doc->encoding));
2859 /* own Undo / Redo implementation to be able to undo / redo changes
2860 * to the encoding or the Unicode BOM (which are Scintilla independet).
2861 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2863 /* Clears an Undo or Redo buffer. */
2864 void document_undo_clear_stack(GTrashStack **stack)
2866 undo_action *a;
2868 while (g_trash_stack_height(stack) > 0)
2870 a = g_trash_stack_pop(stack);
2871 if (G_LIKELY(a != NULL))
2873 switch (a->type)
2875 case UNDO_ENCODING:
2876 case UNDO_RELOAD:
2877 g_free(a->data); break;
2878 default: break;
2880 g_free(a);
2883 *stack = NULL;
2886 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2887 void document_undo_clear(GeanyDocument *doc)
2889 document_undo_clear_stack(&doc->priv->undo_actions);
2890 document_undo_clear_stack(&doc->priv->redo_actions);
2892 if (! main_status.quitting && doc->editor != NULL)
2893 document_set_text_changed(doc, FALSE);
2897 /* Adds an undo action without clearing the redo stack. This function should
2898 * not be called directly, generally (use document_undo_add() instead), but is
2899 * used by document_redo() in order not to erase the redo stack while moving
2900 * an action from the redo stack to the undo stack. */
2901 void document_undo_add_internal(GeanyDocument *doc, guint type, gpointer data)
2903 undo_action *action;
2905 g_return_if_fail(doc != NULL);
2907 action = g_new0(undo_action, 1);
2908 action->type = type;
2909 action->data = data;
2911 g_trash_stack_push(&doc->priv->undo_actions, action);
2913 /* avoid unnecessary redraws */
2914 if (type != UNDO_SCINTILLA || !doc->changed)
2915 document_set_text_changed(doc, TRUE);
2917 ui_update_popup_reundo_items(doc);
2920 /* note: this is called on SCN_MODIFIED notifications */
2921 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2923 /* Clear the redo actions stack before adding the undo action. */
2924 document_undo_clear_stack(&doc->priv->redo_actions);
2926 document_undo_add_internal(doc, type, data);
2930 gboolean document_can_undo(GeanyDocument *doc)
2932 g_return_val_if_fail(doc != NULL, FALSE);
2934 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2935 return TRUE;
2936 else
2937 return FALSE;
2941 static void update_changed_state(GeanyDocument *doc)
2943 doc->changed =
2944 (sci_is_modified(doc->editor->sci) ||
2945 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2946 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2947 document_set_text_changed(doc, doc->changed);
2951 void document_undo(GeanyDocument *doc)
2953 undo_action *action;
2955 g_return_if_fail(doc != NULL);
2957 action = g_trash_stack_pop(&doc->priv->undo_actions);
2959 if (G_UNLIKELY(action == NULL))
2961 /* fallback, should not be necessary */
2962 geany_debug("%s: fallback used", G_STRFUNC);
2963 sci_undo(doc->editor->sci);
2965 else
2967 switch (action->type)
2969 case UNDO_SCINTILLA:
2971 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2973 sci_undo(doc->editor->sci);
2974 break;
2976 case UNDO_BOM:
2978 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2980 doc->has_bom = GPOINTER_TO_INT(action->data);
2981 ui_update_statusbar(doc, -1);
2982 ui_document_show_hide(doc);
2983 break;
2985 case UNDO_ENCODING:
2987 /* use the "old" encoding */
2988 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2990 document_set_encoding(doc, (const gchar*)action->data);
2992 ignore_callback = TRUE;
2993 encodings_select_radio_item((const gchar*)action->data);
2994 ignore_callback = FALSE;
2996 g_free(action->data);
2997 break;
2999 case UNDO_RELOAD:
3001 UndoReloadData *data = (UndoReloadData*)action->data;
3002 gint eol_mode = data->eol_mode;
3003 guint i;
3005 /* We reuse 'data' for the redo action, so read the current EOL mode
3006 * into it before proceeding. */
3007 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3009 /* Undo the rest of the actions which are part of the reloading process. */
3010 for (i = 0; i < data->actions_count; i++)
3011 document_undo(doc);
3013 /* Restore the previous EOL mode. */
3014 sci_set_eol_mode(doc->editor->sci, eol_mode);
3015 /* This might affect the status bar and document menu, so update them. */
3016 ui_update_statusbar(doc, -1);
3017 ui_document_show_hide(doc);
3019 document_redo_add(doc, UNDO_RELOAD, data);
3020 break;
3022 default: break;
3025 g_free(action); /* free the action which was taken from the stack */
3027 update_changed_state(doc);
3028 ui_update_popup_reundo_items(doc);
3032 gboolean document_can_redo(GeanyDocument *doc)
3034 g_return_val_if_fail(doc != NULL, FALSE);
3036 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
3037 return TRUE;
3038 else
3039 return FALSE;
3043 void document_redo(GeanyDocument *doc)
3045 undo_action *action;
3047 g_return_if_fail(doc != NULL);
3049 action = g_trash_stack_pop(&doc->priv->redo_actions);
3051 if (G_UNLIKELY(action == NULL))
3053 /* fallback, should not be necessary */
3054 geany_debug("%s: fallback used", G_STRFUNC);
3055 sci_redo(doc->editor->sci);
3057 else
3059 switch (action->type)
3061 case UNDO_SCINTILLA:
3063 document_undo_add_internal(doc, UNDO_SCINTILLA, NULL);
3065 sci_redo(doc->editor->sci);
3066 break;
3068 case UNDO_BOM:
3070 document_undo_add_internal(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
3072 doc->has_bom = GPOINTER_TO_INT(action->data);
3073 ui_update_statusbar(doc, -1);
3074 ui_document_show_hide(doc);
3075 break;
3077 case UNDO_ENCODING:
3079 document_undo_add_internal(doc, UNDO_ENCODING, g_strdup(doc->encoding));
3081 document_set_encoding(doc, (const gchar*)action->data);
3083 ignore_callback = TRUE;
3084 encodings_select_radio_item((const gchar*)action->data);
3085 ignore_callback = FALSE;
3087 g_free(action->data);
3088 break;
3090 case UNDO_RELOAD:
3092 UndoReloadData *data = (UndoReloadData*)action->data;
3093 gint eol_mode = data->eol_mode;
3094 guint i;
3096 /* We reuse 'data' for the undo action, so read the current EOL mode
3097 * into it before proceeding. */
3098 data->eol_mode = editor_get_eol_char_mode(doc->editor);
3100 /* Redo the rest of the actions which are part of the reloading process. */
3101 for (i = 0; i < data->actions_count; i++)
3102 document_redo(doc);
3104 /* Restore the previous EOL mode. */
3105 sci_set_eol_mode(doc->editor->sci, eol_mode);
3106 /* This might affect the status bar and document menu, so update them. */
3107 ui_update_statusbar(doc, -1);
3108 ui_document_show_hide(doc);
3110 document_undo_add_internal(doc, UNDO_RELOAD, data);
3111 break;
3113 default: break;
3116 g_free(action); /* free the action which was taken from the stack */
3118 update_changed_state(doc);
3119 ui_update_popup_reundo_items(doc);
3123 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
3125 undo_action *action;
3127 g_return_if_fail(doc != NULL);
3129 action = g_new0(undo_action, 1);
3130 action->type = type;
3131 action->data = data;
3133 g_trash_stack_push(&doc->priv->redo_actions, action);
3135 if (type != UNDO_SCINTILLA || !doc->changed)
3136 document_set_text_changed(doc, TRUE);
3138 ui_update_popup_reundo_items(doc);
3142 enum
3144 STATUS_CHANGED,
3145 STATUS_DISK_CHANGED,
3146 STATUS_READONLY
3149 static struct
3151 const gchar *name;
3152 GdkColor color;
3153 gboolean loaded;
3154 } document_status_styles[] = {
3155 { "geany-document-status-changed", {0}, FALSE },
3156 { "geany-document-status-disk-changed", {0}, FALSE },
3157 { "geany-document-status-readonly", {0}, FALSE }
3161 static gint document_get_status_id(GeanyDocument *doc)
3163 if (doc->changed)
3164 return STATUS_CHANGED;
3165 #ifdef USE_GIO_FILEMON
3166 else if (doc->priv->file_disk_status == FILE_CHANGED)
3167 #else
3168 else if (doc->priv->protected)
3169 #endif
3170 return STATUS_DISK_CHANGED;
3171 else if (doc->readonly)
3172 return STATUS_READONLY;
3174 return -1;
3178 /* returns an identifier that is to be set as a widget name or class to get it styled
3179 * depending on the document status (changed, readonly, etc.)
3180 * a NULL return value means default (unchanged) style */
3181 const gchar *document_get_status_widget_class(GeanyDocument *doc)
3183 gint status;
3185 g_return_val_if_fail(doc != NULL, NULL);
3187 status = document_get_status_id(doc);
3188 if (status < 0)
3189 return NULL;
3190 else
3191 return document_status_styles[status].name;
3196 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
3197 * Returned colors are red if the document has changes, green if the document is read-only
3198 * or simply @c NULL if the document is unmodified but writable.
3200 * @param doc The document to use.
3202 * @return The color for the document or @c NULL if the default color should be used. The color
3203 * object is owned by Geany and should not be modified or freed.
3205 * @since 0.16
3207 GEANY_API_SYMBOL
3208 const GdkColor *document_get_status_color(GeanyDocument *doc)
3210 gint status;
3212 g_return_val_if_fail(doc != NULL, NULL);
3214 status = document_get_status_id(doc);
3215 if (status < 0)
3216 return NULL;
3217 if (! document_status_styles[status].loaded)
3219 #if GTK_CHECK_VERSION(3, 0, 0)
3220 GdkRGBA color;
3221 GtkWidgetPath *path = gtk_widget_path_new();
3222 GtkStyleContext *ctx = gtk_style_context_new();
3223 gtk_widget_path_append_type(path, GTK_TYPE_WINDOW);
3224 gtk_widget_path_append_type(path, GTK_TYPE_BOX);
3225 gtk_widget_path_append_type(path, GTK_TYPE_NOTEBOOK);
3226 gtk_widget_path_append_type(path, GTK_TYPE_LABEL);
3227 gtk_widget_path_iter_set_name(path, -1, document_status_styles[status].name);
3228 gtk_style_context_set_screen(ctx, gtk_widget_get_screen(GTK_WIDGET(doc->editor->sci)));
3229 gtk_style_context_set_path(ctx, path);
3230 gtk_style_context_get_color(ctx, GTK_STATE_NORMAL, &color);
3231 document_status_styles[status].color.red = 0xffff * color.red;
3232 document_status_styles[status].color.green = 0xffff * color.green;
3233 document_status_styles[status].color.blue = 0xffff * color.blue;
3234 document_status_styles[status].loaded = TRUE;
3235 gtk_widget_path_unref(path);
3236 g_object_unref(ctx);
3237 #else
3238 GtkSettings *settings = gtk_widget_get_settings(GTK_WIDGET(doc->editor->sci));
3239 gchar *path = g_strconcat("GeanyMainWindow.GtkHBox.GtkNotebook.",
3240 document_status_styles[status].name, NULL);
3241 GtkStyle *style = gtk_rc_get_style_by_paths(settings, path, NULL, GTK_TYPE_LABEL);
3243 document_status_styles[status].color = style->fg[GTK_STATE_NORMAL];
3244 document_status_styles[status].loaded = TRUE;
3245 g_free(path);
3246 #endif
3248 return &document_status_styles[status].color;
3252 /** Accessor function for @ref documents_array items.
3253 * @warning Always check the returned document is valid (@c doc->is_valid).
3254 * @param idx @c documents_array index.
3255 * @return The document, or @c NULL if @a idx is out of range.
3257 * @since 0.16
3259 GEANY_API_SYMBOL
3260 GeanyDocument *document_index(gint idx)
3262 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
3266 GeanyDocument *document_clone(GeanyDocument *old_doc)
3268 gchar *text;
3269 GeanyDocument *doc;
3270 ScintillaObject *old_sci;
3272 g_return_val_if_fail(old_doc, NULL);
3273 old_sci = old_doc->editor->sci;
3274 if (sci_has_selection(old_sci))
3275 text = sci_get_selection_contents(old_sci);
3276 else
3277 text = sci_get_contents(old_sci, -1);
3279 doc = document_new_file(NULL, old_doc->file_type, text);
3280 g_free(text);
3281 document_set_text_changed(doc, TRUE);
3283 /* copy file properties */
3284 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
3285 doc->editor->line_breaking = old_doc->editor->line_breaking;
3286 doc->editor->auto_indent = old_doc->editor->auto_indent;
3287 editor_set_indent(doc->editor, old_doc->editor->indent_type,
3288 old_doc->editor->indent_width);
3289 doc->readonly = old_doc->readonly;
3290 doc->has_bom = old_doc->has_bom;
3291 doc->priv->protected = 0;
3292 document_set_encoding(doc, old_doc->encoding);
3293 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
3294 sci_set_readonly(doc->editor->sci, doc->readonly);
3296 /* update ui */
3297 ui_document_show_hide(doc);
3298 return doc;
3302 /* @note If successful, this should always be followed up with a call to
3303 * document_close_all().
3304 * @return TRUE if all files were saved or had their changes discarded. */
3305 gboolean document_account_for_unsaved(void)
3307 guint i, p, page_count;
3309 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
3310 /* iterate over documents in tabs order */
3311 for (p = 0; p < page_count; p++)
3313 GeanyDocument *doc = document_get_from_page(p);
3315 if (DOC_VALID(doc) && doc->changed)
3317 if (! dialogs_show_unsaved_file(doc))
3318 return FALSE;
3321 /* all documents should now be accounted for, so ignore any changes */
3322 foreach_document (i)
3324 documents[i]->changed = FALSE;
3326 return TRUE;
3330 static void force_close_all(void)
3332 guint i, len = documents_array->len;
3334 /* check all documents have been accounted for */
3335 for (i = 0; i < len; i++)
3337 if (documents[i]->is_valid)
3339 g_return_if_fail(!documents[i]->changed);
3342 main_status.closing_all = TRUE;
3344 foreach_document(i)
3346 document_close(documents[i]);
3349 main_status.closing_all = FALSE;
3353 gboolean document_close_all(void)
3355 if (! document_account_for_unsaved())
3356 return FALSE;
3358 force_close_all();
3360 return TRUE;
3364 /* *
3365 * Shows a message related to a document.
3367 * Use this whenever the user needs to see a document-related message,
3368 * for example when the file was externally modified or deleted.
3370 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3371 * @a response_1 response will be the default for the @c GtkInfoBar or
3372 * @c GtkDialog.
3374 * @param doc @c GeanyDocument.
3375 * @param msgtype The type of message.
3376 * @param response_cb A callback function called when there's a response.
3377 * @param btn_1 The first action area button.
3378 * @param response_1 The response for @a btn_1.
3379 * @param btn_2 The second action area button.
3380 * @param response_2 The response for @a btn_2.
3381 * @param btn_3 The third action area button.
3382 * @param response_3 The response for @a btn_3.
3383 * @param extra_text Text to show below the main message.
3384 * @param format The text format for the main message.
3385 * @param ... Used with @a format as in @c printf.
3387 * @since 1.25
3388 * */
3389 static GtkWidget* document_show_message(GeanyDocument *doc, GtkMessageType msgtype,
3390 void (*response_cb)(GtkWidget *info_bar, gint response_id, GeanyDocument *doc),
3391 const gchar *btn_1, GtkResponseType response_1,
3392 const gchar *btn_2, GtkResponseType response_2,
3393 const gchar *btn_3, GtkResponseType response_3,
3394 const gchar *extra_text, const gchar *format, ...)
3396 va_list args;
3397 gchar *text, *markup;
3398 GtkWidget *hbox, *vbox, *icon, *label, *extra_label, *content_area;
3399 GtkWidget *info_widget, *parent;
3400 parent = document_get_notebook_child(doc);
3402 va_start(args, format);
3403 text = g_strdup_vprintf(format, args);
3404 va_end(args);
3406 markup = g_strdup_printf("<span size=\"larger\">%s</span>", text);
3407 g_free(text);
3409 info_widget = gtk_info_bar_new();
3410 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3411 gtk_box_pack_start(GTK_BOX(parent), info_widget, FALSE, TRUE, 0);
3413 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget), msgtype);
3415 if (btn_1)
3416 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_1, response_1);
3417 if (btn_2)
3418 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_2, response_2);
3419 if (btn_3)
3420 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget), btn_3, response_3);
3422 content_area = gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget));
3424 label = geany_wrap_label_new(NULL);
3425 gtk_label_set_markup(GTK_LABEL(label), markup);
3426 g_free(markup);
3428 g_signal_connect(info_widget, "response", G_CALLBACK(response_cb), doc);
3430 hbox = gtk_hbox_new(FALSE, 12);
3431 gtk_box_pack_start(GTK_BOX(content_area), hbox, TRUE, TRUE, 0);
3433 switch (msgtype)
3435 case GTK_MESSAGE_INFO:
3436 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO, GTK_ICON_SIZE_DIALOG);
3437 break;
3438 case GTK_MESSAGE_WARNING:
3439 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING, GTK_ICON_SIZE_DIALOG);
3440 break;
3441 case GTK_MESSAGE_QUESTION:
3442 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION, GTK_ICON_SIZE_DIALOG);
3443 break;
3444 case GTK_MESSAGE_ERROR:
3445 icon = gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR, GTK_ICON_SIZE_DIALOG);
3446 break;
3447 default:
3448 icon = NULL;
3449 break;
3452 if (icon)
3453 gtk_box_pack_start(GTK_BOX(hbox), icon, FALSE, TRUE, 0);
3455 if (extra_text)
3457 vbox = gtk_vbox_new(FALSE, 6);
3458 extra_label = geany_wrap_label_new(extra_text);
3459 gtk_box_pack_start(GTK_BOX(vbox), label, TRUE, TRUE, 0);
3460 gtk_box_pack_start(GTK_BOX(vbox), extra_label, TRUE, TRUE, 0);
3461 gtk_box_pack_start(GTK_BOX(hbox), vbox, TRUE, TRUE, 0);
3463 else
3464 gtk_box_pack_start(GTK_BOX(hbox), label, TRUE, TRUE, 0);
3466 gtk_box_reorder_child(GTK_BOX(parent), info_widget, 0);
3468 gtk_widget_show_all(info_widget);
3470 return info_widget;
3474 static void on_monitor_reload_file_response(GtkWidget *bar, gint response_id, GeanyDocument *doc)
3476 gboolean close = FALSE;
3478 // disable info bar so actions complete normally
3479 unprotect_document(doc);
3480 doc->priv->info_bars[MSG_TYPE_RELOAD] = NULL;
3482 if (response_id == RESPONSE_DOCUMENT_RELOAD)
3484 close = doc->changed ?
3485 document_reload_prompt(doc, doc->encoding) :
3486 document_reload_force(doc, doc->encoding);
3488 else if (response_id == RESPONSE_DOCUMENT_SAVE)
3490 close = document_save_file(doc, TRUE); // force overwrite
3492 else if (response_id == GTK_RESPONSE_CANCEL)
3494 document_set_text_changed(doc, TRUE);
3495 close = TRUE;
3497 if (!close)
3499 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3500 protect_document(doc);
3501 return;
3503 gtk_widget_destroy(bar);
3507 static gboolean on_sci_key(GtkWidget *widget, GdkEventKey *event, gpointer data)
3509 GtkInfoBar *bar = GTK_INFO_BAR(data);
3511 g_return_val_if_fail(event->type == GDK_KEY_PRESS, FALSE);
3513 switch (event->keyval)
3515 case GDK_Tab:
3516 case GDK_ISO_Left_Tab:
3518 GtkWidget *action_area = gtk_info_bar_get_action_area(bar);
3519 GtkDirectionType dir = event->keyval == GDK_Tab ? GTK_DIR_TAB_FORWARD : GTK_DIR_TAB_BACKWARD;
3520 gtk_widget_child_focus(action_area, dir);
3521 return TRUE;
3523 case GDK_Escape:
3525 gtk_info_bar_response(bar, GTK_RESPONSE_CANCEL);
3526 return TRUE;
3528 default:
3529 return FALSE;
3534 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3535 static void enable_key_intercept(GeanyDocument *doc, GtkWidget *bar)
3537 /* automatically focus editor again on bar close */
3538 g_signal_connect_object(bar, "destroy", G_CALLBACK(gtk_widget_grab_focus), doc->editor->sci,
3539 G_CONNECT_SWAPPED);
3540 g_signal_connect_object(doc->editor->sci, "key-press-event", G_CALLBACK(on_sci_key), bar, 0);
3544 static void monitor_reload_file(GeanyDocument *doc)
3546 gchar *base_name = g_path_get_basename(doc->file_name);
3548 /* show this message only once */
3549 if (doc->priv->info_bars[MSG_TYPE_RELOAD] == NULL)
3551 GtkWidget *bar;
3553 bar = document_show_message(doc, GTK_MESSAGE_QUESTION, on_monitor_reload_file_response,
3554 _("_Reload"), RESPONSE_DOCUMENT_RELOAD,
3555 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE,
3556 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3557 _("Do you want to reload it?"),
3558 _("The file '%s' on the disk is more recent than the current buffer."),
3559 base_name);
3561 protect_document(doc);
3562 doc->priv->info_bars[MSG_TYPE_RELOAD] = bar;
3563 enable_key_intercept(doc, bar);
3565 g_free(base_name);
3569 static void on_monitor_resave_missing_file_response(GtkWidget *bar,
3570 gint response_id,
3571 GeanyDocument *doc)
3573 gboolean close = TRUE;
3575 unprotect_document(doc);
3577 if (response_id == RESPONSE_DOCUMENT_SAVE)
3578 close = dialogs_show_save_as();
3580 if (close)
3582 doc->priv->info_bars[MSG_TYPE_RESAVE] = NULL;
3583 gtk_widget_destroy(bar);
3585 else
3587 /* protect back the document if save didn't occur */
3588 protect_document(doc);
3593 static void monitor_resave_missing_file(GeanyDocument *doc)
3595 if (doc->priv->info_bars[MSG_TYPE_RESAVE] == NULL)
3597 GtkWidget *bar = doc->priv->info_bars[MSG_TYPE_RELOAD];
3599 if (bar != NULL) /* the "file on disk is newer" warning is now moot */
3600 gtk_info_bar_response(GTK_INFO_BAR(bar), GTK_RESPONSE_CANCEL);
3602 bar = document_show_message(doc, GTK_MESSAGE_WARNING,
3603 on_monitor_resave_missing_file_response,
3604 GTK_STOCK_SAVE, RESPONSE_DOCUMENT_SAVE,
3605 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
3606 NULL, GTK_RESPONSE_NONE,
3607 _("Try to resave the file?"),
3608 _("File \"%s\" was not found on disk!"),
3609 doc->file_name);
3611 protect_document(doc);
3612 document_set_text_changed(doc, TRUE);
3613 /* don't prompt more than once */
3614 SETPTR(doc->real_path, NULL);
3615 doc->priv->info_bars[MSG_TYPE_RESAVE] = bar;
3616 enable_key_intercept(doc, bar);
3621 /* Set force to force a disk check, otherwise it is ignored if there was a check
3622 * in the last file_prefs.disk_check_timeout seconds.
3623 * @return @c TRUE if the file has changed. */
3624 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
3626 gboolean ret = FALSE;
3627 gboolean use_gio_filemon;
3628 time_t cur_time = 0;
3629 time_t mtime;
3630 gchar *locale_filename;
3631 FileDiskStatus old_status;
3633 g_return_val_if_fail(doc != NULL, FALSE);
3635 /* ignore remote files and documents that have never been saved to disk */
3636 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
3637 || doc->real_path == NULL || doc->priv->is_remote)
3638 return FALSE;
3640 use_gio_filemon = (doc->priv->monitor != NULL);
3642 if (use_gio_filemon)
3644 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
3645 return FALSE;
3647 else
3649 cur_time = time(NULL);
3650 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
3651 return FALSE;
3653 doc->priv->last_check = cur_time;
3656 locale_filename = utils_get_locale_from_utf8(doc->file_name);
3657 if (!get_mtime(locale_filename, &mtime))
3659 monitor_resave_missing_file(doc);
3660 /* doc may be closed now */
3661 ret = TRUE;
3663 else if (doc->priv->mtime < mtime)
3665 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3666 doc->priv->mtime = mtime;
3667 monitor_reload_file(doc);
3668 /* doc may be closed now */
3669 ret = TRUE;
3671 g_free(locale_filename);
3673 if (DOC_VALID(doc))
3674 { /* doc can get invalid when a document was closed */
3675 old_status = doc->priv->file_disk_status;
3676 doc->priv->file_disk_status = FILE_OK;
3677 if (old_status != doc->priv->file_disk_status)
3678 ui_update_tab_status(doc);
3680 return ret;
3684 /** Compares documents by their display names.
3685 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3686 * @note 'Display name' means the base name of the document's filename.
3688 * @param a @c GeanyDocument**.
3689 * @param b @c GeanyDocument**.
3690 * @warning The arguments take the address of each document pointer.
3691 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3693 * @since 0.21
3695 GEANY_API_SYMBOL
3696 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
3698 GeanyDocument *doc_a = *((GeanyDocument**) a);
3699 GeanyDocument *doc_b = *((GeanyDocument**) b);
3700 gchar *base_name_a, *base_name_b;
3701 gint result;
3703 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
3704 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
3706 result = strcmp(base_name_a, base_name_b);
3708 g_free(base_name_a);
3709 g_free(base_name_b);
3711 return result;
3715 /** Compares documents by their tab order.
3716 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3718 * @param a @c GeanyDocument**.
3719 * @param b @c GeanyDocument**.
3720 * @warning The arguments take the address of each document pointer.
3721 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3723 * @since 0.21 (GEANY_API_VERSION 209)
3725 GEANY_API_SYMBOL
3726 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
3728 GeanyDocument *doc_a = *((GeanyDocument**) a);
3729 GeanyDocument *doc_b = *((GeanyDocument**) b);
3730 gint notebook_position_doc_a;
3731 gint notebook_position_doc_b;
3733 notebook_position_doc_a = document_get_notebook_page(doc_a);
3734 notebook_position_doc_b = document_get_notebook_page(doc_b);
3736 if (notebook_position_doc_a < notebook_position_doc_b)
3737 return -1;
3738 if (notebook_position_doc_a > notebook_position_doc_b)
3739 return 1;
3740 /* equality */
3741 return 0;
3745 /** Compares documents by their tab order, in reverse order.
3746 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3748 * @param a @c GeanyDocument**.
3749 * @param b @c GeanyDocument**.
3750 * @warning The arguments take the address of each document pointer.
3751 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3753 * @since 0.21 (GEANY_API_VERSION 209)
3755 GEANY_API_SYMBOL
3756 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3758 return -1 * document_compare_by_tab_order(a, b);
3762 void document_grab_focus(GeanyDocument *doc)
3764 g_return_if_fail(doc != NULL);
3766 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));