Try to fix Gtk warning when using Tools->Reload Configuration.
[geany-mirror.git] / src / document.c
blobb3471ea5b37cd2be2c7d53147dfbf5e4eb463be7
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2009 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2009 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.
21 * $Id$
25 * Document related actions: new, save, open, etc.
26 * Also Scintilla search actions.
29 #include "geany.h"
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
33 #endif
34 #include <time.h>
36 #include <unistd.h>
37 #include <string.h>
38 #include <errno.h>
40 #ifdef HAVE_SYS_TYPES_H
41 # include <sys/types.h>
42 #endif
44 #include <ctype.h>
45 #include <stdlib.h>
47 /* gstdio.h also includes sys/stat.h */
48 #include <glib/gstdio.h>
50 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
51 /*#define USE_GIO_FILEMON 1*/
52 #if USE_GIO_FILEMON
53 # ifdef HAVE_GIO
54 # include <gio/gio.h>
55 # else
56 # undef USE_GIO_FILEMON
57 # endif
58 #endif
60 #include "document.h"
61 #include "documentprivate.h"
62 #include "filetypes.h"
63 #include "support.h"
64 #include "sciwrappers.h"
65 #include "editor.h"
66 #include "dialogs.h"
67 #include "msgwindow.h"
68 #include "templates.h"
69 #include "sidebar.h"
70 #include "ui_utils.h"
71 #include "utils.h"
72 #include "encodings.h"
73 #include "notebook.h"
74 #include "main.h"
75 #include "vte.h"
76 #include "build.h"
77 #include "symbols.h"
78 #include "highlighting.h"
79 #include "navqueue.h"
80 #include "win32.h"
81 #include "search.h"
84 GeanyFilePrefs file_prefs;
86 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
87 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
88 * to a document over time, but it might no longer represent a notebook tab. To check this,
89 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
90 * file by then.
92 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
93 * although usually you would just use the foreach_document() macro.
95 * Never assume that the order of document pointers is the same as the order of notebook tabs.
96 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
97 GPtrArray *documents_array;
100 /* an undo action, also used for redo actions */
101 typedef struct
103 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
104 guint type; /* to identify the action */
105 gpointer *data; /* the old value (before the change), in case of a redo action
106 * it contains the new value */
107 } undo_action;
110 static void document_undo_clear(GeanyDocument *doc);
111 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
112 static gboolean update_tags_from_buffer(GeanyDocument *doc);
115 /* ignore the case of filenames and paths under WIN32, causes errors if not */
116 #ifdef G_OS_WIN32
117 #define filenamecmp(a, b) utils_str_casecmp((a), (b))
118 #else
119 #define filenamecmp(a, b) strcmp((a), (b))
120 #endif
123 * Find and retrieve a document with the given filename from the document list.
125 * @param realname The filename to search, which should be identical to the
126 * string returned by @c tm_get_real_path().
128 * @return The matching document, or @c NULL.
129 * @note This is only really useful when passing a @c TMWorkObject::file_name.
130 * @see document_find_by_filename().
132 * @since 0.15
134 GeanyDocument* document_find_by_real_path(const gchar *realname)
136 guint i;
138 if (! realname)
139 return NULL; /* file doesn't exist on disk */
141 for (i = 0; i < documents_array->len; i++)
143 GeanyDocument *doc = documents[i];
145 if (! doc->is_valid || G_UNLIKELY(! doc->real_path))
146 continue;
148 if (filenamecmp(realname, doc->real_path) == 0)
150 return doc;
153 return NULL;
157 /* dereference symlinks, /../ junk in path and return locale encoding */
158 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
160 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
161 gchar *realname = tm_get_real_path(locale_name);
163 g_free(locale_name);
164 return realname;
169 * Find and retrieve a document with the given filename from the document list.
170 * This matches either an exact GeanyDocument::file_name string, or variant
171 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
172 * match @c "/name").
174 * @param utf8_filename The filename to search (in UTF-8 encoding).
176 * @return The matching document, or @c NULL.
177 * @see document_find_by_real_path().
179 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
181 guint i;
182 GeanyDocument *doc;
183 gchar *realname;
185 g_return_val_if_fail(utf8_filename != NULL, NULL);
187 /* First search GeanyDocument::file_name, so we can find documents with a
188 * filename set but not saved on disk, like vcdiff produces */
189 for (i = 0; i < documents_array->len; i++)
191 doc = documents[i];
193 if (! doc->is_valid || G_UNLIKELY(doc->file_name == NULL))
194 continue;
196 if (filenamecmp(utf8_filename, doc->file_name) == 0)
198 return doc;
201 /* Now try matching based on the realpath(), which is unique per file on disk */
202 realname = get_real_path_from_utf8(utf8_filename);
203 doc = document_find_by_real_path(realname);
204 g_free(realname);
205 return doc;
209 /* returns the document which has sci, or NULL. */
210 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
212 guint i;
214 g_return_val_if_fail(sci != NULL, NULL);
216 for (i = 0; i < documents_array->len; i++)
218 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
219 return documents[i];
221 return NULL;
225 /** Get the notebook page index for a document.
226 * @param doc The document.
227 * @return The index.
228 * @since 0.19 */
229 gint document_get_notebook_page(GeanyDocument *doc)
231 g_return_val_if_fail(doc != NULL, -1);
233 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
234 GTK_WIDGET(doc->editor->sci));
239 * Find and retrieve the document for the given notebook page @a page_num.
241 * @param page_num The notebook page number to search.
243 * @return The corresponding document for the given notebook page, or @c NULL.
245 GeanyDocument *document_get_from_page(guint page_num)
247 ScintillaObject *sci;
249 if (page_num >= documents_array->len)
250 return NULL;
252 sci = (ScintillaObject*)gtk_notebook_get_nth_page(
253 GTK_NOTEBOOK(main_widgets.notebook), page_num);
255 return document_find_by_sci(sci);
260 * Find and retrieve the current document.
262 * @return A pointer to the current document or @c NULL if there are no opened documents.
264 GeanyDocument *document_get_current(void)
266 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
268 if (cur_page == -1)
269 return NULL;
270 else
272 ScintillaObject *sci = (ScintillaObject*)
273 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
275 return document_find_by_sci(sci);
280 void document_init_doclist()
282 documents_array = g_ptr_array_new();
286 void document_finalize()
288 g_ptr_array_free(documents_array, TRUE);
293 * Returns the last part of the filename of the given GeanyDocument. The result is also
294 * truncated to a maximum of @a length characters in case the filename is very long.
296 * @param doc The document to use.
297 * @param length The length of the resulting string or -1 to use a default value.
299 * @return The ellipsized last part of the filename of @a doc, should be freed when no
300 * longer needed.
302 * @since 0.17
304 /* TODO make more use of this */
305 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
307 gchar *base_name, *short_name;
309 g_return_val_if_fail(doc != NULL, NULL);
311 if (length < 0)
312 length = 30;
314 base_name = g_path_get_basename(DOC_FILENAME(doc));
315 short_name = utils_str_middle_truncate(base_name, length);
317 g_free(base_name);
319 return short_name;
323 void document_update_tab_label(GeanyDocument *doc)
325 gchar *short_name;
326 GtkWidget *parent;
328 g_return_if_fail(doc != NULL);
330 short_name = document_get_basename_for_display(doc, -1);
332 /* we need to use the event box for the tooltip, labels don't get the necessary events */
333 parent = gtk_widget_get_parent(doc->priv->tab_label);
334 parent = gtk_widget_get_parent(parent);
336 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
338 ui_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
340 g_free(short_name);
345 * Update the tab labels, the status bar, the window title and some save-sensitive buttons
346 * according to the document's save state.
347 * This is called by Geany mostly when opening or saving files.
349 * @param doc The document to use.
350 * @param changed Whether the document state should indicate changes have been made.
352 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
354 g_return_if_fail(doc != NULL);
356 doc->changed = changed;
358 if (! main_status.quitting)
360 ui_update_tab_status(doc);
361 ui_save_buttons_toggle(changed);
362 ui_set_window_title(doc);
363 ui_update_statusbar(doc, -1);
368 /* Sets is_valid to FALSE and initializes some members to NULL, to mark it uninitialized.
369 * The flag is_valid is set to TRUE in document_create(). */
370 static void init_doc_struct(GeanyDocument *new_doc)
372 GeanyDocumentPrivate *priv;
374 memset(new_doc, 0, sizeof(GeanyDocument));
376 new_doc->is_valid = FALSE;
377 new_doc->has_tags = FALSE;
378 new_doc->readonly = FALSE;
379 new_doc->file_name = NULL;
380 new_doc->file_type = NULL;
381 new_doc->tm_file = NULL;
382 new_doc->encoding = NULL;
383 new_doc->has_bom = FALSE;
384 new_doc->editor = NULL;
385 new_doc->changed = FALSE;
386 new_doc->real_path = NULL;
388 new_doc->priv = g_new0(GeanyDocumentPrivate, 1);
389 priv = new_doc->priv;
390 priv->tag_store = NULL;
391 priv->tag_tree = NULL;
392 priv->saved_encoding.encoding = NULL;
393 priv->saved_encoding.has_bom = FALSE;
394 priv->undo_actions = NULL;
395 priv->redo_actions = NULL;
396 priv->line_count = 0;
397 #if ! defined(USE_GIO_FILEMON)
398 priv->last_check = time(NULL);
399 #endif
403 /* returns the next free place in the document list,
404 * or -1 if the documents_array is full */
405 static gint document_get_new_idx(void)
407 guint i;
409 for (i = 0; i < documents_array->len; i++)
411 if (documents[i]->editor == NULL)
413 return (gint) i;
416 return -1;
420 static void queue_colourise(GeanyDocument *doc)
422 /* Colourise the editor before it is next drawn */
423 doc->priv->colourise_needed = TRUE;
425 /* If the editor doesn't need drawing (e.g. after saving the current
426 * document), we need to force a redraw, so the expose event is triggered.
427 * This ensures we don't start colourising before all documents are opened/saved,
428 * only once the editor is drawn. */
429 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
433 #if USE_GIO_FILEMON
434 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
435 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
436 GeanyDocument *doc)
438 g_return_if_fail(doc != NULL);
440 if (file_prefs.disk_check_timeout == 0)
441 return;
443 geany_debug("%s: event: %d previous file status: %d",
444 G_STRFUNC, event, doc->priv->file_disk_status);
445 switch (event)
447 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
449 if (doc->priv->file_disk_status == FILE_IGNORE)
450 doc->priv->file_disk_status = FILE_OK;
451 else
452 doc->priv->file_disk_status = FILE_CHANGED;
453 g_message("%s: FILE_CHANGED", G_STRFUNC);
454 break;
456 case G_FILE_MONITOR_EVENT_DELETED:
458 doc->priv->file_disk_status = FILE_CHANGED;
459 g_message("%s: FILE_MISSING", G_STRFUNC);
460 break;
462 default:
463 break;
465 if (doc->priv->file_disk_status != FILE_OK)
467 ui_update_tab_status(doc);
470 #endif
473 void document_stop_file_monitoring(GeanyDocument *doc)
475 g_return_if_fail(doc != NULL);
477 if (doc->priv->monitor != NULL)
479 g_object_unref(doc->priv->monitor);
480 doc->priv->monitor = NULL;
485 static void monitor_file_setup(GeanyDocument *doc)
487 g_return_if_fail(doc != NULL);
488 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
489 * doesn't work at all for remote files and legacy polling is too slow. */
490 if (! doc->priv->is_remote)
492 #if USE_GIO_FILEMON
493 gchar *locale_filename;
495 /* stop any previous monitoring */
496 document_stop_file_monitoring(doc);
498 locale_filename = utils_get_locale_from_utf8(doc->file_name);
499 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
501 /* get a file monitor and connect to the 'changed' signal */
502 GFile *file = g_file_new_for_path(locale_filename);
503 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
504 g_signal_connect(doc->priv->monitor, "changed",
505 G_CALLBACK(monitor_file_changed_cb), doc);
507 /* we set the rate limit according to the GUI pref but it's most probably not used */
508 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
510 g_object_unref(file);
512 g_free(locale_filename);
513 #endif
515 doc->priv->file_disk_status = FILE_OK;
519 void document_try_focus(GeanyDocument *doc)
521 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
522 if (DOC_VALID(doc))
524 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
525 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
527 if (focusw == doc->priv->tag_tree)
528 gtk_widget_grab_focus(sci);
533 static gboolean on_idle_focus(gpointer doc)
535 document_try_focus(doc);
536 return FALSE;
540 /* Creates a new document and editor, adding a tab in the notebook.
541 * @return The created document */
542 static GeanyDocument *document_create(const gchar *utf8_filename)
544 GeanyDocument *doc;
545 gint new_idx;
546 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
548 if (cur_pages == 1)
550 GeanyDocument *cur = document_get_current();
551 /* remove the empty document and open a new one */
552 if (cur != NULL && cur->file_name == NULL && ! cur->changed)
553 document_remove_page(0);
556 new_idx = document_get_new_idx();
557 if (new_idx == -1) /* expand the array, no free places */
559 GeanyDocument *new_doc = g_new0(GeanyDocument, 1);
561 new_idx = documents_array->len;
562 g_ptr_array_add(documents_array, new_doc);
564 doc = documents[new_idx];
565 init_doc_struct(doc); /* initialize default document settings */
566 doc->index = new_idx;
568 doc->file_name = g_strdup(utf8_filename);
570 doc->editor = editor_create(doc);
572 sidebar_openfiles_add(doc); /* sets doc->iter */
574 notebook_new_tab(doc);
576 /* select document in sidebar */
578 GtkTreeSelection *sel;
580 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
581 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
584 ui_document_buttons_update();
586 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
587 return doc;
592 * Close the given document.
594 * @param doc The document to remove.
596 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
598 * @since 0.15
600 gboolean document_close(GeanyDocument *doc)
602 g_return_val_if_fail(doc, FALSE);
604 return document_remove_page(document_get_notebook_page(doc));
609 * Remove the given notebook tab at @a page_num and clear all related information
610 * in the document list.
612 * @param page_num The notebook page number to remove.
614 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
616 gboolean document_remove_page(guint page_num)
618 GeanyDocument *doc = document_get_from_page(page_num);
620 if (G_UNLIKELY(doc == NULL))
622 g_warning("%s: page_num: %d", G_STRFUNC, page_num);
623 return FALSE;
626 if (doc->changed && ! dialogs_show_unsaved_file(doc))
628 return FALSE;
631 /* tell any plugins that the document is about to be closed */
632 g_signal_emit_by_name(geany_object, "document-close", doc);
634 /* Checking real_path makes it likely the file exists on disk */
635 if (! main_status.closing_all && doc->real_path != NULL)
636 ui_add_recent_file(doc->file_name);
638 doc->is_valid = FALSE;
640 notebook_remove_page(page_num);
641 sidebar_remove_document(doc);
642 navqueue_remove_file(doc->file_name);
643 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
644 g_free(doc->encoding);
645 g_free(doc->priv->saved_encoding.encoding);
646 g_free(doc->file_name);
647 g_free(doc->real_path);
648 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
650 editor_destroy(doc->editor);
651 doc->editor = NULL;
653 document_stop_file_monitoring(doc);
655 doc->file_name = NULL;
656 doc->real_path = NULL;
657 doc->file_type = NULL;
658 doc->encoding = NULL;
659 doc->has_bom = FALSE;
660 doc->tm_file = NULL;
661 document_undo_clear(doc);
662 g_free(doc->priv);
664 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
666 sidebar_update_tag_list(NULL, FALSE);
667 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
668 ui_set_window_title(NULL);
669 ui_save_buttons_toggle(FALSE);
670 ui_document_buttons_update();
671 build_menu_update(NULL);
673 return TRUE;
677 /* used to keep a record of the unchanged document state encoding */
678 static void store_saved_encoding(GeanyDocument *doc)
680 g_free(doc->priv->saved_encoding.encoding);
681 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
682 doc->priv->saved_encoding.has_bom = doc->has_bom;
686 /* Opens a new empty document only if there are no other documents open */
687 GeanyDocument *document_new_file_if_non_open(void)
689 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
690 return document_new_file(NULL, NULL, NULL);
692 return NULL;
697 * Creates a new document.
698 * After all, the "document-new" signal is emitted for plugins.
700 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
701 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
702 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
704 * @return The new document.
706 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft,
707 const gchar *text)
709 GeanyDocument *doc;
711 if (utf8_filename && g_path_is_absolute(utf8_filename))
713 gchar *tmp;
714 tmp = utils_strdupa(utf8_filename); /* work around const */
715 utils_tidy_path(tmp);
716 utf8_filename = tmp;
718 doc = document_create(utf8_filename);
720 g_assert(doc != NULL);
722 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
723 if (text)
724 sci_set_text(doc->editor->sci, text);
725 else
726 sci_clear_all(doc->editor->sci);
728 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
729 /* convert the eol chars in the template text in case they are different from
730 * from file_prefs.default_eol */
731 if (text != NULL)
732 sci_convert_eols(doc->editor->sci, file_prefs.default_eol_character);
734 sci_set_undo_collection(doc->editor->sci, TRUE);
735 sci_empty_undo_buffer(doc->editor->sci);
737 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
738 /* store the opened encoding for undo/redo */
739 store_saved_encoding(doc);
741 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
742 ft = filetypes_detect_from_document(doc);
744 document_set_filetype(doc, ft); /* also clears taglist */
746 ui_set_window_title(doc);
747 build_menu_update(doc);
748 document_update_tag_list(doc, FALSE);
749 document_set_text_changed(doc, FALSE);
750 ui_document_show_hide(doc); /* update the document menu */
752 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
753 /* bring it in front, jump to the start and grab the focus */
754 editor_goto_pos(doc->editor, 0, FALSE);
755 document_try_focus(doc);
757 #if USE_GIO_FILEMON
758 monitor_file_setup(doc);
759 #else
760 doc->priv->mtime = time(NULL);
761 #endif
763 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
764 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
766 g_signal_emit_by_name(geany_object, "document-new", doc);
768 msgwin_status_add(_("New file \"%s\" opened."),
769 DOC_FILENAME(doc));
771 return doc;
776 * Open a document specified by @a locale_filename.
777 * After all, the "document-open" signal is emitted for plugins.
779 * @param locale_filename The filename of the document to load, in locale encoding.
780 * @param readonly Whether to open the document in read-only mode.
781 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
782 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
784 * @return The document opened or @c NULL.
786 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
787 GeanyFiletype *ft, const gchar *forced_enc)
789 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
793 typedef struct
795 gchar *data; /* null-terminated file data */
796 gsize size; /* actual file size on disk */
797 gsize len; /* string length of data */
798 gchar *enc;
799 gboolean bom;
800 time_t mtime; /* modification time, read by stat::st_mtime */
801 gboolean readonly;
802 } FileData;
805 /* reload file with specified encoding */
806 static gboolean
807 handle_forced_encoding(FileData *filedata, const gchar *forced_enc)
809 GeanyEncodingIndex enc_idx;
811 if (utils_str_equal(forced_enc, "UTF-8"))
813 if (! g_utf8_validate(filedata->data, filedata->len, NULL))
815 return FALSE;
818 else
820 gchar *converted_text = encodings_convert_to_utf8_from_charset(
821 filedata->data, filedata->size, forced_enc, FALSE);
822 if (converted_text == NULL)
824 return FALSE;
826 else
828 g_free(filedata->data);
829 filedata->data = converted_text;
830 filedata->len = strlen(converted_text);
833 enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
834 filedata->bom = (enc_idx == GEANY_ENCODING_UTF_8);
835 filedata->enc = g_strdup(forced_enc);
836 return TRUE;
840 /* detect encoding and convert to UTF-8 if necessary */
841 static gboolean
842 handle_encoding(FileData *filedata, GeanyEncodingIndex enc_idx)
844 g_return_val_if_fail(filedata->enc == NULL, FALSE);
845 g_return_val_if_fail(filedata->bom == FALSE, FALSE);
847 if (filedata->size == 0)
849 /* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
850 * e.g. UTF32 file with a BOM(so size is 4, len is 0) */
851 filedata->enc = g_strdup("UTF-8");
853 else
855 /* first check for a BOM */
856 if (enc_idx != GEANY_ENCODING_NONE)
858 filedata->enc = g_strdup(encodings[enc_idx].charset);
859 filedata->bom = TRUE;
861 if (enc_idx != GEANY_ENCODING_UTF_8) /* the BOM indicated something else than UTF-8 */
863 gchar *converted_text = encodings_convert_to_utf8_from_charset(
864 filedata->data, filedata->size, filedata->enc, FALSE);
865 if (converted_text != NULL)
867 g_free(filedata->data);
868 filedata->data = converted_text;
869 filedata->len = strlen(converted_text);
871 else
873 /* there was a problem converting data from BOM encoding type */
874 g_free(filedata->enc);
875 filedata->enc = NULL;
876 filedata->bom = FALSE;
881 if (filedata->enc == NULL) /* either there was no BOM or the BOM encoding failed */
883 /* try UTF-8 first */
884 if ((filedata->size == filedata->len) &&
885 g_utf8_validate(filedata->data, filedata->len, NULL))
887 filedata->enc = g_strdup("UTF-8");
889 else
891 /* detect the encoding */
892 gchar *converted_text = encodings_convert_to_utf8(filedata->data,
893 filedata->size, &filedata->enc);
895 if (converted_text == NULL)
897 return FALSE;
899 g_free(filedata->data);
900 filedata->data = converted_text;
901 filedata->len = strlen(converted_text);
905 return TRUE;
909 static void
910 handle_bom(FileData *filedata)
912 guint bom_len;
914 encodings_scan_unicode_bom(filedata->data, filedata->size, &bom_len);
915 g_return_if_fail(bom_len != 0);
917 /* use filedata->len here because the contents are already converted into UTF-8 */
918 filedata->len -= bom_len;
919 /* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
920 g_memmove(filedata->data, filedata->data + bom_len, filedata->len + 1);
921 filedata->data = g_realloc(filedata->data, filedata->len + 1);
925 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
926 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
927 FileData *filedata, const gchar *forced_enc)
929 GError *err = NULL;
930 struct stat st;
931 GeanyEncodingIndex tmp_enc_idx;
933 filedata->data = NULL;
934 filedata->len = 0;
935 filedata->enc = NULL;
936 filedata->bom = FALSE;
937 filedata->readonly = FALSE;
939 if (g_stat(locale_filename, &st) != 0)
941 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
942 display_filename, g_strerror(errno));
943 return FALSE;
946 filedata->mtime = st.st_mtime;
948 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
950 ui_set_statusbar(TRUE, "%s", err->message);
951 g_error_free(err);
952 return FALSE;
955 /* use strlen to check for null chars */
956 filedata->size = (gsize) st.st_size;
957 filedata->len = strlen(filedata->data);
959 /* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
960 * if we have a BOM */
961 tmp_enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
963 /* check whether the size of the loaded data is equal to the size of the file in the
964 * filesystem file size may be 0 to allow opening files in /proc/ which have typically a
965 * file size of 0 bytes */
966 if (filedata->len != filedata->size && filedata->size != 0 && (
967 tmp_enc_idx == GEANY_ENCODING_UTF_8 || /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
968 tmp_enc_idx == GEANY_ENCODING_UTF_7)) /* filter UTF-7/8 where no NULL bytes are allowed */
970 const gchar *warn_msg = _(
971 "The file \"%s\" could not be opened properly and has been truncated. " \
972 "This can occur if the file contains a NULL byte. " \
973 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
975 if (main_status.main_window_realized)
976 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
978 ui_set_statusbar(TRUE, warn_msg, display_filename);
980 /* set the file to read-only mode because saving it is probably dangerous */
981 filedata->readonly = TRUE;
984 /* Determine character encoding and convert to UTF-8 */
985 if (forced_enc != NULL)
987 /* the encoding should be ignored(requested by user), so open the file "as it is" */
988 if (utils_str_equal(forced_enc, encodings[GEANY_ENCODING_NONE].charset))
990 filedata->bom = FALSE;
991 filedata->enc = g_strdup(encodings[GEANY_ENCODING_NONE].charset);
993 else if (! handle_forced_encoding(filedata, forced_enc))
995 /* For translators: the second wildcard is an encoding name, e.g.
996 * The file \"test.txt\" is not valid UTF-8. */
997 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
998 display_filename, forced_enc);
999 utils_beep();
1000 g_free(filedata->data);
1001 return FALSE;
1004 else if (! handle_encoding(filedata, tmp_enc_idx))
1006 ui_set_statusbar(TRUE,
1007 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1008 display_filename);
1009 utils_beep();
1010 g_free(filedata->data);
1011 return FALSE;
1014 if (filedata->bom)
1015 handle_bom(filedata);
1016 return TRUE;
1020 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1021 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1022 * if cl_options.goto_column is set.
1024 * returns the new position which may have changed */
1025 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1027 if (cl_options.goto_line >= 0)
1028 { /* goto line which was specified on command line and then undefine the line */
1029 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1030 editor->scroll_percent = 0.5F;
1031 cl_options.goto_line = -1;
1033 else if (pos > 0)
1035 sci_set_current_position(editor->sci, pos, FALSE);
1036 editor->scroll_percent = 0.5F;
1039 if (cl_options.goto_column >= 0)
1040 { /* goto column which was specified on command line and then undefine the column */
1042 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1043 sci_set_current_position(editor->sci, new_pos, FALSE);
1044 editor->scroll_percent = 0.5F;
1045 cl_options.goto_column = -1;
1046 return new_pos;
1048 return sci_get_current_position(editor->sci);
1052 /* Count lines that start with some hard tabs then a soft tab. */
1053 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1055 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1056 ScintillaObject *sci = editor->sci;
1057 gsize count = 0;
1058 struct Sci_TextToFind ttf;
1059 gchar *soft_tab = g_strnfill(iprefs->width, ' ');
1060 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1062 g_free(soft_tab);
1064 ttf.chrg.cpMin = 0;
1065 ttf.chrg.cpMax = sci_get_length(sci);
1066 ttf.lpstrText = regex;
1067 while (1)
1069 gint pos;
1071 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1072 if (pos == -1)
1073 break; /* no more matches */
1074 count++;
1075 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1077 g_free(regex);
1078 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1079 return count > sci_get_line_count(sci) * 0.02;
1083 /* Detect the indent type based on counting the leading indent characters for each line. */
1084 static GeanyIndentType detect_indent_type(GeanyEditor *editor)
1086 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1087 ScintillaObject *sci = editor->sci;
1088 guint line, line_count;
1089 gsize tabs = 0, spaces = 0;
1091 if (detect_tabs_and_spaces(editor))
1092 return GEANY_INDENT_TYPE_BOTH;
1094 line_count = sci_get_line_count(sci);
1095 for (line = 0; line < line_count; line++)
1097 gint pos = sci_get_position_from_line(sci, line);
1098 gchar c;
1100 /* most code will have indent total <= 24, otherwise it's more likely to be
1101 * alignment than indentation */
1102 if (sci_get_line_indentation(sci, line) > 24)
1103 continue;
1105 c = sci_get_char_at(sci, pos);
1106 if (c == '\t')
1107 tabs++;
1108 else
1109 if (c == ' ')
1111 /* check for at least 2 spaces */
1112 if (sci_get_char_at(sci, pos + 1) == ' ')
1113 spaces++;
1116 if (spaces == 0 && tabs == 0)
1117 return iprefs->type;
1119 /* the factors may need to be tweaked */
1120 if (spaces > tabs * 4)
1121 return GEANY_INDENT_TYPE_SPACES;
1122 else if (tabs > spaces * 4)
1123 return GEANY_INDENT_TYPE_TABS;
1124 else
1125 return GEANY_INDENT_TYPE_BOTH;
1129 static void set_indentation(GeanyEditor *editor)
1131 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1133 switch (FILETYPE_ID(editor->document->file_type))
1135 case GEANY_FILETYPES_MAKE:
1136 /* force using tabs for indentation for Makefiles */
1137 editor_set_indent_type(editor, GEANY_INDENT_TYPE_TABS);
1138 return;
1139 case GEANY_FILETYPES_F77:
1140 /* force using spaces for indentation for Fortran 77 */
1141 editor_set_indent_type(editor, GEANY_INDENT_TYPE_SPACES);
1142 return;
1144 if (iprefs->detect_type)
1146 GeanyIndentType type = detect_indent_type(editor);
1148 if (type != iprefs->type)
1150 const gchar *name = NULL;
1152 switch (type)
1154 case GEANY_INDENT_TYPE_SPACES:
1155 name = _("Spaces");
1156 break;
1157 case GEANY_INDENT_TYPE_TABS:
1158 name = _("Tabs");
1159 break;
1160 case GEANY_INDENT_TYPE_BOTH:
1161 name = _("Tabs and Spaces");
1162 break;
1164 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1165 * and Spaces), the second one is the filename */
1166 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1167 DOC_FILENAME(editor->document));
1169 editor_set_indent_type(editor, type);
1174 #if 0
1175 static gboolean auto_update_tag_list(gpointer data)
1177 GeanyDocument *doc = data;
1179 if (! doc || ! doc->is_valid || doc->tm_file == NULL)
1180 return FALSE;
1182 if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != GTK_WIDGET(doc->editor->sci))
1183 return TRUE;
1185 if (update_tags_from_buffer(doc))
1186 sidebar_update_tag_list(doc, TRUE);
1188 return TRUE;
1190 #endif
1193 /* To open a new file, set doc to NULL; filename should be locale encoded.
1194 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1195 * pos is the cursor position, which can be overridden by --line and --column.
1196 * forced_enc can be NULL to detect the file encoding.
1197 * Returns: doc of the opened file or NULL if an error occurred. */
1198 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1199 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1201 gint editor_mode;
1202 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1203 gchar *utf8_filename = NULL;
1204 gchar *display_filename = NULL;
1205 gchar *locale_filename = NULL;
1206 GeanyFiletype *use_ft;
1207 FileData filedata;
1209 if (reload)
1211 utf8_filename = g_strdup(doc->file_name);
1212 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1214 else
1216 /* filename must not be NULL when opening a file */
1217 if (filename == NULL)
1219 ui_set_statusbar(FALSE, _("Invalid filename"));
1220 return NULL;
1223 #ifdef G_OS_WIN32
1224 /* if filename is a shortcut, try to resolve it */
1225 locale_filename = win32_get_shortcut_target(filename);
1226 #else
1227 locale_filename = g_strdup(filename);
1228 #endif
1229 /* remove relative junk */
1230 utils_tidy_path(locale_filename);
1232 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1233 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1235 /* if file is already open, switch to it and go */
1236 doc = document_find_by_filename(utf8_filename);
1237 if (doc != NULL)
1239 ui_add_recent_file(utf8_filename); /* either add or reorder recent item */
1240 /* show the doc before reload dialog */
1241 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1242 gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
1243 (GtkWidget*) doc->editor->sci));
1244 document_check_disk_status(doc, TRUE); /* force a file changed check */
1247 if (reload || doc == NULL)
1248 { /* doc possibly changed */
1249 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1251 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1253 g_free(display_filename);
1254 g_free(utf8_filename);
1255 g_free(locale_filename);
1256 return NULL;
1259 if (! reload)
1261 doc = document_create(utf8_filename);
1262 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1264 /* file exists on disk, set real_path */
1265 setptr(doc->real_path, tm_get_real_path(locale_filename));
1267 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1268 monitor_file_setup(doc);
1271 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1272 sci_empty_undo_buffer(doc->editor->sci);
1274 /* add the text to the ScintillaObject */
1275 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1276 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1277 queue_colourise(doc); /* Ensure the document gets colourised. */
1279 /* detect & set line endings */
1280 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1281 sci_set_eol_mode(doc->editor->sci, editor_mode);
1282 g_free(filedata.data);
1284 sci_set_undo_collection(doc->editor->sci, TRUE);
1286 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1287 g_free(doc->encoding); /* if reloading, free old encoding */
1288 doc->encoding = filedata.enc;
1289 doc->has_bom = filedata.bom;
1290 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1292 doc->readonly = readonly || filedata.readonly;
1293 sci_set_readonly(doc->editor->sci, doc->readonly);
1295 /* update line number margin width */
1296 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1297 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1299 if (! reload)
1302 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1303 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1304 doc->editor);
1306 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1308 else
1309 { /* reloading */
1310 document_undo_clear(doc);
1312 use_ft = ft;
1314 /* update taglist, typedef keywords and build menu if necessary */
1315 document_set_filetype(doc, use_ft);
1317 /* set indentation settings after setting the filetype */
1318 if (reload)
1319 editor_set_indent_type(doc->editor, doc->editor->indent_type); /* resetup sci */
1320 else
1321 set_indentation(doc->editor);
1323 document_set_text_changed(doc, FALSE); /* also updates tab state */
1324 ui_document_show_hide(doc); /* update the document menu */
1326 /* finally add current file to recent files menu, but not the files from the last session */
1327 if (! main_status.opening_session_files)
1328 ui_add_recent_file(utf8_filename);
1330 if (! reload)
1331 g_signal_emit_by_name(geany_object, "document-open", doc);
1333 if (reload)
1334 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1335 else
1336 /* For translators: this is the status window message for opening a file. %d is the number
1337 * of the newly opened file, %s indicates whether the file is opened read-only
1338 * (it is replaced with the string ", read-only"). */
1339 msgwin_status_add(_("File %s opened(%d%s)."),
1340 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1341 (readonly) ? _(", read-only") : "");
1344 g_free(display_filename);
1345 g_free(utf8_filename);
1346 g_free(locale_filename);
1348 /* TODO This could be used to automatically update the symbol list,
1349 * based on a configurable interval */
1350 /*g_timeout_add(10000, auto_update_tag_list, doc);*/
1352 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1353 pos = set_cursor_position(doc->editor, pos);
1354 /* now bring the file in front */
1355 editor_goto_pos(doc->editor, pos, FALSE);
1357 /* finally, let the editor widget grab the focus so you can start coding
1358 * right away */
1359 g_idle_add(on_idle_focus, doc);
1360 return doc;
1364 /* Takes a new line separated list of filename URIs and opens each file.
1365 * length is the length of the string or -1 if it should be detected */
1366 void document_open_file_list(const gchar *data, gssize length)
1368 gint i;
1369 gchar *filename;
1370 gchar **list;
1372 g_return_if_fail(data != NULL);
1374 if (length < 0)
1375 length = strlen(data);
1377 switch (utils_get_line_endings(data, length))
1379 case SC_EOL_CR: list = g_strsplit(data, "\r", 0); break;
1380 case SC_EOL_CRLF: list = g_strsplit(data, "\r\n", 0); break;
1381 case SC_EOL_LF: list = g_strsplit(data, "\n", 0); break;
1382 default: list = g_strsplit(data, "\n", 0);
1385 for (i = 0; ; i++)
1387 if (list[i] == NULL)
1388 break;
1389 filename = g_filename_from_uri(list[i], NULL, NULL);
1390 if (G_UNLIKELY(filename == NULL))
1391 continue;
1392 document_open_file(filename, FALSE, NULL, NULL);
1393 g_free(filename);
1396 g_strfreev(list);
1401 * Opens each file in the list @a filenames.
1402 * Internally, document_open_file() is called for every list item.
1404 * @param filenames A list of filenames to load, in locale encoding.
1405 * @param readonly Whether to open the document in read-only mode.
1406 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1407 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1409 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1410 const gchar *forced_enc)
1412 const GSList *item;
1414 for (item = filenames; item != NULL; item = g_slist_next(item))
1416 document_open_file(item->data, readonly, ft, forced_enc);
1422 * Reloads the document with the specified file encoding
1423 * @a forced_enc or @c NULL to auto-detect the file encoding.
1425 * @param doc The document to reload.
1426 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1428 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1430 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1432 gint pos = 0;
1433 GeanyDocument *new_doc;
1435 g_return_val_if_fail(doc != NULL, FALSE);
1437 /* try to set the cursor to the position before reloading */
1438 pos = sci_get_current_position(doc->editor->sci);
1439 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1441 return (new_doc != NULL);
1445 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1447 #if ! USE_GIO_FILEMON
1448 struct stat st;
1450 g_return_val_if_fail(doc != NULL, FALSE);
1452 /* stat the file to get the timestamp, otherwise on Windows the actual
1453 * timestamp can be ahead of time(NULL) */
1454 if (g_stat(locale_filename, &st) != 0)
1456 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1457 g_strerror(errno));
1458 return FALSE;
1461 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1462 #endif
1463 return TRUE;
1467 /* Sets line and column to the given position byte_pos in the document.
1468 * byte_pos is the position counted in bytes, not characters */
1469 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1471 gint i;
1472 gint line_start;
1474 /* for some reason we can use byte count instead of character count here */
1475 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1476 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1477 /* get the column in the line */
1478 *column = byte_pos - line_start;
1480 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1481 * skip one byte(i++) and decrease the column number which is based on byte count */
1482 for (i = line_start; i < (line_start + *column); i++)
1484 if (sci_get_char_at(doc->editor->sci, i) < 0)
1486 (*column)--;
1487 i++;
1493 static void replace_header_filename(GeanyDocument *doc)
1495 gchar *filebase;
1496 gchar *filename;
1497 struct Sci_TextToFind ttf;
1499 g_return_if_fail(doc != NULL);
1500 g_return_if_fail(doc->file_type != NULL);
1502 if (doc->file_type->extension)
1503 filebase = g_strconcat(GEANY_STRING_UNTITLED, ".", doc->file_type->extension, NULL);
1504 else
1505 filebase = g_strdup(GEANY_STRING_UNTITLED);
1507 filename = g_path_get_basename(doc->file_name);
1509 /* only search the first 3 lines */
1510 ttf.chrg.cpMin = 0;
1511 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 3);
1512 ttf.lpstrText = (gchar*)filebase;
1514 if (sci_find_text(doc->editor->sci, SCFIND_MATCHCASE, &ttf) != -1)
1516 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1517 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1518 sci_replace_target(doc->editor->sci, filename, FALSE);
1521 g_free(filebase);
1522 g_free(filename);
1527 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1528 * you still have to call @ref document_save_file_as() to change the @a doc object.
1529 * It also stops monitoring for file changes to prevent receiving too many file change events
1530 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1532 * @param doc The current document which should be renamed.
1533 * @param new_filename The new filename in UTF-8 encoding.
1535 * @since 0.16
1537 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1539 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1540 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1541 gint result;
1543 /* stop file monitoring to avoid getting events for deleting/creating files,
1544 * it's re-setup in document_save_file_as() */
1545 document_stop_file_monitoring(doc);
1547 result = g_rename(old_locale_filename, new_locale_filename);
1548 if (result != 0)
1550 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1551 _("Error renaming file."), g_strerror(errno));
1553 g_free(old_locale_filename);
1554 g_free(new_locale_filename);
1559 * Saves the document, detecting the filetype.
1561 * @param doc The document for the file to save.
1562 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1563 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1565 * @see document_save_file().
1567 * @since 0.16
1569 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1571 gboolean ret;
1573 g_return_val_if_fail(doc != NULL, FALSE);
1575 if (utf8_fname != NULL)
1576 setptr(doc->file_name, g_strdup(utf8_fname));
1578 /* reset real path, it's retrieved again in document_save() */
1579 setptr(doc->real_path, NULL);
1581 /* detect filetype */
1582 if (FILETYPE_ID(doc->file_type) == GEANY_FILETYPES_NONE)
1584 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1586 document_set_filetype(doc, ft);
1587 if (document_get_current() == doc)
1589 ignore_callback = TRUE;
1590 filetypes_select_radio_item(doc->file_type);
1591 ignore_callback = FALSE;
1594 replace_header_filename(doc);
1596 ret = document_save_file(doc, TRUE);
1598 /* file monitoring support, add file monitoring after the file has been saved
1599 * to ignore any earlier events */
1600 monitor_file_setup(doc);
1601 doc->priv->file_disk_status = FILE_IGNORE;
1603 if (ret)
1604 ui_add_recent_file(doc->file_name);
1605 return ret;
1609 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1611 GError *conv_error = NULL;
1612 gchar* conv_file_contents = NULL;
1613 gsize bytes_read;
1614 gsize conv_len;
1616 g_return_val_if_fail(data != NULL || *data == NULL, FALSE);
1617 g_return_val_if_fail(len != NULL, FALSE);
1619 /* try to convert it from UTF-8 to original encoding */
1620 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1621 &bytes_read, &conv_len, &conv_error);
1623 if (conv_error != NULL)
1625 gchar *text = g_strdup_printf(
1626 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1627 doc->encoding);
1628 gchar *error_text;
1630 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1632 gchar *context = NULL;
1633 gint line, column;
1634 gint context_len;
1635 gunichar unic;
1636 /* don't read over the doc length */
1637 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1638 context = g_malloc(7); /* read 6 bytes from Sci + '\0' */
1639 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1641 /* take only one valid Unicode character from the context and discard the leftover */
1642 unic = g_utf8_get_char_validated(context, -1);
1643 context_len = g_unichar_to_utf8(unic, context);
1644 context[context_len] = '\0';
1645 get_line_column_from_pos(doc, bytes_read, &line, &column);
1647 error_text = g_strdup_printf(
1648 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1649 conv_error->message, context, line + 1, column);
1650 g_free(context);
1652 else
1653 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1655 geany_debug("encoding error: %s", conv_error->message);
1656 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1657 g_error_free(conv_error);
1658 g_free(text);
1659 g_free(error_text);
1660 return FALSE;
1662 else
1664 g_free(*data);
1665 *data = conv_file_contents;
1666 *len = conv_len;
1669 return TRUE;
1673 static gchar *write_data_to_disk(GeanyDocument *doc, const gchar *locale_filename,
1674 const gchar *data, gint len)
1676 FILE *fp;
1677 gint bytes_written;
1678 gint err = 0;
1679 GError *error = NULL;
1681 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1682 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1684 /* we never use g_file_set_contents() for remote files as Geany only writes such files
1685 * 'into' the Fuse mountpoint, the file itself is then written by GVfs on the target
1686 * remote filesystem. */
1687 if (! file_prefs.use_safe_file_saving || doc->priv->is_remote)
1689 fp = g_fopen(locale_filename, "wb");
1690 if (G_UNLIKELY(fp == NULL))
1691 return g_strdup(g_strerror(errno));
1693 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1695 if (G_UNLIKELY(len != bytes_written))
1696 err = errno;
1698 fclose(fp);
1700 if (err != 0)
1701 return g_strdup(g_strerror(err));
1703 else
1705 g_file_set_contents(locale_filename, data, len, &error);
1706 if (error != NULL)
1708 gchar *msg = g_strdup(error->message);
1709 g_error_free(error);
1710 return msg;
1714 /* now the file is on disk, set real_path */
1715 if (doc->real_path == NULL)
1717 doc->real_path = tm_get_real_path(locale_filename);
1718 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1719 monitor_file_setup(doc);
1722 return NULL;
1727 * Save the document. Saving includes replacing tabs by spaces,
1728 * stripping trailing spaces and adding a final new line at the end of the file (all only if
1729 * user enabled these features). Then the "document-before-save" signal is emitted,
1730 * allowing plugins to modify the document before it is saved, and data is
1731 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1732 * After all, the "document-save" signal is emitted for plugins.
1734 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1736 * @param doc The document to save.
1737 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1739 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1741 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1743 gchar *errmsg;
1744 gchar *data;
1745 gsize len;
1746 gchar *locale_filename;
1748 g_return_val_if_fail(doc != NULL, FALSE);
1750 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1751 if (! force && ! ui_prefs.allow_always_save && (! doc->changed || doc->readonly))
1752 return FALSE;
1754 if (G_UNLIKELY(doc->file_name == NULL))
1756 ui_set_statusbar(TRUE, _("Error saving file."));
1757 utils_beep();
1758 return FALSE;
1761 /* replaces tabs by spaces but only if the current file is not a Makefile */
1762 if (file_prefs.replace_tabs && FILETYPE_ID(doc->file_type) != GEANY_FILETYPES_MAKE)
1763 editor_replace_tabs(doc->editor);
1764 /* strip trailing spaces */
1765 if (file_prefs.strip_trailing_spaces)
1766 editor_strip_trailing_spaces(doc->editor);
1767 /* ensure the file has a newline at the end */
1768 if (file_prefs.final_new_line)
1769 editor_ensure_final_newline(doc->editor);
1771 /* notify plugins which may wish to modify the document before it's saved */
1772 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1774 len = sci_get_length(doc->editor->sci) + 1;
1775 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1776 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1777 * encoding, it will be converted to doc->encoding below and this conversion
1778 * also changes the BOM */
1779 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1780 data[0] = (gchar) 0xef;
1781 data[1] = (gchar) 0xbb;
1782 data[2] = (gchar) 0xbf;
1783 sci_get_text(doc->editor->sci, len, data + 3);
1784 len += 3;
1786 else
1788 data = (gchar*) g_malloc(len);
1789 sci_get_text(doc->editor->sci, len, data);
1792 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1793 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1794 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1796 if (! save_convert_to_encoding(doc, &data, &len))
1798 g_free(data);
1799 return FALSE;
1802 else
1804 len = strlen(data);
1807 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1809 /* ignore file changed notification when the file is written */
1810 doc->priv->file_disk_status = FILE_IGNORE;
1812 /* actually write the content of data to the file on disk */
1813 errmsg = write_data_to_disk(doc, locale_filename, data, len);
1814 g_free(data);
1816 if (errmsg != NULL)
1818 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1819 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1820 doc->priv->file_disk_status = FILE_OK;
1821 utils_beep();
1822 g_free(locale_filename);
1823 g_free(errmsg);
1824 return FALSE;
1827 /* store the opened encoding for undo/redo */
1828 store_saved_encoding(doc);
1830 /* ignore the following things if we are quitting */
1831 if (! main_status.quitting)
1833 sci_set_savepoint(doc->editor->sci);
1835 if (file_prefs.disk_check_timeout > 0)
1836 document_update_timestamp(doc, locale_filename);
1838 /* update filetype-related things */
1839 document_set_filetype(doc, doc->file_type);
1841 document_update_tab_label(doc);
1843 msgwin_status_add(_("File %s saved."), doc->file_name);
1844 ui_update_statusbar(doc, -1);
1845 #ifdef HAVE_VTE
1846 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1847 #endif
1849 g_free(locale_filename);
1851 g_signal_emit_by_name(geany_object, "document-save", doc);
1853 return TRUE;
1857 /* special search function, used from the find entry in the toolbar
1858 * return TRUE if text was found otherwise FALSE
1859 * return also TRUE if text is empty */
1860 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc)
1862 gint start_pos, search_pos;
1863 struct Sci_TextToFind ttf;
1865 g_return_val_if_fail(text != NULL, FALSE);
1866 g_return_val_if_fail(doc != NULL, FALSE);
1867 if (! *text)
1868 return TRUE;
1870 start_pos = (inc) ? sci_get_selection_start(doc->editor->sci) :
1871 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1873 /* search cursor to end */
1874 ttf.chrg.cpMin = start_pos;
1875 ttf.chrg.cpMax = sci_get_length(doc->editor->sci);
1876 ttf.lpstrText = (gchar *)text;
1877 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1879 /* if no match, search start to cursor */
1880 if (search_pos == -1)
1882 ttf.chrg.cpMin = 0;
1883 ttf.chrg.cpMax = start_pos + strlen(text);
1884 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1887 if (search_pos != -1)
1889 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1891 /* unfold maybe folded results */
1892 sci_ensure_line_is_visible(doc->editor->sci, line);
1894 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1895 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1897 if (! editor_line_in_view(doc->editor, line))
1898 { /* we need to force scrolling in case the cursor is outside of the current visible area
1899 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1900 * while searching */
1901 editor_scroll_to_line(doc->editor, -1, 0.3F);
1903 else
1904 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1905 return TRUE;
1907 else
1909 if (! inc)
1911 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1913 utils_beep();
1914 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1915 return FALSE;
1920 /* General search function, used from the find dialog.
1921 * Returns -1 on failure or the start position of the matching text.
1922 * Will skip past any selection, ignoring it. */
1923 gint document_find_text(GeanyDocument *doc, const gchar *text, gint flags, gboolean search_backwards,
1924 gboolean scroll, GtkWidget *parent)
1926 gint selection_end, selection_start, search_pos;
1928 g_return_val_if_fail(doc != NULL && text != NULL, -1);
1929 if (! *text)
1930 return -1;
1932 /* Sci doesn't support searching backwards with a regex */
1933 if (flags & SCFIND_REGEXP)
1934 search_backwards = FALSE;
1936 selection_start = sci_get_selection_start(doc->editor->sci);
1937 selection_end = sci_get_selection_end(doc->editor->sci);
1938 if ((selection_end - selection_start) > 0)
1939 { /* there's a selection so go to the end */
1940 if (search_backwards)
1941 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1942 else
1943 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1946 sci_set_search_anchor(doc->editor->sci);
1947 if (search_backwards)
1948 search_pos = sci_search_prev(doc->editor->sci, flags, text);
1949 else
1950 search_pos = sci_search_next(doc->editor->sci, flags, text);
1952 if (search_pos != -1)
1954 /* unfold maybe folded results */
1955 sci_ensure_line_is_visible(doc->editor->sci,
1956 sci_get_line_from_position(doc->editor->sci, search_pos));
1957 if (scroll)
1958 doc->editor->scroll_percent = 0.3F;
1960 else
1962 gint sci_len = sci_get_length(doc->editor->sci);
1964 /* if we just searched the whole text, give up searching. */
1965 if ((selection_end == 0 && ! search_backwards) ||
1966 (selection_end == sci_len && search_backwards))
1968 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1969 utils_beep();
1970 return -1;
1973 /* we searched only part of the document, so ask whether to wraparound. */
1974 if (search_prefs.suppress_dialogs ||
1975 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
1976 _("Wrap search and find again?"), _("\"%s\" was not found."), text))
1978 gint ret;
1980 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
1981 ret = document_find_text(doc, text, flags, search_backwards, scroll, parent);
1982 if (ret == -1)
1983 { /* return to original cursor position if not found */
1984 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
1986 return ret;
1989 return search_pos;
1993 /* Replaces the selection if it matches, otherwise just finds the next match.
1994 * Returns: start of replaced text, or -1 if no replacement was made */
1995 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
1996 gint flags, gboolean search_backwards)
1998 gint selection_end, selection_start, search_pos;
2000 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2002 if (! *find_text)
2003 return -1;
2005 /* Sci doesn't support searching backwards with a regex */
2006 if (flags & SCFIND_REGEXP)
2007 search_backwards = FALSE;
2009 selection_start = sci_get_selection_start(doc->editor->sci);
2010 selection_end = sci_get_selection_end(doc->editor->sci);
2011 if (selection_end == selection_start)
2013 /* no selection so just find the next match */
2014 document_find_text(doc, find_text, flags, search_backwards, TRUE, NULL);
2015 return -1;
2017 /* there's a selection so go to the start before finding to search through it
2018 * this ensures there is a match */
2019 if (search_backwards)
2020 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2021 else
2022 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2024 search_pos = document_find_text(doc, find_text, flags, search_backwards, TRUE, NULL);
2025 /* return if the original selected text did not match (at the start of the selection) */
2026 if (search_pos != selection_start)
2027 return -1;
2029 if (search_pos != -1)
2031 gint replace_len;
2032 /* search next/prev will select matching text, which we use to set the replace target */
2033 sci_target_from_selection(doc->editor->sci);
2034 replace_len = sci_replace_target(doc->editor->sci, replace_text, flags & SCFIND_REGEXP);
2035 /* select the replacement - find text will skip past the selected text */
2036 sci_set_selection_start(doc->editor->sci, search_pos);
2037 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2039 else
2041 /* no match in the selection */
2042 utils_beep();
2044 return search_pos;
2048 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *find_text,
2049 const gchar *replace_text, gboolean escaped_chars)
2051 gchar *escaped_find_text, *escaped_replace_text, *filename;
2053 if (count == 0)
2055 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), find_text);
2056 return;
2059 filename = g_path_get_basename(DOC_FILENAME(doc));
2061 if (escaped_chars)
2062 { /* escape special characters for showing */
2063 escaped_find_text = g_strescape(find_text, NULL);
2064 escaped_replace_text = g_strescape(replace_text, NULL);
2065 ui_set_statusbar(TRUE, ngettext(
2066 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2067 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2068 count), filename, count, escaped_find_text, escaped_replace_text);
2069 g_free(escaped_find_text);
2070 g_free(escaped_replace_text);
2072 else
2074 ui_set_statusbar(TRUE, ngettext(
2075 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2076 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2077 count), filename, count, find_text, replace_text);
2079 g_free(filename);
2083 /* Replace all text matches in a certain range within document.
2084 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2085 * or -1 if no text was found.
2086 * scroll_to_match is whether to scroll the last replacement in view (which also
2087 * clears the selection).
2088 * Returns: the number of replacements made. */
2089 static guint
2090 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2091 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2093 gint count = 0;
2094 struct Sci_TextToFind ttf;
2095 ScintillaObject *sci;
2097 if (new_range_end != NULL)
2098 *new_range_end = -1;
2100 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2102 if (! *find_text || doc->readonly)
2103 return 0;
2105 sci = doc->editor->sci;
2107 sci_start_undo_action(sci);
2108 ttf.chrg.cpMin = start;
2109 ttf.chrg.cpMax = end;
2110 ttf.lpstrText = (gchar*)find_text;
2112 while (TRUE)
2114 gint search_pos;
2115 gint find_len = 0, replace_len = 0;
2117 search_pos = sci_find_text(sci, flags, &ttf);
2118 find_len = ttf.chrgText.cpMax - ttf.chrgText.cpMin;
2119 if (search_pos == -1)
2120 break; /* no more matches */
2121 if (find_len == 0 && ! NZV(replace_text))
2122 break; /* nothing to do */
2124 if (search_pos + find_len > end)
2125 break; /* found text is partly out of range */
2126 else
2128 gint movepastEOL = 0;
2130 sci_set_target_start(sci, search_pos);
2131 sci_set_target_end(sci, search_pos + find_len);
2133 if (find_len <= 0)
2135 gchar chNext = sci_get_char_at(sci, sci_get_target_end(sci));
2137 if (chNext == '\r' || chNext == '\n')
2138 movepastEOL = 1;
2140 replace_len = sci_replace_target(sci, replace_text,
2141 flags & SCFIND_REGEXP);
2142 count++;
2143 if (search_pos == end)
2144 break; /* Prevent hang when replacing regex $ */
2146 /* make the next search start after the replaced text */
2147 start = search_pos + replace_len + movepastEOL;
2148 if (find_len == 0)
2149 start = sci_get_position_after(sci, start); /* prevent '[ ]*' regex rematching part of replaced text */
2150 ttf.chrg.cpMin = start;
2151 end += replace_len - find_len; /* update end of range now text has changed */
2152 ttf.chrg.cpMax = end;
2155 sci_end_undo_action(sci);
2157 if (count > 0)
2158 { /* scroll last match in view, will destroy the existing selection */
2159 if (scroll_to_match)
2160 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2162 if (new_range_end != NULL)
2163 *new_range_end = end;
2165 return count;
2169 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2170 gint flags, gboolean escaped_chars)
2172 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2173 gint max_column = 0, count = 0;
2174 gboolean replaced = FALSE;
2176 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2178 if (! *find_text)
2179 return;
2181 selection_start = sci_get_selection_start(doc->editor->sci);
2182 selection_end = sci_get_selection_end(doc->editor->sci);
2183 /* do we have a selection? */
2184 if ((selection_end - selection_start) == 0)
2186 utils_beep();
2187 return;
2190 selection_mode = sci_get_selection_mode(doc->editor->sci);
2191 selected_lines = sci_get_lines_selected(doc->editor->sci);
2192 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2193 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2195 gint first_line, line;
2197 sci_start_undo_action(doc->editor->sci);
2199 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2200 /* Find the last line with chars selected (not EOL char) */
2201 last_line = sci_get_line_from_position(doc->editor->sci,
2202 selection_end - editor_get_eol_char_len(doc->editor));
2203 last_line = MAX(first_line, last_line);
2204 for (line = first_line; line < (first_line + selected_lines); line++)
2206 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2207 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2209 /* skip line if there is no selection */
2210 if (line_start != INVALID_POSITION)
2212 /* don't let document_replace_range() scroll to match to keep our selection */
2213 gint new_sel_end;
2215 count += document_replace_range(doc, find_text, replace_text, flags,
2216 line_start, line_end, FALSE, &new_sel_end);
2217 if (new_sel_end != -1)
2219 replaced = TRUE;
2220 /* this gets the greatest column within the selection after replacing */
2221 max_column = MAX(max_column,
2222 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2226 sci_end_undo_action(doc->editor->sci);
2228 else /* handle normal line selection */
2230 count += document_replace_range(doc, find_text, replace_text, flags,
2231 selection_start, selection_end, TRUE, &selection_end);
2232 if (selection_end != -1)
2233 replaced = TRUE;
2236 if (replaced)
2237 { /* update the selection for the new endpoint */
2239 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2241 /* now we can scroll to the selection and destroy it because we rebuild it later */
2242 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2244 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2245 * the highest column on the last line. The wrapped selection is completely different
2246 * from the original one, so skip the selection at all */
2247 /* TODO is there a better way to handle the wrapped selection? */
2248 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2249 { /* for keeping and adjusting the selection in multi line rectangle selection we
2250 * need the last line of the original selection and the greatest column number after
2251 * replacing and set the selection end to the last line at the greatest column */
2252 sci_set_selection_start(doc->editor->sci, selection_start);
2253 sci_set_selection_end(doc->editor->sci,
2254 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2255 sci_set_selection_mode(doc->editor->sci, selection_mode);
2258 else
2260 sci_set_selection_start(doc->editor->sci, selection_start);
2261 sci_set_selection_end(doc->editor->sci, selection_end);
2264 else /* no replacements */
2265 utils_beep();
2267 show_replace_summary(doc, count, find_text, replace_text, escaped_chars);
2271 /* returns TRUE if at least one replacement was made. */
2272 gboolean document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2273 gint flags, gboolean escaped_chars)
2275 gint len, count;
2276 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2278 if (! *find_text)
2279 return FALSE;
2281 len = sci_get_length(doc->editor->sci);
2282 count = document_replace_range(
2283 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2285 show_replace_summary(doc, count, find_text, replace_text, escaped_chars);
2286 return (count > 0);
2290 static gboolean update_tags_from_buffer(GeanyDocument *doc)
2292 gboolean result;
2293 #if 1
2294 /* old code */
2295 result = tm_source_file_update(doc->tm_file, TRUE, FALSE, TRUE);
2296 #else
2297 gsize len = sci_get_length(doc->editor->sci) + 1;
2298 gchar *text = g_malloc(len);
2300 /* we copy the whole text into memory instead using a direct char pointer from
2301 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2302 sci_get_text(doc->editor->sci, len, text);
2303 result = tm_source_file_buffer_update(doc->tm_file, (guchar*) text, len, TRUE);
2304 g_free(text);
2305 #endif
2306 return result;
2310 void document_update_tag_list(GeanyDocument *doc, gboolean update)
2312 /* We must call sidebar_update_tag_list() before returning,
2313 * to ensure that the symbol list is always updated properly (e.g.
2314 * when creating a new document with a partial filename set. */
2315 gboolean success = FALSE;
2317 /* if the filetype doesn't have a tag parser or it is a new file */
2318 if (doc == NULL || doc->file_type == NULL || app->tm_workspace == NULL ||
2319 ! filetype_has_tags(doc->file_type) || ! doc->file_name)
2321 /* set the default (empty) tag list */
2322 sidebar_update_tag_list(doc, FALSE);
2323 return;
2326 if (doc->tm_file == NULL)
2328 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2329 const gchar *name;
2331 /* lookup the name rather than using filetype name to support custom filetypes */
2332 name = tm_source_file_get_lang_name(doc->file_type->lang);
2333 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2334 g_free(locale_filename);
2336 if (doc->tm_file)
2338 if (!tm_workspace_add_object(doc->tm_file))
2340 tm_work_object_free(doc->tm_file);
2341 doc->tm_file = NULL;
2343 else
2345 if (update)
2346 update_tags_from_buffer(doc);
2347 success = TRUE;
2351 else
2353 success = update_tags_from_buffer(doc);
2354 if (G_UNLIKELY(! success))
2355 geany_debug("tag list updating failed");
2357 sidebar_update_tag_list(doc, success);
2361 /* Caches the list of project typenames, as a space separated GString.
2362 * Returns: TRUE if typenames have changed.
2363 * (*types) is set to the list of typenames, or NULL if there are none. */
2364 static gboolean get_project_typenames(const GString **types, gint lang)
2366 static GString *last_typenames = NULL;
2367 GString *s = NULL;
2369 if (app->tm_workspace)
2371 GPtrArray *tags_array = app->tm_workspace->work_object.tags_array;
2373 if (tags_array)
2375 s = symbols_find_tags_as_string(tags_array, TM_GLOBAL_TYPE_MASK, lang);
2379 if (s && last_typenames && g_string_equal(s, last_typenames))
2381 g_string_free(s, TRUE);
2382 *types = last_typenames;
2383 return FALSE; /* project typenames haven't changed */
2385 /* cache typename list for next time */
2386 if (last_typenames)
2387 g_string_free(last_typenames, TRUE);
2388 last_typenames = s;
2390 *types = s;
2391 if (s == NULL)
2392 return FALSE;
2393 return TRUE;
2397 /* If sci is NULL, update project typenames for all documents that support typenames,
2398 * if typenames have changed.
2399 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2400 * if necessary, and typename keywords are set for sci.
2401 * Returns: TRUE if any scintilla type keywords were updated. */
2402 static gboolean update_type_keywords(GeanyDocument *doc, gint lang)
2404 gboolean ret = FALSE;
2405 guint n;
2406 const GString *s;
2407 ScintillaObject *sci;
2409 g_return_val_if_fail(doc != NULL, FALSE);
2410 sci = doc->editor->sci;
2412 switch (FILETYPE_ID(doc->file_type))
2413 { /* continue working with the following languages, skip on all others */
2414 case GEANY_FILETYPES_C:
2415 case GEANY_FILETYPES_CPP:
2416 case GEANY_FILETYPES_CS:
2417 case GEANY_FILETYPES_D:
2418 case GEANY_FILETYPES_JAVA:
2419 case GEANY_FILETYPES_VALA:
2420 break;
2421 default:
2422 return FALSE;
2425 sci = doc->editor->sci;
2426 if (sci != NULL && editor_lexer_get_type_keyword_idx(sci_get_lexer(sci)) == -1)
2427 return FALSE;
2429 if (! get_project_typenames(&s, lang))
2430 { /* typenames have not changed */
2431 if (s != NULL && sci != NULL)
2433 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(sci));
2435 sci_set_keywords(sci, keyword_idx, s->str);
2436 queue_colourise(doc);
2438 return FALSE;
2440 g_return_val_if_fail(s != NULL, FALSE);
2442 for (n = 0; n < documents_array->len; n++)
2444 if (documents[n]->is_valid)
2446 ScintillaObject *wid = documents[n]->editor->sci;
2447 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(wid));
2449 if (keyword_idx > 0)
2451 sci_set_keywords(wid, keyword_idx, s->str);
2452 queue_colourise(documents[n]);
2453 ret = TRUE;
2457 return ret;
2461 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2462 gboolean filetype_changed)
2464 g_return_if_fail(doc);
2465 if (type == NULL)
2466 type = filetypes[GEANY_FILETYPES_NONE];
2468 if (filetype_changed)
2470 doc->file_type = type;
2472 /* delete tm file object to force creation of a new one */
2473 if (doc->tm_file != NULL)
2475 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2476 doc->tm_file = NULL;
2478 /* load tags files before highlighting (some lexers highlight global typenames) */
2479 if (type->id != GEANY_FILETYPES_NONE)
2480 symbols_global_tags_loaded(type->id);
2482 highlighting_set_styles(doc->editor->sci, type);
2483 editor_set_indentation_guides(doc->editor);
2484 build_menu_update(doc);
2485 queue_colourise(doc);
2488 document_update_tag_list(doc, TRUE);
2490 /* Update session typename keywords. */
2491 update_type_keywords(doc, type->lang);
2495 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2496 * @param doc The document to use.
2497 * @param type The filetype. */
2498 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2500 gboolean ft_changed;
2501 GeanyFiletype *old_ft;
2503 g_return_if_fail(doc);
2504 if (type == NULL)
2505 type = filetypes[GEANY_FILETYPES_NONE];
2507 old_ft = doc->file_type;
2508 geany_debug("%s : %s (%s)",
2509 (doc->file_name != NULL) ? doc->file_name : "unknown",
2510 (type->name != NULL) ? type->name : "unknown",
2511 (doc->encoding != NULL) ? doc->encoding : "unknown");
2513 ft_changed = (doc->file_type != type); /* filetype has changed */
2514 document_load_config(doc, type, ft_changed);
2516 if (ft_changed)
2517 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2521 void document_reload_config(GeanyDocument *doc)
2523 document_load_config(doc, doc->file_type, TRUE);
2528 * Sets the encoding of a document.
2529 * This function only set the encoding of the %document, it does not any conversions. The new
2530 * encoding is used when e.g. saving the file.
2532 * @param doc The document to use.
2533 * @param new_encoding The encoding to be set for the document.
2535 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2537 if (doc == NULL || new_encoding == NULL ||
2538 utils_str_equal(new_encoding, doc->encoding))
2539 return;
2541 g_free(doc->encoding);
2542 doc->encoding = g_strdup(new_encoding);
2544 ui_update_statusbar(doc, -1);
2545 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2546 encodings_is_unicode_charset(doc->encoding));
2550 /* own Undo / Redo implementation to be able to undo / redo changes
2551 * to the encoding or the Unicode BOM (which are Scintilla independet).
2552 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2554 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2555 void document_undo_clear(GeanyDocument *doc)
2557 undo_action *a;
2559 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2561 a = g_trash_stack_pop(&doc->priv->undo_actions);
2562 if (G_LIKELY(a != NULL))
2564 switch (a->type)
2566 case UNDO_ENCODING: g_free(a->data); break;
2567 default: break;
2569 g_free(a);
2572 doc->priv->undo_actions = NULL;
2574 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2576 a = g_trash_stack_pop(&doc->priv->redo_actions);
2577 if (G_LIKELY(a != NULL))
2579 switch (a->type)
2581 case UNDO_ENCODING: g_free(a->data); break;
2582 default: break;
2584 g_free(a);
2587 doc->priv->redo_actions = NULL;
2589 if (! main_status.quitting && doc->editor != NULL)
2590 document_set_text_changed(doc, FALSE);
2594 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2596 undo_action *action;
2598 g_return_if_fail(doc != NULL);
2600 action = g_new0(undo_action, 1);
2601 action->type = type;
2602 action->data = data;
2604 g_trash_stack_push(&doc->priv->undo_actions, action);
2606 document_set_text_changed(doc, TRUE);
2607 ui_update_popup_reundo_items(doc);
2611 gboolean document_can_undo(GeanyDocument *doc)
2613 g_return_val_if_fail(doc != NULL, FALSE);
2615 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2616 return TRUE;
2617 else
2618 return FALSE;
2622 static void update_changed_state(GeanyDocument *doc)
2624 doc->changed =
2625 (sci_is_modified(doc->editor->sci) ||
2626 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2627 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2628 document_set_text_changed(doc, doc->changed);
2632 void document_undo(GeanyDocument *doc)
2634 undo_action *action;
2636 g_return_if_fail(doc != NULL);
2638 action = g_trash_stack_pop(&doc->priv->undo_actions);
2640 if (G_UNLIKELY(action == NULL))
2642 /* fallback, should not be necessary */
2643 geany_debug("%s: fallback used", G_STRFUNC);
2644 sci_undo(doc->editor->sci);
2646 else
2648 switch (action->type)
2650 case UNDO_SCINTILLA:
2652 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2654 sci_undo(doc->editor->sci);
2655 break;
2657 case UNDO_BOM:
2659 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2661 doc->has_bom = GPOINTER_TO_INT(action->data);
2662 ui_update_statusbar(doc, -1);
2663 ui_document_show_hide(doc);
2664 break;
2666 case UNDO_ENCODING:
2668 /* use the "old" encoding */
2669 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2671 document_set_encoding(doc, (const gchar*)action->data);
2673 ignore_callback = TRUE;
2674 encodings_select_radio_item((const gchar*)action->data);
2675 ignore_callback = FALSE;
2677 g_free(action->data);
2678 break;
2680 default: break;
2683 g_free(action); /* free the action which was taken from the stack */
2685 update_changed_state(doc);
2686 ui_update_popup_reundo_items(doc);
2690 gboolean document_can_redo(GeanyDocument *doc)
2692 g_return_val_if_fail(doc != NULL, FALSE);
2694 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2695 return TRUE;
2696 else
2697 return FALSE;
2701 void document_redo(GeanyDocument *doc)
2703 undo_action *action;
2705 g_return_if_fail(doc != NULL);
2707 action = g_trash_stack_pop(&doc->priv->redo_actions);
2709 if (G_UNLIKELY(action == NULL))
2711 /* fallback, should not be necessary */
2712 geany_debug("%s: fallback used", G_STRFUNC);
2713 sci_redo(doc->editor->sci);
2715 else
2717 switch (action->type)
2719 case UNDO_SCINTILLA:
2721 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2723 sci_redo(doc->editor->sci);
2724 break;
2726 case UNDO_BOM:
2728 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2730 doc->has_bom = GPOINTER_TO_INT(action->data);
2731 ui_update_statusbar(doc, -1);
2732 ui_document_show_hide(doc);
2733 break;
2735 case UNDO_ENCODING:
2737 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2739 document_set_encoding(doc, (const gchar*)action->data);
2741 ignore_callback = TRUE;
2742 encodings_select_radio_item((const gchar*)action->data);
2743 ignore_callback = FALSE;
2745 g_free(action->data);
2746 break;
2748 default: break;
2751 g_free(action); /* free the action which was taken from the stack */
2753 update_changed_state(doc);
2754 ui_update_popup_reundo_items(doc);
2758 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2760 undo_action *action;
2762 g_return_if_fail(doc != NULL);
2764 action = g_new0(undo_action, 1);
2765 action->type = type;
2766 action->data = data;
2768 g_trash_stack_push(&doc->priv->redo_actions, action);
2770 document_set_text_changed(doc, TRUE);
2771 ui_update_popup_reundo_items(doc);
2776 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2777 * Returned colors are red if the document has changes, green if the document is read-only
2778 * or simply @c NULL if the document is unmodified but writable.
2780 * @param doc The document to use.
2782 * @return The color for the document or @c NULL if the default color should be used. The color
2783 * object is owned by Geany and should not be modified or freed.
2785 * @since 0.16
2787 const GdkColor *document_get_status_color(GeanyDocument *doc)
2789 static GdkColor red = {0, 0xFFFF, 0, 0};
2790 static GdkColor green = {0, 0, 0x7FFF, 0};
2791 #if USE_GIO_FILEMON
2792 static GdkColor orange = {0, 0xFFFF, 0x7FFF, 0};
2793 #endif
2794 GdkColor *color = NULL;
2796 g_return_val_if_fail(doc != NULL, NULL);
2798 if (doc->changed)
2799 color = &red;
2800 #if USE_GIO_FILEMON
2801 else if (doc->priv->file_disk_status == FILE_CHANGED)
2802 color = &orange;
2803 #endif
2804 else if (doc->readonly)
2805 color = &green;
2807 return color; /* return pointer to static GdkColor. */
2811 /** Accessor function for @ref GeanyData::documents_array items.
2812 * @warning Always check the returned document is valid (@c doc->is_valid).
2813 * @param idx @c documents_array index.
2814 * @return The document, or @c NULL if @a idx is out of range.
2816 * @since 0.16
2818 GeanyDocument *document_index(gint idx)
2820 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2824 /* create a new file and copy file content and properties */
2825 GeanyDocument *document_clone(GeanyDocument *old_doc, const gchar *utf8_filename)
2827 gint len;
2828 gchar *text;
2829 GeanyDocument *doc;
2831 g_return_val_if_fail(old_doc != NULL, NULL);
2833 len = sci_get_length(old_doc->editor->sci) + 1;
2834 text = (gchar*) g_malloc(len);
2835 sci_get_text(old_doc->editor->sci, len, text);
2836 /* use old file type (or maybe NULL for auto detect would be better?) */
2837 doc = document_new_file(utf8_filename, old_doc->file_type, text);
2838 g_free(text);
2840 /* copy file properties */
2841 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2842 doc->readonly = old_doc->readonly;
2843 doc->has_bom = old_doc->has_bom;
2844 document_set_encoding(doc, old_doc->encoding);
2845 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2846 sci_set_readonly(doc->editor->sci, doc->readonly);
2848 ui_document_show_hide(doc);
2849 return doc;
2853 /* @note If successful, this should always be followed up with a call to
2854 * document_close_all().
2855 * @return TRUE if all files were saved or had their changes discarded. */
2856 gboolean document_account_for_unsaved(void)
2858 guint i, p, page_count, len = documents_array->len;
2859 GeanyDocument *doc;
2861 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2862 for (p = 0; p < page_count; p++)
2864 doc = document_get_from_page(p);
2865 if (doc->changed)
2867 if (! dialogs_show_unsaved_file(doc))
2868 return FALSE;
2871 /* all documents should now be accounted for, so ignore any changes */
2872 for (i = 0; i < len; i++)
2874 doc = documents[i];
2875 if (doc->is_valid && doc->changed)
2877 doc->changed = FALSE;
2880 return TRUE;
2884 static void force_close_all(void)
2886 guint i, len = documents_array->len;
2888 /* check all documents have been accounted for */
2889 for (i = 0; i < len; i++)
2891 if (documents[i]->is_valid)
2893 g_return_if_fail(!documents[i]->changed);
2896 main_status.closing_all = TRUE;
2898 while (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) > 0)
2900 document_remove_page(0);
2903 main_status.closing_all = FALSE;
2907 gboolean document_close_all(void)
2909 if (! document_account_for_unsaved())
2910 return FALSE;
2912 force_close_all();
2914 return TRUE;
2918 static gboolean monitor_reload_file(GeanyDocument *doc)
2920 gchar *base_name = g_path_get_basename(doc->file_name);
2921 gboolean want_reload;
2923 want_reload = dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
2924 _("Do you want to reload it?"),
2925 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2926 base_name);
2928 if (want_reload)
2929 document_reload_file(doc, doc->encoding);
2931 g_free(base_name);
2932 return want_reload;
2936 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2938 gboolean want_reload = FALSE;
2940 /* file is missing - set unsaved state */
2941 document_set_text_changed(doc, TRUE);
2942 /* don't prompt more than once */
2943 setptr(doc->real_path, NULL);
2945 if (dialogs_show_question_full(NULL, GTK_STOCK_SAVE, GTK_STOCK_CANCEL,
2946 _("Try to resave the file?"),
2947 _("File \"%s\" was not found on disk!"), doc->file_name))
2949 dialogs_show_save_as();
2950 want_reload = TRUE;
2952 return want_reload;
2956 /* Set force to force a disk check, otherwise it is ignored if there was a check
2957 * in the last file_prefs.disk_check_timeout seconds.
2958 * @return @c TRUE if the file has changed. */
2959 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
2961 gboolean ret = FALSE;
2962 gboolean use_gio_filemon;
2963 time_t cur_time = 0;
2964 struct stat st;
2965 gchar *locale_filename;
2966 FileDiskStatus old_status;
2968 g_return_val_if_fail(doc != NULL, FALSE);
2970 /* ignore remote files and documents that have never been saved to disk */
2971 if (file_prefs.disk_check_timeout == 0 || doc->real_path == NULL || doc->priv->is_remote)
2972 return FALSE;
2974 use_gio_filemon = (doc->priv->monitor != NULL);
2976 if (use_gio_filemon)
2978 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
2979 return FALSE;
2981 else
2983 cur_time = time(NULL);
2984 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
2985 return FALSE;
2987 doc->priv->last_check = cur_time;
2990 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2991 if (g_stat(locale_filename, &st) != 0)
2993 monitor_resave_missing_file(doc);
2994 ret = TRUE;
2996 else if (! use_gio_filemon && /* ignore these checks when using GIO */
2997 (G_UNLIKELY(doc->priv->mtime > cur_time) || G_UNLIKELY(st.st_mtime > cur_time)))
2999 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
3001 else if (doc->priv->mtime < st.st_mtime)
3003 monitor_reload_file(doc);
3004 doc->priv->mtime = st.st_mtime;
3005 ret = TRUE;
3007 g_free(locale_filename);
3009 old_status = doc->priv->file_disk_status;
3010 doc->priv->file_disk_status = FILE_OK;
3011 if (old_status != doc->priv->file_disk_status)
3012 ui_update_tab_status(doc);
3014 return ret;