Force selection to change when Default or Alt colourscheme chosen
[geany-mirror.git] / src / document.c
blob20a5a5c1bac3c02cd1f78fcad837c5263082f474
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2011 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2011 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
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * Document related actions: new, save, open, etc.
24 * Also Scintilla search actions.
27 #include "geany.h"
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #include <time.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <errno.h>
38 #ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
40 #endif
42 #include <stdlib.h>
44 /* gstdio.h also includes sys/stat.h */
45 #include <glib/gstdio.h>
47 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
48 /*#define USE_GIO_FILEMON 1*/
49 #include <gio/gio.h>
51 #include "document.h"
52 #include "documentprivate.h"
53 #include "filetypes.h"
54 #include "support.h"
55 #include "sciwrappers.h"
56 #include "editor.h"
57 #include "dialogs.h"
58 #include "msgwindow.h"
59 #include "templates.h"
60 #include "sidebar.h"
61 #include "ui_utils.h"
62 #include "utils.h"
63 #include "encodings.h"
64 #include "notebook.h"
65 #include "main.h"
66 #include "vte.h"
67 #include "build.h"
68 #include "symbols.h"
69 #include "highlighting.h"
70 #include "navqueue.h"
71 #include "win32.h"
72 #include "search.h"
73 #include "filetypesprivate.h"
74 #include "project.h"
76 #include "SciLexer.h"
79 GeanyFilePrefs file_prefs;
81 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
82 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
83 * to a document over time, but it might no longer represent a notebook tab. To check this,
84 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
85 * file by then.
87 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
88 * although usually you would just use the foreach_document() macro.
90 * Never assume that the order of document pointers is the same as the order of notebook tabs.
91 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
92 GPtrArray *documents_array = NULL;
95 /* an undo action, also used for redo actions */
96 typedef struct
98 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
99 guint type; /* to identify the action */
100 gpointer *data; /* the old value (before the change), in case of a redo action
101 * it contains the new value */
102 } undo_action;
105 static void document_undo_clear(GeanyDocument *doc);
106 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
107 static gboolean remove_page(guint page_num);
111 * Finds a document whose @c real_path field matches the given filename.
113 * @param realname The filename to search, which should be identical to the
114 * string returned by @c tm_get_real_path().
116 * @return The matching document, or @c NULL.
117 * @note This is only really useful when passing a @c TMWorkObject::file_name.
118 * @see GeanyDocument::real_path.
119 * @see document_find_by_filename().
121 * @since 0.15
123 GeanyDocument* document_find_by_real_path(const gchar *realname)
125 guint i;
127 if (! realname)
128 return NULL; /* file doesn't exist on disk */
130 for (i = 0; i < documents_array->len; i++)
132 GeanyDocument *doc = documents[i];
134 if (! doc->is_valid || ! doc->real_path)
135 continue;
137 if (utils_filenamecmp(realname, doc->real_path) == 0)
139 return doc;
142 return NULL;
146 /* dereference symlinks, /../ junk in path and return locale encoding */
147 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
149 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
150 gchar *realname = tm_get_real_path(locale_name);
152 g_free(locale_name);
153 return realname;
158 * Finds a document with the given filename.
159 * This matches either an exact GeanyDocument::file_name string, or variant
160 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
161 * match @c "/name").
163 * @param utf8_filename The filename to search (in UTF-8 encoding).
165 * @return The matching document, or @c NULL.
166 * @see document_find_by_real_path().
168 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
170 guint i;
171 GeanyDocument *doc;
172 gchar *realname;
174 g_return_val_if_fail(utf8_filename != NULL, NULL);
176 /* First search GeanyDocument::file_name, so we can find documents with a
177 * filename set but not saved on disk, like vcdiff produces */
178 for (i = 0; i < documents_array->len; i++)
180 doc = documents[i];
182 if (! doc->is_valid || doc->file_name == NULL)
183 continue;
185 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
187 return doc;
190 /* Now try matching based on the realpath(), which is unique per file on disk */
191 realname = get_real_path_from_utf8(utf8_filename);
192 doc = document_find_by_real_path(realname);
193 g_free(realname);
194 return doc;
198 /* returns the document which has sci, or NULL. */
199 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
201 guint i;
203 g_return_val_if_fail(sci != NULL, NULL);
205 for (i = 0; i < documents_array->len; i++)
207 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
208 return documents[i];
210 return NULL;
214 /** Gets the notebook page index for a document.
215 * @param doc The document.
216 * @return The index.
217 * @since 0.19 */
218 gint document_get_notebook_page(GeanyDocument *doc)
220 g_return_val_if_fail(doc != NULL, -1);
222 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
223 GTK_WIDGET(doc->editor->sci));
228 * Finds the document for the given notebook page @a page_num.
230 * @param page_num The notebook page number to search.
232 * @return The corresponding document for the given notebook page, or @c NULL.
234 GeanyDocument *document_get_from_page(guint page_num)
236 ScintillaObject *sci;
238 if (page_num >= documents_array->len)
239 return NULL;
241 sci = (ScintillaObject*)gtk_notebook_get_nth_page(
242 GTK_NOTEBOOK(main_widgets.notebook), page_num);
244 return document_find_by_sci(sci);
249 * Finds the current document.
251 * @return A pointer to the current document or @c NULL if there are no opened documents.
253 GeanyDocument *document_get_current(void)
255 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
257 if (cur_page == -1)
258 return NULL;
259 else
261 ScintillaObject *sci = (ScintillaObject*)
262 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
264 return document_find_by_sci(sci);
269 void document_init_doclist()
271 documents_array = g_ptr_array_new();
275 void document_finalize()
277 guint i;
279 for (i = 0; i < documents_array->len; i++)
280 g_free(documents[i]);
281 g_ptr_array_free(documents_array, TRUE);
286 * Returns the last part of the filename of the given GeanyDocument. The result is also
287 * truncated to a maximum of @a length characters in case the filename is very long.
289 * @param doc The document to use.
290 * @param length The length of the resulting string or -1 to use a default value.
292 * @return The ellipsized last part of the filename of @a doc, should be freed when no
293 * longer needed.
295 * @since 0.17
297 /* TODO make more use of this */
298 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
300 gchar *base_name, *short_name;
302 g_return_val_if_fail(doc != NULL, NULL);
304 if (length < 0)
305 length = 30;
307 base_name = g_path_get_basename(DOC_FILENAME(doc));
308 short_name = utils_str_middle_truncate(base_name, (guint)length);
310 g_free(base_name);
312 return short_name;
316 void document_update_tab_label(GeanyDocument *doc)
318 gchar *short_name;
319 GtkWidget *parent;
321 g_return_if_fail(doc != NULL);
323 short_name = document_get_basename_for_display(doc, -1);
325 /* we need to use the event box for the tooltip, labels don't get the necessary events */
326 parent = gtk_widget_get_parent(doc->priv->tab_label);
327 parent = gtk_widget_get_parent(parent);
329 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
331 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
333 g_free(short_name);
338 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
339 * according to the document's save state.
340 * This is called by Geany mostly when opening or saving files.
342 * @param doc The document to use.
343 * @param changed Whether the document state should indicate changes have been made.
345 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
347 g_return_if_fail(doc != NULL);
349 doc->changed = changed;
351 if (! main_status.quitting)
353 ui_update_tab_status(doc);
354 ui_save_buttons_toggle(changed);
355 ui_set_window_title(doc);
356 ui_update_statusbar(doc, -1);
361 /* returns the next free place in the document list,
362 * or -1 if the documents_array is full */
363 static gint document_get_new_idx(void)
365 guint i;
367 for (i = 0; i < documents_array->len; i++)
369 if (documents[i]->editor == NULL)
371 return (gint) i;
374 return -1;
378 static void queue_colourise(GeanyDocument *doc)
380 /* Colourise the editor before it is next drawn */
381 doc->priv->colourise_needed = TRUE;
383 /* If the editor doesn't need drawing (e.g. after saving the current
384 * document), we need to force a redraw, so the expose event is triggered.
385 * This ensures we don't start colourising before all documents are opened/saved,
386 * only once the editor is drawn. */
387 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
391 #ifdef USE_GIO_FILEMON
392 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
393 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
394 GeanyDocument *doc)
396 g_return_if_fail(doc != NULL);
398 if (file_prefs.disk_check_timeout == 0)
399 return;
401 geany_debug("%s: event: %d previous file status: %d",
402 G_STRFUNC, event, doc->priv->file_disk_status);
403 switch (event)
405 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
407 if (doc->priv->file_disk_status == FILE_IGNORE)
408 doc->priv->file_disk_status = FILE_OK;
409 else
410 doc->priv->file_disk_status = FILE_CHANGED;
411 g_message("%s: FILE_CHANGED", G_STRFUNC);
412 break;
414 case G_FILE_MONITOR_EVENT_DELETED:
416 doc->priv->file_disk_status = FILE_CHANGED;
417 g_message("%s: FILE_MISSING", G_STRFUNC);
418 break;
420 default:
421 break;
423 if (doc->priv->file_disk_status != FILE_OK)
425 ui_update_tab_status(doc);
428 #endif
431 static void document_stop_file_monitoring(GeanyDocument *doc)
433 g_return_if_fail(doc != NULL);
435 if (doc->priv->monitor != NULL)
437 g_object_unref(doc->priv->monitor);
438 doc->priv->monitor = NULL;
443 static void monitor_file_setup(GeanyDocument *doc)
445 g_return_if_fail(doc != NULL);
446 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
447 * doesn't work at all for remote files and legacy polling is too slow. */
448 if (! doc->priv->is_remote)
450 #ifdef USE_GIO_FILEMON
451 gchar *locale_filename;
453 /* stop any previous monitoring */
454 document_stop_file_monitoring(doc);
456 locale_filename = utils_get_locale_from_utf8(doc->file_name);
457 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
459 /* get a file monitor and connect to the 'changed' signal */
460 GFile *file = g_file_new_for_path(locale_filename);
461 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
462 g_signal_connect(doc->priv->monitor, "changed",
463 G_CALLBACK(monitor_file_changed_cb), doc);
465 /* we set the rate limit according to the GUI pref but it's most probably not used */
466 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
468 g_object_unref(file);
470 g_free(locale_filename);
471 #endif
473 doc->priv->file_disk_status = FILE_OK;
477 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
479 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
480 if (DOC_VALID(doc))
482 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
483 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
485 if (source_widget == NULL)
486 source_widget = doc->priv->tag_tree;
488 if (focusw == source_widget)
489 gtk_widget_grab_focus(sci);
494 static gboolean on_idle_focus(gpointer doc)
496 document_try_focus(doc, NULL);
497 return FALSE;
501 /* Creates a new document and editor, adding a tab in the notebook.
502 * @return The created document */
503 static GeanyDocument *document_create(const gchar *utf8_filename)
505 GeanyDocument *doc;
506 gint new_idx;
507 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
509 if (cur_pages == 1)
511 doc = document_get_current();
512 /* remove the empty document first */
513 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
514 /* prevent immediately opening another new doc with
515 * new_document_after_close pref */
516 remove_page(0);
519 new_idx = document_get_new_idx();
520 if (new_idx == -1) /* expand the array, no free places */
522 doc = g_new0(GeanyDocument, 1);
524 new_idx = documents_array->len;
525 g_ptr_array_add(documents_array, doc);
528 doc = documents[new_idx];
530 /* initialize default document settings */
531 doc->priv = g_new0(GeanyDocumentPrivate, 1);
532 doc->index = new_idx;
533 doc->file_name = g_strdup(utf8_filename);
534 doc->editor = editor_create(doc);
535 #ifndef USE_GIO_FILEMON
536 doc->priv->last_check = time(NULL);
537 #endif
539 sidebar_openfiles_add(doc); /* sets doc->iter */
541 notebook_new_tab(doc);
543 /* select document in sidebar */
545 GtkTreeSelection *sel;
547 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
548 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
551 ui_document_buttons_update();
553 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
554 return doc;
559 * Closes the given document.
561 * @param doc The document to remove.
563 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
565 * @since 0.15
567 gboolean document_close(GeanyDocument *doc)
569 g_return_val_if_fail(doc, FALSE);
571 return document_remove_page(document_get_notebook_page(doc));
575 /* Call document_remove_page() instead, this is only needed for document_create()
576 * to prevent re-opening a new document when the last document is closed (if enabled). */
577 static gboolean remove_page(guint page_num)
579 GeanyDocument *doc = document_get_from_page(page_num);
581 g_return_val_if_fail(doc != NULL, FALSE);
583 if (doc->changed && ! dialogs_show_unsaved_file(doc))
584 return FALSE;
586 /* tell any plugins that the document is about to be closed */
587 g_signal_emit_by_name(geany_object, "document-close", doc);
589 /* Checking real_path makes it likely the file exists on disk */
590 if (! main_status.closing_all && doc->real_path != NULL)
591 ui_add_recent_document(doc);
593 doc->is_valid = FALSE;
595 if (! main_status.quitting)
597 notebook_remove_page(page_num);
598 sidebar_remove_document(doc);
599 navqueue_remove_file(doc->file_name);
600 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
602 g_free(doc->encoding);
603 g_free(doc->priv->saved_encoding.encoding);
604 g_free(doc->file_name);
605 g_free(doc->real_path);
606 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
608 editor_destroy(doc->editor);
609 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
611 document_stop_file_monitoring(doc);
613 document_undo_clear(doc);
615 g_free(doc->priv);
617 /* reset document settings to defaults for re-use */
618 memset(doc, 0, sizeof(GeanyDocument));
620 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
622 sidebar_update_tag_list(NULL, FALSE);
623 ui_set_window_title(NULL);
624 ui_save_buttons_toggle(FALSE);
625 ui_update_popup_reundo_items(NULL);
626 ui_document_buttons_update();
627 build_menu_update(NULL);
629 return TRUE;
634 * Removes the given notebook tab at @a page_num and clears all related information
635 * in the document list.
637 * @param page_num The notebook page number to remove.
639 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
641 gboolean document_remove_page(guint page_num)
643 gboolean done = remove_page(page_num);
645 if (done && ui_prefs.new_document_after_close)
646 document_new_file_if_non_open();
648 return done;
652 /* used to keep a record of the unchanged document state encoding */
653 static void store_saved_encoding(GeanyDocument *doc)
655 g_free(doc->priv->saved_encoding.encoding);
656 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
657 doc->priv->saved_encoding.has_bom = doc->has_bom;
661 /* Opens a new empty document only if there are no other documents open */
662 GeanyDocument *document_new_file_if_non_open(void)
664 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
665 return document_new_file(NULL, NULL, NULL);
667 return NULL;
672 * Creates a new document.
673 * Line endings in @a text will be converted to the default setting.
674 * Afterwards, the @c "document-new" signal is emitted for plugins.
676 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
677 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
678 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
680 * @return The new document.
682 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
684 GeanyDocument *doc;
686 if (utf8_filename && g_path_is_absolute(utf8_filename))
688 gchar *tmp;
689 tmp = utils_strdupa(utf8_filename); /* work around const */
690 utils_tidy_path(tmp);
691 utf8_filename = tmp;
693 doc = document_create(utf8_filename);
695 g_assert(doc != NULL);
697 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
698 if (text)
700 GString *template = g_string_new(text);
701 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
703 sci_set_text(doc->editor->sci, template->str);
704 g_string_free(template, TRUE);
706 else
707 sci_clear_all(doc->editor->sci);
709 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
711 sci_set_undo_collection(doc->editor->sci, TRUE);
712 sci_empty_undo_buffer(doc->editor->sci);
714 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
715 /* store the opened encoding for undo/redo */
716 store_saved_encoding(doc);
718 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
719 ft = filetypes_detect_from_document(doc);
721 document_set_filetype(doc, ft); /* also re-parses tags */
723 ui_set_window_title(doc);
724 build_menu_update(doc);
725 document_set_text_changed(doc, FALSE);
726 ui_document_show_hide(doc); /* update the document menu */
728 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
729 /* bring it in front, jump to the start and grab the focus */
730 editor_goto_pos(doc->editor, 0, FALSE);
731 document_try_focus(doc, NULL);
733 #ifdef USE_GIO_FILEMON
734 monitor_file_setup(doc);
735 #else
736 doc->priv->mtime = time(NULL);
737 #endif
739 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
740 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
742 g_signal_emit_by_name(geany_object, "document-new", doc);
744 msgwin_status_add(_("New file \"%s\" opened."),
745 DOC_FILENAME(doc));
747 return doc;
752 * Opens a document specified by @a locale_filename.
753 * Afterwards, the @c "document-open" signal is emitted for plugins.
755 * @param locale_filename The filename of the document to load, in locale encoding.
756 * @param readonly Whether to open the document in read-only mode.
757 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
758 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
760 * @return The document opened or @c NULL.
762 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
763 GeanyFiletype *ft, const gchar *forced_enc)
765 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
769 typedef struct
771 gchar *data; /* null-terminated file data */
772 gsize len; /* string length of data */
773 gchar *enc;
774 gboolean bom;
775 time_t mtime; /* modification time, read by stat::st_mtime */
776 gboolean readonly;
777 } FileData;
780 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
781 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
782 FileData *filedata, const gchar *forced_enc)
784 GError *err = NULL;
785 struct stat st;
787 filedata->data = NULL;
788 filedata->len = 0;
789 filedata->enc = NULL;
790 filedata->bom = FALSE;
791 filedata->readonly = FALSE;
793 if (g_stat(locale_filename, &st) != 0)
795 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
796 display_filename, g_strerror(errno));
797 return FALSE;
800 filedata->mtime = st.st_mtime;
802 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
804 ui_set_statusbar(TRUE, "%s", err->message);
805 g_error_free(err);
806 return FALSE;
809 filedata->len = (gsize) st.st_size;
810 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
811 &filedata->enc, &filedata->bom, &filedata->readonly))
813 if (forced_enc)
815 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
816 display_filename, forced_enc);
818 else
820 ui_set_statusbar(TRUE,
821 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
822 display_filename);
824 g_free(filedata->data);
825 return FALSE;
828 if (filedata->readonly)
830 const gchar *warn_msg = _(
831 "The file \"%s\" could not be opened properly and has been truncated. " \
832 "This can occur if the file contains a NULL byte. " \
833 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
835 if (main_status.main_window_realized)
836 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
838 ui_set_statusbar(TRUE, warn_msg, display_filename);
841 return TRUE;
845 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
846 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
847 * if cl_options.goto_column is set.
849 * returns the new position which may have changed */
850 static gint set_cursor_position(GeanyEditor *editor, gint pos)
852 if (cl_options.goto_line >= 0)
853 { /* goto line which was specified on command line and then undefine the line */
854 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
855 editor->scroll_percent = 0.5F;
856 cl_options.goto_line = -1;
858 else if (pos > 0)
860 sci_set_current_position(editor->sci, pos, FALSE);
861 editor->scroll_percent = 0.5F;
864 if (cl_options.goto_column >= 0)
865 { /* goto column which was specified on command line and then undefine the column */
867 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
868 sci_set_current_position(editor->sci, new_pos, FALSE);
869 editor->scroll_percent = 0.5F;
870 cl_options.goto_column = -1;
871 return new_pos;
873 return sci_get_current_position(editor->sci);
877 /* Count lines that start with some hard tabs then a soft tab. */
878 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
880 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
881 ScintillaObject *sci = editor->sci;
882 gsize count = 0;
883 struct Sci_TextToFind ttf;
884 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
885 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
887 g_free(soft_tab);
889 ttf.chrg.cpMin = 0;
890 ttf.chrg.cpMax = sci_get_length(sci);
891 ttf.lpstrText = regex;
892 while (1)
894 gint pos;
896 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
897 if (pos == -1)
898 break; /* no more matches */
899 count++;
900 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
902 g_free(regex);
903 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
904 return count > sci_get_line_count(sci) * 0.02;
908 /* Detect the indent type based on counting the leading indent characters for each line.
909 * Returns whether detection succeeded, and the detected type in *type_ upon success */
910 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
912 GeanyEditor *editor = doc->editor;
913 ScintillaObject *sci = editor->sci;
914 gint line, line_count;
915 gsize tabs = 0, spaces = 0;
917 if (detect_tabs_and_spaces(editor))
919 *type_ = GEANY_INDENT_TYPE_BOTH;
920 return TRUE;
923 line_count = sci_get_line_count(sci);
924 for (line = 0; line < line_count; line++)
926 gint pos = sci_get_position_from_line(sci, line);
927 gchar c;
929 /* most code will have indent total <= 24, otherwise it's more likely to be
930 * alignment than indentation */
931 if (sci_get_line_indentation(sci, line) > 24)
932 continue;
934 c = sci_get_char_at(sci, pos);
935 if (c == '\t')
936 tabs++;
937 /* check for at least 2 spaces */
938 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
939 spaces++;
941 if (spaces == 0 && tabs == 0)
942 return FALSE;
944 /* the factors may need to be tweaked */
945 if (spaces > tabs * 4)
946 *type_ = GEANY_INDENT_TYPE_SPACES;
947 else if (tabs > spaces * 4)
948 *type_ = GEANY_INDENT_TYPE_TABS;
949 else
950 *type_ = GEANY_INDENT_TYPE_BOTH;
952 return TRUE;
956 /* Detect the indent width based on counting the leading indent characters for each line.
957 * Returns whether detection succeeded, and the detected width in *width_ upon success */
958 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
960 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
961 ScintillaObject *sci = editor->sci;
962 gint line, line_count;
963 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
964 gint count, width, i;
966 /* can't easily detect the supposed width of a tab, guess the default is OK */
967 if (type == GEANY_INDENT_TYPE_TABS)
968 return FALSE;
970 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
971 sci_set_tab_width(sci, 8);
973 line_count = sci_get_line_count(sci);
974 for (line = 0; line < line_count; line++)
976 width = sci_get_line_indentation(sci, line);
977 /* most code will have indent total <= 24, otherwise it's more likely to be
978 * alignment than indentation */
979 if (width > 24)
980 continue;
981 /* < 2 is no indentation */
982 if (width < 2)
983 continue;
985 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
987 if ((width % (i + 2)) == 0)
988 widths[i]++;
991 count = 0;
992 width = iprefs->width;
993 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
995 /* give large indents higher weight not to be fooled by spurious indents */
996 if (widths[i] >= count * 1.5)
998 width = i + 2;
999 count = widths[i];
1003 if (count == 0)
1004 return FALSE;
1006 *width_ = width;
1007 return TRUE;
1011 /* same as detect_indent_width() but uses editor's indent type */
1012 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1014 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1018 void document_apply_indent_settings(GeanyDocument *doc)
1020 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1021 GeanyIndentType type = iprefs->type;
1022 gint width = iprefs->width;
1024 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1026 if (type != iprefs->type)
1028 const gchar *name = NULL;
1030 switch (type)
1032 case GEANY_INDENT_TYPE_SPACES:
1033 name = _("Spaces");
1034 break;
1035 case GEANY_INDENT_TYPE_TABS:
1036 name = _("Tabs");
1037 break;
1038 case GEANY_INDENT_TYPE_BOTH:
1039 name = _("Tabs and Spaces");
1040 break;
1042 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1043 * and Spaces), the second one is the filename */
1044 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1045 DOC_FILENAME(doc));
1048 else if (doc->file_type->indent_type > -1)
1049 type = doc->file_type->indent_type;
1051 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1053 if (width != iprefs->width)
1055 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1056 DOC_FILENAME(doc));
1059 else if (doc->file_type->indent_width > -1)
1060 width = doc->file_type->indent_width;
1062 editor_set_indent(doc->editor, type, width);
1066 void document_show_tab(GeanyDocument *doc)
1068 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1069 document_get_notebook_page(doc));
1073 /* To open a new file, set doc to NULL; filename should be locale encoded.
1074 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1075 * pos is the cursor position, which can be overridden by --line and --column.
1076 * forced_enc can be NULL to detect the file encoding.
1077 * Returns: doc of the opened file or NULL if an error occurred. */
1078 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1079 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1081 gint editor_mode;
1082 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1083 gchar *utf8_filename = NULL;
1084 gchar *display_filename = NULL;
1085 gchar *locale_filename = NULL;
1086 GeanyFiletype *use_ft;
1087 FileData filedata;
1089 if (reload)
1091 utf8_filename = g_strdup(doc->file_name);
1092 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1094 else
1096 /* filename must not be NULL when opening a file */
1097 g_return_val_if_fail(filename, NULL);
1099 #ifdef G_OS_WIN32
1100 /* if filename is a shortcut, try to resolve it */
1101 locale_filename = win32_get_shortcut_target(filename);
1102 #else
1103 locale_filename = g_strdup(filename);
1104 #endif
1105 /* remove relative junk */
1106 utils_tidy_path(locale_filename);
1108 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1109 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1111 /* if file is already open, switch to it and go */
1112 doc = document_find_by_filename(utf8_filename);
1113 if (doc != NULL)
1115 ui_add_recent_document(doc); /* either add or reorder recent item */
1116 /* show the doc before reload dialog */
1117 document_show_tab(doc);
1118 document_check_disk_status(doc, TRUE); /* force a file changed check */
1121 if (reload || doc == NULL)
1122 { /* doc possibly changed */
1123 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1125 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1127 g_free(display_filename);
1128 g_free(utf8_filename);
1129 g_free(locale_filename);
1130 return NULL;
1133 if (! reload)
1135 doc = document_create(utf8_filename);
1136 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1138 /* file exists on disk, set real_path */
1139 SETPTR(doc->real_path, tm_get_real_path(locale_filename));
1141 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1142 monitor_file_setup(doc);
1145 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1146 sci_empty_undo_buffer(doc->editor->sci);
1148 /* add the text to the ScintillaObject */
1149 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1150 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1151 queue_colourise(doc); /* Ensure the document gets colourised. */
1153 /* detect & set line endings */
1154 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1155 sci_set_eol_mode(doc->editor->sci, editor_mode);
1156 g_free(filedata.data);
1158 sci_set_undo_collection(doc->editor->sci, TRUE);
1160 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1161 g_free(doc->encoding); /* if reloading, free old encoding */
1162 doc->encoding = filedata.enc;
1163 doc->has_bom = filedata.bom;
1164 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1166 doc->readonly = readonly || filedata.readonly;
1167 sci_set_readonly(doc->editor->sci, doc->readonly);
1169 /* update line number margin width */
1170 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1171 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1173 if (! reload)
1176 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1177 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1178 doc->editor);
1180 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1182 else
1183 { /* reloading */
1184 document_undo_clear(doc);
1186 use_ft = ft;
1188 /* update taglist, typedef keywords and build menu if necessary */
1189 document_set_filetype(doc, use_ft);
1191 /* set indentation settings after setting the filetype */
1192 if (reload)
1193 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1194 else
1195 document_apply_indent_settings(doc);
1197 document_set_text_changed(doc, FALSE); /* also updates tab state */
1198 ui_document_show_hide(doc); /* update the document menu */
1200 /* finally add current file to recent files menu, but not the files from the last session */
1201 if (! main_status.opening_session_files)
1202 ui_add_recent_document(doc);
1204 if (reload)
1206 g_signal_emit_by_name(geany_object, "document-reload", doc);
1207 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1209 else
1211 g_signal_emit_by_name(geany_object, "document-open", doc);
1212 /* For translators: this is the status window message for opening a file. %d is the number
1213 * of the newly opened file, %s indicates whether the file is opened read-only
1214 * (it is replaced with the string ", read-only"). */
1215 msgwin_status_add(_("File %s opened(%d%s)."),
1216 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1217 (readonly) ? _(", read-only") : "");
1221 g_free(display_filename);
1222 g_free(utf8_filename);
1223 g_free(locale_filename);
1225 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1226 pos = set_cursor_position(doc->editor, pos);
1227 /* now bring the file in front */
1228 editor_goto_pos(doc->editor, pos, FALSE);
1230 /* finally, let the editor widget grab the focus so you can start coding
1231 * right away */
1232 g_idle_add(on_idle_focus, doc);
1233 return doc;
1237 /* Takes a new line separated list of filename URIs and opens each file.
1238 * length is the length of the string */
1239 void document_open_file_list(const gchar *data, gsize length)
1241 guint i;
1242 gchar *filename;
1243 gchar **list;
1245 g_return_if_fail(data != NULL);
1247 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1249 /* stop at the end or first empty item, because last item is empty but not null */
1250 for (i = 0; list[i] != NULL && list[i][0] != '\0'; i++)
1252 filename = utils_get_path_from_uri(list[i]);
1253 if (filename == NULL)
1254 continue;
1255 document_open_file(filename, FALSE, NULL, NULL);
1256 g_free(filename);
1259 g_strfreev(list);
1264 * Opens each file in the list @a filenames.
1265 * Internally, document_open_file() is called for every list item.
1267 * @param filenames A list of filenames to load, in locale encoding.
1268 * @param readonly Whether to open the document in read-only mode.
1269 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1270 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1272 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1273 const gchar *forced_enc)
1275 const GSList *item;
1277 for (item = filenames; item != NULL; item = g_slist_next(item))
1279 document_open_file(item->data, readonly, ft, forced_enc);
1285 * Reloads the document with the specified file encoding
1286 * @a forced_enc or @c NULL to auto-detect the file encoding.
1288 * @param doc The document to reload.
1289 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1291 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1293 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1295 gint pos = 0;
1296 GeanyDocument *new_doc;
1298 g_return_val_if_fail(doc != NULL, FALSE);
1300 /* try to set the cursor to the position before reloading */
1301 pos = sci_get_current_position(doc->editor->sci);
1302 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1304 return (new_doc != NULL);
1308 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1310 #ifndef USE_GIO_FILEMON
1311 struct stat st;
1313 g_return_val_if_fail(doc != NULL, FALSE);
1315 /* stat the file to get the timestamp, otherwise on Windows the actual
1316 * timestamp can be ahead of time(NULL) */
1317 if (g_stat(locale_filename, &st) != 0)
1319 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1320 g_strerror(errno));
1321 return FALSE;
1324 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1325 #endif
1326 return TRUE;
1330 /* Sets line and column to the given position byte_pos in the document.
1331 * byte_pos is the position counted in bytes, not characters */
1332 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1334 gint i;
1335 gint line_start;
1337 /* for some reason we can use byte count instead of character count here */
1338 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1339 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1340 /* get the column in the line */
1341 *column = byte_pos - line_start;
1343 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1344 * skip one byte(i++) and decrease the column number which is based on byte count */
1345 for (i = line_start; i < (line_start + *column); i++)
1347 if (sci_get_char_at(doc->editor->sci, i) < 0)
1349 (*column)--;
1350 i++;
1356 static void replace_header_filename(GeanyDocument *doc)
1358 gchar *filebase;
1359 gchar *filename;
1360 struct Sci_TextToFind ttf;
1362 g_return_if_fail(doc != NULL);
1363 g_return_if_fail(doc->file_type != NULL);
1365 if (doc->file_type->extension)
1366 filebase = g_strconcat("\\<", GEANY_STRING_UNTITLED, "\\.\\w+", NULL);
1367 else
1368 filebase = g_strdup(GEANY_STRING_UNTITLED);
1370 filename = g_path_get_basename(doc->file_name);
1372 /* only search the first 3 lines */
1373 ttf.chrg.cpMin = 0;
1374 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 3);
1375 ttf.lpstrText = filebase;
1377 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf) != -1)
1379 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1380 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1381 sci_replace_target(doc->editor->sci, filename, FALSE);
1383 g_free(filebase);
1384 g_free(filename);
1389 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1390 * you still have to call @ref document_save_file_as() to change the @a doc object.
1391 * It also stops monitoring for file changes to prevent receiving too many file change events
1392 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1394 * @param doc The current document which should be renamed.
1395 * @param new_filename The new filename in UTF-8 encoding.
1397 * @since 0.16
1399 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1401 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1402 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1403 gint result;
1405 /* stop file monitoring to avoid getting events for deleting/creating files,
1406 * it's re-setup in document_save_file_as() */
1407 document_stop_file_monitoring(doc);
1409 result = g_rename(old_locale_filename, new_locale_filename);
1410 if (result != 0)
1412 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1413 _("Error renaming file."), g_strerror(errno));
1415 g_free(old_locale_filename);
1416 g_free(new_locale_filename);
1420 /* Return TRUE if the document doesn't have a full filename set.
1421 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1422 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1423 * new files. */
1424 gboolean document_need_save_as(GeanyDocument *doc)
1426 g_return_val_if_fail(doc != NULL, FALSE);
1428 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1433 * Saves the document, detecting the filetype.
1435 * @param doc The document for the file to save.
1436 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1437 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1439 * @see document_save_file().
1441 * @since 0.16
1443 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1445 gboolean ret;
1447 g_return_val_if_fail(doc != NULL, FALSE);
1449 if (utf8_fname != NULL)
1450 SETPTR(doc->file_name, g_strdup(utf8_fname));
1452 /* reset real path, it's retrieved again in document_save() */
1453 SETPTR(doc->real_path, NULL);
1455 /* detect filetype */
1456 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1458 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1460 document_set_filetype(doc, ft);
1461 if (document_get_current() == doc)
1463 ignore_callback = TRUE;
1464 filetypes_select_radio_item(doc->file_type);
1465 ignore_callback = FALSE;
1468 replace_header_filename(doc);
1470 ret = document_save_file(doc, TRUE);
1472 /* file monitoring support, add file monitoring after the file has been saved
1473 * to ignore any earlier events */
1474 monitor_file_setup(doc);
1475 doc->priv->file_disk_status = FILE_IGNORE;
1477 if (ret)
1478 ui_add_recent_document(doc);
1479 return ret;
1483 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1485 GError *conv_error = NULL;
1486 gchar* conv_file_contents = NULL;
1487 gsize bytes_read;
1488 gsize conv_len;
1490 g_return_val_if_fail(data != NULL && *data != NULL, FALSE);
1491 g_return_val_if_fail(len != NULL, FALSE);
1493 /* try to convert it from UTF-8 to original encoding */
1494 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1495 &bytes_read, &conv_len, &conv_error);
1497 if (conv_error != NULL)
1499 gchar *text = g_strdup_printf(
1500 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1501 doc->encoding);
1502 gchar *error_text;
1504 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1506 gchar *context = NULL;
1507 gint line, column;
1508 gint context_len;
1509 gunichar unic;
1510 /* don't read over the doc length */
1511 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1512 context = g_malloc(7); /* read 6 bytes from Sci + '\0' */
1513 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1515 /* take only one valid Unicode character from the context and discard the leftover */
1516 unic = g_utf8_get_char_validated(context, -1);
1517 context_len = g_unichar_to_utf8(unic, context);
1518 context[context_len] = '\0';
1519 get_line_column_from_pos(doc, bytes_read, &line, &column);
1521 error_text = g_strdup_printf(
1522 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1523 conv_error->message, context, line + 1, column);
1524 g_free(context);
1526 else
1527 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1529 geany_debug("encoding error: %s", conv_error->message);
1530 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1531 g_error_free(conv_error);
1532 g_free(text);
1533 g_free(error_text);
1534 return FALSE;
1536 else
1538 g_free(*data);
1539 *data = conv_file_contents;
1540 *len = conv_len;
1542 return TRUE;
1546 static gchar *write_data_to_disk(const gchar *locale_filename,
1547 const gchar *data, gsize len)
1549 GError *error = NULL;
1551 if (file_prefs.use_safe_file_saving)
1553 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1554 * This is the only option that handles disk space exhaustion. */
1555 if (g_file_set_contents(locale_filename, data, len, &error))
1556 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1558 else if (file_prefs.use_gio_unsafe_file_saving)
1560 GFile *fp;
1562 /* Use GIO API to save file (GVFS-safe)
1563 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1564 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1565 fp = g_file_new_for_path(locale_filename);
1566 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1567 G_FILE_CREATE_NONE, NULL, NULL, &error);
1568 g_object_unref(fp);
1570 else
1572 FILE *fp;
1573 int save_errno;
1574 gchar *display_name = g_filename_display_name(locale_filename);
1576 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1577 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1578 errno = 0;
1579 fp = g_fopen(locale_filename, "wb");
1580 if (fp == NULL)
1582 save_errno = errno;
1584 g_set_error(&error,
1585 G_FILE_ERROR,
1586 g_file_error_from_errno(save_errno),
1587 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1588 display_name,
1589 g_strerror(save_errno));
1591 else
1593 gsize bytes_written;
1595 errno = 0;
1596 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1598 if (len != bytes_written)
1600 save_errno = errno;
1602 g_set_error(&error,
1603 G_FILE_ERROR,
1604 g_file_error_from_errno(save_errno),
1605 _("Failed to write file '%s': fwrite() failed: %s"),
1606 display_name,
1607 g_strerror(save_errno));
1610 errno = 0;
1611 /* preserve the fwrite() error if any */
1612 if (fclose(fp) != 0 && error == NULL)
1614 save_errno = errno;
1616 g_set_error(&error,
1617 G_FILE_ERROR,
1618 g_file_error_from_errno(save_errno),
1619 _("Failed to close file '%s': fclose() failed: %s"),
1620 display_name,
1621 g_strerror(save_errno));
1625 g_free(display_name);
1627 if (error != NULL)
1629 gchar *msg = g_strdup(error->message);
1630 g_error_free(error);
1631 /* geany will warn about file truncation for unsafe saving below */
1632 return msg;
1634 return NULL;
1638 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1639 const gchar *data, gsize len)
1641 gchar *err;
1643 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1644 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1646 err = write_data_to_disk(locale_filename, data, len);
1647 if (err)
1648 return err;
1650 /* now the file is on disk, set real_path */
1651 if (doc->real_path == NULL)
1653 doc->real_path = tm_get_real_path(locale_filename);
1654 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1655 monitor_file_setup(doc);
1657 return NULL;
1662 * Saves the document.
1663 * Also shows the Save As dialog if necessary.
1664 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1666 * Saving may include replacing tabs by spaces,
1667 * stripping trailing spaces and adding a final new line at the end of the file, depending
1668 * on user preferences. Then the @c "document-before-save" signal is emitted,
1669 * allowing plugins to modify the document before it is saved, and data is
1670 * actually written to disk.
1672 * On successful saving:
1673 * - GeanyDocument::real_path is set.
1674 * - The filetype is set again or auto-detected if it wasn't set yet.
1675 * - The @c "document-save" signal is emitted for plugins.
1677 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1678 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1679 * added in Geany 1.22.
1681 * @param doc The document to save.
1682 * @param force Whether to save the file even if it is not modified.
1684 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1686 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1688 gchar *errmsg;
1689 gchar *data;
1690 gsize len;
1691 gchar *locale_filename;
1692 const GeanyFilePrefs *fp;
1694 g_return_val_if_fail(doc != NULL, FALSE);
1696 if (document_need_save_as(doc))
1698 /* ensure doc is the current tab before showing the dialog */
1699 document_show_tab(doc);
1700 return dialogs_show_save_as();
1703 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1704 if (! force && ! ui_prefs.allow_always_save && (! doc->changed || doc->readonly))
1705 return FALSE;
1707 fp = project_get_file_prefs();
1708 /* replaces tabs by spaces but only if the current file is not a Makefile */
1709 if (fp->replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1710 editor_replace_tabs(doc->editor);
1711 /* strip trailing spaces */
1712 if (fp->strip_trailing_spaces)
1713 editor_strip_trailing_spaces(doc->editor);
1714 /* ensure the file has a newline at the end */
1715 if (fp->final_new_line)
1716 editor_ensure_final_newline(doc->editor);
1717 /* ensure newlines are consistent */
1718 if (fp->ensure_convert_new_lines)
1719 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1721 /* notify plugins which may wish to modify the document before it's saved */
1722 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1724 len = sci_get_length(doc->editor->sci) + 1;
1725 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1726 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1727 * encoding, it will be converted to doc->encoding below and this conversion
1728 * also changes the BOM */
1729 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1730 data[0] = (gchar) 0xef;
1731 data[1] = (gchar) 0xbb;
1732 data[2] = (gchar) 0xbf;
1733 sci_get_text(doc->editor->sci, len, data + 3);
1734 len += 3;
1736 else
1738 data = (gchar*) g_malloc(len);
1739 sci_get_text(doc->editor->sci, len, data);
1742 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1743 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1744 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1746 if (! save_convert_to_encoding(doc, &data, &len))
1748 g_free(data);
1749 return FALSE;
1752 else
1754 len = strlen(data);
1757 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1759 /* ignore file changed notification when the file is written */
1760 doc->priv->file_disk_status = FILE_IGNORE;
1762 /* actually write the content of data to the file on disk */
1763 errmsg = save_doc(doc, locale_filename, data, len);
1764 g_free(data);
1766 if (errmsg != NULL)
1768 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1770 if (!file_prefs.use_safe_file_saving)
1772 SETPTR(errmsg,
1773 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1775 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1776 doc->priv->file_disk_status = FILE_OK;
1777 utils_beep();
1778 g_free(locale_filename);
1779 g_free(errmsg);
1780 return FALSE;
1783 /* store the opened encoding for undo/redo */
1784 store_saved_encoding(doc);
1786 /* ignore the following things if we are quitting */
1787 if (! main_status.quitting)
1789 sci_set_savepoint(doc->editor->sci);
1791 if (file_prefs.disk_check_timeout > 0)
1792 document_update_timestamp(doc, locale_filename);
1794 /* update filetype-related things */
1795 document_set_filetype(doc, doc->file_type);
1797 document_update_tab_label(doc);
1799 msgwin_status_add(_("File %s saved."), doc->file_name);
1800 ui_update_statusbar(doc, -1);
1801 #ifdef HAVE_VTE
1802 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1803 #endif
1805 g_free(locale_filename);
1807 g_signal_emit_by_name(geany_object, "document-save", doc);
1809 return TRUE;
1813 /* special search function, used from the find entry in the toolbar
1814 * return TRUE if text was found otherwise FALSE
1815 * return also TRUE if text is empty */
1816 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1817 gboolean backwards)
1819 gint start_pos, search_pos;
1820 struct Sci_TextToFind ttf;
1822 g_return_val_if_fail(text != NULL, FALSE);
1823 g_return_val_if_fail(doc != NULL, FALSE);
1824 if (! *text)
1825 return TRUE;
1827 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1828 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1830 /* search cursor to end or start */
1831 ttf.chrg.cpMin = start_pos;
1832 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1833 ttf.lpstrText = (gchar *)text;
1834 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1836 /* if no match, search start (or end) to cursor */
1837 if (search_pos == -1)
1839 if (backwards)
1841 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1842 ttf.chrg.cpMax = start_pos;
1844 else
1846 ttf.chrg.cpMin = 0;
1847 ttf.chrg.cpMax = start_pos + strlen(text);
1849 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1852 if (search_pos != -1)
1854 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1856 /* unfold maybe folded results */
1857 sci_ensure_line_is_visible(doc->editor->sci, line);
1859 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1860 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1862 if (! editor_line_in_view(doc->editor, line))
1863 { /* we need to force scrolling in case the cursor is outside of the current visible area
1864 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1865 * while searching */
1866 editor_scroll_to_line(doc->editor, -1, 0.3F);
1868 else
1869 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1870 return TRUE;
1872 else
1874 if (! inc)
1876 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1878 utils_beep();
1879 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1880 return FALSE;
1885 /* General search function, used from the find dialog.
1886 * Returns -1 on failure or the start position of the matching text.
1887 * Will skip past any selection, ignoring it.
1889 * @param text Text to find.
1890 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1892 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1893 gint flags, gboolean search_backwards, gboolean scroll, GtkWidget *parent)
1895 gint selection_end, selection_start, search_pos;
1897 g_return_val_if_fail(doc != NULL && text != NULL, -1);
1898 if (! *text)
1899 return -1;
1901 /* Sci doesn't support searching backwards with a regex */
1902 if (flags & SCFIND_REGEXP)
1903 search_backwards = FALSE;
1905 if (!original_text)
1906 original_text = text;
1908 selection_start = sci_get_selection_start(doc->editor->sci);
1909 selection_end = sci_get_selection_end(doc->editor->sci);
1910 if ((selection_end - selection_start) > 0)
1911 { /* there's a selection so go to the end */
1912 if (search_backwards)
1913 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1914 else
1915 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1918 sci_set_search_anchor(doc->editor->sci);
1919 if (search_backwards)
1920 search_pos = sci_search_prev(doc->editor->sci, flags, text);
1921 else
1922 search_pos = search_find_next(doc->editor->sci, text, flags);
1924 if (search_pos != -1)
1926 /* unfold maybe folded results */
1927 sci_ensure_line_is_visible(doc->editor->sci,
1928 sci_get_line_from_position(doc->editor->sci, search_pos));
1929 if (scroll)
1930 doc->editor->scroll_percent = 0.3F;
1932 else
1934 gint sci_len = sci_get_length(doc->editor->sci);
1936 /* if we just searched the whole text, give up searching. */
1937 if ((selection_end == 0 && ! search_backwards) ||
1938 (selection_end == sci_len && search_backwards))
1940 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
1941 utils_beep();
1942 return -1;
1945 /* we searched only part of the document, so ask whether to wraparound. */
1946 if (search_prefs.always_wrap ||
1947 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
1948 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
1950 gint ret;
1952 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
1953 ret = document_find_text(doc, text, original_text, flags, search_backwards, scroll, parent);
1954 if (ret == -1)
1955 { /* return to original cursor position if not found */
1956 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
1958 return ret;
1961 return search_pos;
1965 /* Replaces the selection if it matches, otherwise just finds the next match.
1966 * Returns: start of replaced text, or -1 if no replacement was made
1968 * @param find_text Text to find.
1969 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
1971 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
1972 const gchar *replace_text, gint flags, gboolean search_backwards)
1974 gint selection_end, selection_start, search_pos;
1976 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
1978 if (! *find_text)
1979 return -1;
1981 /* Sci doesn't support searching backwards with a regex */
1982 if (flags & SCFIND_REGEXP)
1983 search_backwards = FALSE;
1985 if (!original_find_text)
1986 original_find_text = find_text;
1988 selection_start = sci_get_selection_start(doc->editor->sci);
1989 selection_end = sci_get_selection_end(doc->editor->sci);
1990 if (selection_end == selection_start)
1992 /* no selection so just find the next match */
1993 document_find_text(doc, find_text, original_find_text, flags, search_backwards, TRUE, NULL);
1994 return -1;
1996 /* there's a selection so go to the start before finding to search through it
1997 * this ensures there is a match */
1998 if (search_backwards)
1999 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2000 else
2001 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2003 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, TRUE, NULL);
2004 /* return if the original selected text did not match (at the start of the selection) */
2005 if (search_pos != selection_start)
2006 return -1;
2008 if (search_pos != -1)
2010 gint replace_len;
2011 /* search next/prev will select matching text, which we use to set the replace target */
2012 sci_target_from_selection(doc->editor->sci);
2013 replace_len = search_replace_target(doc->editor->sci, replace_text, flags & SCFIND_REGEXP);
2014 /* select the replacement - find text will skip past the selected text */
2015 sci_set_selection_start(doc->editor->sci, search_pos);
2016 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2018 else
2020 /* no match in the selection */
2021 utils_beep();
2023 return search_pos;
2027 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2028 const gchar *original_replace_text)
2030 gchar *filename;
2032 if (count == 0)
2034 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2035 return;
2038 filename = g_path_get_basename(DOC_FILENAME(doc));
2039 ui_set_statusbar(TRUE, ngettext(
2040 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2041 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2042 count), filename, count, original_find_text, original_replace_text);
2043 g_free(filename);
2047 /* Replace all text matches in a certain range within document.
2048 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2049 * or -1 if no text was found.
2050 * scroll_to_match is whether to scroll the last replacement in view (which also
2051 * clears the selection).
2052 * Returns: the number of replacements made. */
2053 static guint
2054 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2055 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2057 gint count = 0;
2058 struct Sci_TextToFind ttf;
2059 ScintillaObject *sci;
2061 if (new_range_end != NULL)
2062 *new_range_end = -1;
2064 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2066 if (! *find_text || doc->readonly)
2067 return 0;
2069 sci = doc->editor->sci;
2071 ttf.chrg.cpMin = start;
2072 ttf.chrg.cpMax = end;
2073 ttf.lpstrText = (gchar*)find_text;
2075 sci_start_undo_action(sci);
2076 count = search_replace_range(sci, &ttf, flags, replace_text);
2077 sci_end_undo_action(sci);
2079 if (count > 0)
2080 { /* scroll last match in view, will destroy the existing selection */
2081 if (scroll_to_match)
2082 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2084 if (new_range_end != NULL)
2085 *new_range_end = ttf.chrg.cpMax;
2087 return count;
2091 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2092 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2094 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2095 gint max_column = 0, count = 0;
2096 gboolean replaced = FALSE;
2098 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2100 if (! *find_text)
2101 return;
2103 selection_start = sci_get_selection_start(doc->editor->sci);
2104 selection_end = sci_get_selection_end(doc->editor->sci);
2105 /* do we have a selection? */
2106 if ((selection_end - selection_start) == 0)
2108 utils_beep();
2109 return;
2112 selection_mode = sci_get_selection_mode(doc->editor->sci);
2113 selected_lines = sci_get_lines_selected(doc->editor->sci);
2114 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2115 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2117 gint first_line, line;
2119 sci_start_undo_action(doc->editor->sci);
2121 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2122 /* Find the last line with chars selected (not EOL char) */
2123 last_line = sci_get_line_from_position(doc->editor->sci,
2124 selection_end - editor_get_eol_char_len(doc->editor));
2125 last_line = MAX(first_line, last_line);
2126 for (line = first_line; line < (first_line + selected_lines); line++)
2128 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2129 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2131 /* skip line if there is no selection */
2132 if (line_start != INVALID_POSITION)
2134 /* don't let document_replace_range() scroll to match to keep our selection */
2135 gint new_sel_end;
2137 count += document_replace_range(doc, find_text, replace_text, flags,
2138 line_start, line_end, FALSE, &new_sel_end);
2139 if (new_sel_end != -1)
2141 replaced = TRUE;
2142 /* this gets the greatest column within the selection after replacing */
2143 max_column = MAX(max_column,
2144 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2148 sci_end_undo_action(doc->editor->sci);
2150 else /* handle normal line selection */
2152 count += document_replace_range(doc, find_text, replace_text, flags,
2153 selection_start, selection_end, TRUE, &selection_end);
2154 if (selection_end != -1)
2155 replaced = TRUE;
2158 if (replaced)
2159 { /* update the selection for the new endpoint */
2161 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2163 /* now we can scroll to the selection and destroy it because we rebuild it later */
2164 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2166 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2167 * the highest column on the last line. The wrapped selection is completely different
2168 * from the original one, so skip the selection at all */
2169 /* TODO is there a better way to handle the wrapped selection? */
2170 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2171 { /* for keeping and adjusting the selection in multi line rectangle selection we
2172 * need the last line of the original selection and the greatest column number after
2173 * replacing and set the selection end to the last line at the greatest column */
2174 sci_set_selection_start(doc->editor->sci, selection_start);
2175 sci_set_selection_end(doc->editor->sci,
2176 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2177 sci_set_selection_mode(doc->editor->sci, selection_mode);
2180 else
2182 sci_set_selection_start(doc->editor->sci, selection_start);
2183 sci_set_selection_end(doc->editor->sci, selection_end);
2186 else /* no replacements */
2187 utils_beep();
2189 show_replace_summary(doc, count, original_find_text, original_replace_text);
2193 /* returns number of replacements made. */
2194 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2195 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2197 gint len, count;
2198 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2200 if (! *find_text)
2201 return FALSE;
2203 len = sci_get_length(doc->editor->sci);
2204 count = document_replace_range(
2205 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2207 show_replace_summary(doc, count, original_find_text, original_replace_text);
2208 return count;
2213 * Parses or re-parses the document's buffer and updates the type
2214 * keywords and symbol list.
2216 * @param doc The document.
2218 void document_update_tags(GeanyDocument *doc)
2220 guchar *buffer_ptr;
2221 gsize len;
2223 g_return_if_fail(DOC_VALID(doc));
2224 g_return_if_fail(app->tm_workspace != NULL);
2226 /* early out if it's a new file or doesn't support tags */
2227 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2229 /* We must call sidebar_update_tag_list() before returning,
2230 * to ensure that the symbol list is always updated properly (e.g.
2231 * when creating a new document with a partial filename set. */
2232 sidebar_update_tag_list(doc, FALSE);
2233 return;
2236 /* create a new TM file if there isn't one yet */
2237 if (! doc->tm_file)
2239 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2240 const gchar *name;
2242 /* lookup the name rather than using filetype name to support custom filetypes */
2243 name = tm_source_file_get_lang_name(doc->file_type->lang);
2244 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2245 g_free(locale_filename);
2247 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2249 tm_work_object_free(doc->tm_file);
2250 doc->tm_file = NULL;
2254 /* early out if there's no work object and we couldn't create one */
2255 if (doc->tm_file == NULL)
2257 /* We must call sidebar_update_tag_list() before returning,
2258 * to ensure that the symbol list is always updated properly (e.g.
2259 * when creating a new document with a partial filename set. */
2260 sidebar_update_tag_list(doc, FALSE);
2261 return;
2264 len = sci_get_length(doc->editor->sci);
2265 /* tm_source_file_buffer_update() below don't support 0-length data,
2266 * so just empty the tags array and leave */
2267 if (len < 1)
2269 tm_tags_array_free(doc->tm_file->tags_array, FALSE);
2270 sidebar_update_tag_list(doc, FALSE);
2271 return;
2274 /* Parse Scintilla's buffer directly using TagManager
2275 * Note: this buffer *MUST NOT* be modified */
2276 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2277 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2279 sidebar_update_tag_list(doc, TRUE);
2280 document_highlight_tags(doc);
2284 /* Re-highlights type keywords without re-parsing the whole document. */
2285 void document_highlight_tags(GeanyDocument *doc)
2287 GString *keywords_str;
2288 gchar *keywords;
2289 gint keyword_idx;
2291 /* some filetypes support type keywords (such as struct names), but not
2292 * necessarily all filetypes for a particular scintilla lexer. this
2293 * tells us whether the filetype supports keywords, and if so
2294 * which index to use for the scintilla keywords set. */
2295 switch (doc->file_type->id)
2297 case GEANY_FILETYPES_C:
2298 case GEANY_FILETYPES_CPP:
2299 case GEANY_FILETYPES_CS:
2300 case GEANY_FILETYPES_D:
2301 case GEANY_FILETYPES_JAVA:
2302 case GEANY_FILETYPES_OBJECTIVEC:
2303 case GEANY_FILETYPES_VALA:
2306 /* index of the keyword set in the Scintilla lexer, for
2307 * example in LexCPP.cxx, see "cppWordLists" global array.
2308 * TODO: this magic number should be a member of the filetype */
2309 keyword_idx = 3;
2310 break;
2312 default:
2313 return; /* early out if type keywords are not supported */
2315 if (!app->tm_workspace->work_object.tags_array)
2316 return;
2318 /* get any type keywords and tell scintilla about them
2319 * this will cause the type keywords to be colourized in scintilla */
2320 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2321 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2322 if (keywords_str)
2324 keywords = g_string_free(keywords_str, FALSE);
2325 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2326 g_free(keywords);
2327 queue_colourise(doc); /* force re-highlighting the entire document */
2332 static gboolean on_document_update_tag_list_idle(gpointer data)
2334 GeanyDocument *doc = data;
2336 if (! DOC_VALID(doc))
2337 return FALSE;
2339 if (! main_status.quitting)
2340 document_update_tags(doc);
2342 doc->priv->tag_list_update_source = 0;
2344 /* don't update the tags until another modification of the buffer */
2345 return FALSE;
2349 void document_update_tag_list_in_idle(GeanyDocument *doc)
2351 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2352 return;
2354 /* prevent "stacking up" callback handlers, we only need one to run soon */
2355 if (doc->priv->tag_list_update_source != 0)
2356 g_source_remove(doc->priv->tag_list_update_source);
2358 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2359 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2363 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2364 gboolean filetype_changed)
2366 g_return_if_fail(doc);
2367 if (type == NULL)
2368 type = filetypes[GEANY_FILETYPES_NONE];
2370 if (filetype_changed)
2372 doc->file_type = type;
2374 /* delete tm file object to force creation of a new one */
2375 if (doc->tm_file != NULL)
2377 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2378 doc->tm_file = NULL;
2380 /* load tags files before highlighting (some lexers highlight global typenames) */
2381 if (type->id != GEANY_FILETYPES_NONE)
2382 symbols_global_tags_loaded(type->id);
2384 highlighting_set_styles(doc->editor->sci, type);
2385 editor_set_indentation_guides(doc->editor);
2386 build_menu_update(doc);
2387 queue_colourise(doc);
2388 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2391 document_update_tags(doc);
2395 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2396 * @param doc The document to use.
2397 * @param type The filetype. */
2398 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2400 gboolean ft_changed;
2401 GeanyFiletype *old_ft;
2403 g_return_if_fail(doc);
2404 if (type == NULL)
2405 type = filetypes[GEANY_FILETYPES_NONE];
2407 old_ft = doc->file_type;
2408 geany_debug("%s : %s (%s)",
2409 (doc->file_name != NULL) ? doc->file_name : "unknown",
2410 type->name,
2411 (doc->encoding != NULL) ? doc->encoding : "unknown");
2413 ft_changed = (doc->file_type != type); /* filetype has changed */
2414 document_load_config(doc, type, ft_changed);
2416 if (ft_changed)
2418 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2420 /* assume that if previous filetype was none and the settings are the default ones, this
2421 * is the first time the filetype is carefully set, so we should apply indent settings */
2422 if (old_ft && old_ft->id == GEANY_FILETYPES_NONE &&
2423 doc->editor->indent_type == iprefs->type &&
2424 doc->editor->indent_width == iprefs->width)
2426 document_apply_indent_settings(doc);
2427 ui_document_show_hide(doc);
2430 sidebar_openfiles_update(doc); /* to update the icon */
2431 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2436 void document_reload_config(GeanyDocument *doc)
2438 document_load_config(doc, doc->file_type, TRUE);
2443 * Sets the encoding of a document.
2444 * This function only set the encoding of the %document, it does not any conversions. The new
2445 * encoding is used when e.g. saving the file.
2447 * @param doc The document to use.
2448 * @param new_encoding The encoding to be set for the document.
2450 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2452 if (doc == NULL || new_encoding == NULL ||
2453 utils_str_equal(new_encoding, doc->encoding))
2454 return;
2456 g_free(doc->encoding);
2457 doc->encoding = g_strdup(new_encoding);
2459 ui_update_statusbar(doc, -1);
2460 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2461 encodings_is_unicode_charset(doc->encoding));
2465 /* own Undo / Redo implementation to be able to undo / redo changes
2466 * to the encoding or the Unicode BOM (which are Scintilla independet).
2467 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2469 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2470 void document_undo_clear(GeanyDocument *doc)
2472 undo_action *a;
2474 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2476 a = g_trash_stack_pop(&doc->priv->undo_actions);
2477 if (G_LIKELY(a != NULL))
2479 switch (a->type)
2481 case UNDO_ENCODING: g_free(a->data); break;
2482 default: break;
2484 g_free(a);
2487 doc->priv->undo_actions = NULL;
2489 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2491 a = g_trash_stack_pop(&doc->priv->redo_actions);
2492 if (G_LIKELY(a != NULL))
2494 switch (a->type)
2496 case UNDO_ENCODING: g_free(a->data); break;
2497 default: break;
2499 g_free(a);
2502 doc->priv->redo_actions = NULL;
2504 if (! main_status.quitting && doc->editor != NULL)
2505 document_set_text_changed(doc, FALSE);
2509 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2511 undo_action *action;
2513 g_return_if_fail(doc != NULL);
2515 action = g_new0(undo_action, 1);
2516 action->type = type;
2517 action->data = data;
2519 g_trash_stack_push(&doc->priv->undo_actions, action);
2521 document_set_text_changed(doc, TRUE);
2522 ui_update_popup_reundo_items(doc);
2526 gboolean document_can_undo(GeanyDocument *doc)
2528 g_return_val_if_fail(doc != NULL, FALSE);
2530 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2531 return TRUE;
2532 else
2533 return FALSE;
2537 static void update_changed_state(GeanyDocument *doc)
2539 doc->changed =
2540 (sci_is_modified(doc->editor->sci) ||
2541 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2542 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2543 document_set_text_changed(doc, doc->changed);
2547 void document_undo(GeanyDocument *doc)
2549 undo_action *action;
2551 g_return_if_fail(doc != NULL);
2553 action = g_trash_stack_pop(&doc->priv->undo_actions);
2555 if (G_UNLIKELY(action == NULL))
2557 /* fallback, should not be necessary */
2558 geany_debug("%s: fallback used", G_STRFUNC);
2559 sci_undo(doc->editor->sci);
2561 else
2563 switch (action->type)
2565 case UNDO_SCINTILLA:
2567 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2569 sci_undo(doc->editor->sci);
2570 break;
2572 case UNDO_BOM:
2574 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2576 doc->has_bom = GPOINTER_TO_INT(action->data);
2577 ui_update_statusbar(doc, -1);
2578 ui_document_show_hide(doc);
2579 break;
2581 case UNDO_ENCODING:
2583 /* use the "old" encoding */
2584 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2586 document_set_encoding(doc, (const gchar*)action->data);
2588 ignore_callback = TRUE;
2589 encodings_select_radio_item((const gchar*)action->data);
2590 ignore_callback = FALSE;
2592 g_free(action->data);
2593 break;
2595 default: break;
2598 g_free(action); /* free the action which was taken from the stack */
2600 update_changed_state(doc);
2601 ui_update_popup_reundo_items(doc);
2605 gboolean document_can_redo(GeanyDocument *doc)
2607 g_return_val_if_fail(doc != NULL, FALSE);
2609 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2610 return TRUE;
2611 else
2612 return FALSE;
2616 void document_redo(GeanyDocument *doc)
2618 undo_action *action;
2620 g_return_if_fail(doc != NULL);
2622 action = g_trash_stack_pop(&doc->priv->redo_actions);
2624 if (G_UNLIKELY(action == NULL))
2626 /* fallback, should not be necessary */
2627 geany_debug("%s: fallback used", G_STRFUNC);
2628 sci_redo(doc->editor->sci);
2630 else
2632 switch (action->type)
2634 case UNDO_SCINTILLA:
2636 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2638 sci_redo(doc->editor->sci);
2639 break;
2641 case UNDO_BOM:
2643 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2645 doc->has_bom = GPOINTER_TO_INT(action->data);
2646 ui_update_statusbar(doc, -1);
2647 ui_document_show_hide(doc);
2648 break;
2650 case UNDO_ENCODING:
2652 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2654 document_set_encoding(doc, (const gchar*)action->data);
2656 ignore_callback = TRUE;
2657 encodings_select_radio_item((const gchar*)action->data);
2658 ignore_callback = FALSE;
2660 g_free(action->data);
2661 break;
2663 default: break;
2666 g_free(action); /* free the action which was taken from the stack */
2668 update_changed_state(doc);
2669 ui_update_popup_reundo_items(doc);
2673 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2675 undo_action *action;
2677 g_return_if_fail(doc != NULL);
2679 action = g_new0(undo_action, 1);
2680 action->type = type;
2681 action->data = data;
2683 g_trash_stack_push(&doc->priv->redo_actions, action);
2685 document_set_text_changed(doc, TRUE);
2686 ui_update_popup_reundo_items(doc);
2691 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2692 * Returned colors are red if the document has changes, green if the document is read-only
2693 * or simply @c NULL if the document is unmodified but writable.
2695 * @param doc The document to use.
2697 * @return The color for the document or @c NULL if the default color should be used. The color
2698 * object is owned by Geany and should not be modified or freed.
2700 * @since 0.16
2702 const GdkColor *document_get_status_color(GeanyDocument *doc)
2704 static GdkColor red = {0, 0xFFFF, 0, 0};
2705 static GdkColor green = {0, 0, 0x7FFF, 0};
2706 #ifdef USE_GIO_FILEMON
2707 static GdkColor orange = {0, 0xFFFF, 0x7FFF, 0};
2708 #endif
2709 GdkColor *color = NULL;
2711 g_return_val_if_fail(doc != NULL, NULL);
2713 if (doc->changed)
2714 color = &red;
2715 #ifdef USE_GIO_FILEMON
2716 else if (doc->priv->file_disk_status == FILE_CHANGED)
2717 color = &orange;
2718 #endif
2719 else if (doc->readonly)
2720 color = &green;
2722 return color; /* return pointer to static GdkColor. */
2726 /** Accessor function for @ref GeanyData::documents_array items.
2727 * @warning Always check the returned document is valid (@c doc->is_valid).
2728 * @param idx @c documents_array index.
2729 * @return The document, or @c NULL if @a idx is out of range.
2731 * @since 0.16
2733 GeanyDocument *document_index(gint idx)
2735 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2739 /* create a new file and copy file content and properties */
2740 GeanyDocument *document_clone(GeanyDocument *old_doc, const gchar *utf8_filename)
2742 gint len;
2743 gchar *text;
2744 GeanyDocument *doc;
2746 g_return_val_if_fail(old_doc != NULL, NULL);
2748 len = sci_get_length(old_doc->editor->sci) + 1;
2749 text = (gchar*) g_malloc(len);
2750 sci_get_text(old_doc->editor->sci, len, text);
2751 /* use old file type (or maybe NULL for auto detect would be better?) */
2752 doc = document_new_file(utf8_filename, old_doc->file_type, text);
2753 g_free(text);
2755 /* copy file properties */
2756 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2757 doc->readonly = old_doc->readonly;
2758 doc->has_bom = old_doc->has_bom;
2759 document_set_encoding(doc, old_doc->encoding);
2760 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2761 sci_set_readonly(doc->editor->sci, doc->readonly);
2763 ui_document_show_hide(doc);
2764 return doc;
2768 /* @note If successful, this should always be followed up with a call to
2769 * document_close_all().
2770 * @return TRUE if all files were saved or had their changes discarded. */
2771 gboolean document_account_for_unsaved(void)
2773 guint i, p, page_count;
2775 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2776 /* iterate over documents in tabs order */
2777 for (p = 0; p < page_count; p++)
2779 GeanyDocument *doc = document_get_from_page(p);
2781 if (DOC_VALID(doc) && doc->changed)
2783 if (! dialogs_show_unsaved_file(doc))
2784 return FALSE;
2787 /* all documents should now be accounted for, so ignore any changes */
2788 foreach_document (i)
2790 documents[i]->changed = FALSE;
2792 return TRUE;
2796 static void force_close_all(void)
2798 guint i, len = documents_array->len;
2800 /* check all documents have been accounted for */
2801 for (i = 0; i < len; i++)
2803 if (documents[i]->is_valid)
2805 g_return_if_fail(!documents[i]->changed);
2808 main_status.closing_all = TRUE;
2810 foreach_document(i)
2812 document_close(documents[i]);
2815 main_status.closing_all = FALSE;
2819 gboolean document_close_all(void)
2821 if (! document_account_for_unsaved())
2822 return FALSE;
2824 force_close_all();
2826 return TRUE;
2830 static void monitor_reload_file(GeanyDocument *doc)
2832 gchar *base_name = g_path_get_basename(doc->file_name);
2833 gint ret;
2835 ret = dialogs_show_prompt(NULL,
2836 GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
2837 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2838 _("_Reload"), GTK_RESPONSE_ACCEPT,
2839 _("Do you want to reload it?"),
2840 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2841 base_name);
2842 g_free(base_name);
2844 if (ret == GTK_RESPONSE_ACCEPT)
2845 document_reload_file(doc, doc->encoding);
2846 else if (ret == GTK_RESPONSE_CLOSE)
2847 document_close(doc);
2851 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2853 gboolean want_reload = FALSE;
2854 gboolean file_saved = FALSE;
2855 gint ret;
2857 ret = dialogs_show_prompt(NULL,
2858 _("Close _without saving"), GTK_RESPONSE_CLOSE,
2859 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2860 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
2861 _("Try to resave the file?"),
2862 _("File \"%s\" was not found on disk!"),
2863 doc->file_name);
2864 if (ret == GTK_RESPONSE_ACCEPT)
2866 file_saved = dialogs_show_save_as();
2867 want_reload = TRUE;
2869 else if (ret == GTK_RESPONSE_CLOSE)
2871 document_close(doc);
2873 if (ret != GTK_RESPONSE_CLOSE && ! file_saved)
2875 /* file is missing - set unsaved state */
2876 document_set_text_changed(doc, TRUE);
2877 /* don't prompt more than once */
2878 SETPTR(doc->real_path, NULL);
2881 return want_reload;
2885 /* Set force to force a disk check, otherwise it is ignored if there was a check
2886 * in the last file_prefs.disk_check_timeout seconds.
2887 * @return @c TRUE if the file has changed. */
2888 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
2890 gboolean ret = FALSE;
2891 gboolean use_gio_filemon;
2892 time_t cur_time = 0;
2893 struct stat st;
2894 gchar *locale_filename;
2895 FileDiskStatus old_status;
2897 g_return_val_if_fail(doc != NULL, FALSE);
2899 /* ignore remote files and documents that have never been saved to disk */
2900 if (notebook_switch_in_progress() || file_prefs.disk_check_timeout == 0
2901 || doc->real_path == NULL || doc->priv->is_remote)
2902 return FALSE;
2904 use_gio_filemon = (doc->priv->monitor != NULL);
2906 if (use_gio_filemon)
2908 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
2909 return FALSE;
2911 else
2913 cur_time = time(NULL);
2914 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
2915 return FALSE;
2917 doc->priv->last_check = cur_time;
2920 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2921 if (g_stat(locale_filename, &st) != 0)
2923 monitor_resave_missing_file(doc);
2924 /* doc may be closed now */
2925 ret = TRUE;
2927 else if (! use_gio_filemon && /* ignore check when using GIO */
2928 doc->priv->mtime > cur_time)
2930 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
2931 /* Note: on Windows st.st_mtime can be newer than cur_time */
2933 else if (doc->priv->mtime < st.st_mtime)
2935 doc->priv->mtime = st.st_mtime;
2936 monitor_reload_file(doc);
2937 /* doc may be closed now */
2938 ret = TRUE;
2940 g_free(locale_filename);
2942 if (DOC_VALID(doc))
2943 { /* doc can get invalid when a document was closed */
2944 old_status = doc->priv->file_disk_status;
2945 doc->priv->file_disk_status = FILE_OK;
2946 if (old_status != doc->priv->file_disk_status)
2947 ui_update_tab_status(doc);
2949 return ret;
2953 /** Compares documents by their display names.
2954 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2955 * @note 'Display name' means the base name of the document's filename.
2957 * @param a @c GeanyDocument**.
2958 * @param b @c GeanyDocument**.
2959 * @warning The arguments take the address of each document pointer.
2960 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2962 * @since 0.21
2964 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
2966 GeanyDocument *doc_a = *((GeanyDocument**) a);
2967 GeanyDocument *doc_b = *((GeanyDocument**) b);
2968 gchar *base_name_a, *base_name_b;
2969 gint result;
2971 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
2972 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
2974 result = strcmp(base_name_a, base_name_b);
2976 g_free(base_name_a);
2977 g_free(base_name_b);
2979 return result;
2983 /** Compares documents by their tab order.
2984 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2986 * @param a @c GeanyDocument**.
2987 * @param b @c GeanyDocument**.
2988 * @warning The arguments take the address of each document pointer.
2989 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2991 * @since 0.21 (GEANY_API_VERSION 209)
2993 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
2995 GeanyDocument *doc_a = *((GeanyDocument**) a);
2996 GeanyDocument *doc_b = *((GeanyDocument**) b);
2997 gint notebook_position_doc_a;
2998 gint notebook_position_doc_b;
3000 notebook_position_doc_a = document_get_notebook_page(doc_a);
3001 notebook_position_doc_b = document_get_notebook_page(doc_b);
3003 if (notebook_position_doc_a < notebook_position_doc_b)
3004 return -1;
3005 if (notebook_position_doc_a > notebook_position_doc_b)
3006 return 1;
3007 /* equality */
3008 return 0;
3012 /** Compares documents by their tab order, in reverse order.
3013 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3015 * @param a @c GeanyDocument**.
3016 * @param b @c GeanyDocument**.
3017 * @warning The arguments take the address of each document pointer.
3018 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3020 * @since 0.21 (GEANY_API_VERSION 209)
3022 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3024 GeanyDocument *doc_a = *((GeanyDocument**) a);
3025 GeanyDocument *doc_b = *((GeanyDocument**) b);
3026 gint notebook_position_doc_a;
3027 gint notebook_position_doc_b;
3029 notebook_position_doc_a = document_get_notebook_page(doc_a);
3030 notebook_position_doc_b = document_get_notebook_page(doc_b);
3032 if (notebook_position_doc_a < notebook_position_doc_b)
3033 return 1;
3034 if (notebook_position_doc_a > notebook_position_doc_b)
3035 return -1;
3036 /* equality */
3037 return 0;
3041 void document_grab_focus(GeanyDocument *doc)
3043 g_return_if_fail(doc != NULL);
3045 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));