Support more folding icon styles: arrows, +/- and no lines
[geany-mirror.git] / src / document.c
blob8ebfd0badf113db50917cb7119db74f7cc6c69e2
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 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 <stdlib.h>
46 /* gstdio.h also includes sys/stat.h */
47 #include <glib/gstdio.h>
49 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
50 /*#define USE_GIO_FILEMON 1*/
51 #if USE_GIO_FILEMON
52 # ifdef HAVE_GIO
53 # include <gio/gio.h>
54 # else
55 # undef USE_GIO_FILEMON
56 # endif
57 #endif
59 #include "document.h"
60 #include "documentprivate.h"
61 #include "filetypes.h"
62 #include "support.h"
63 #include "sciwrappers.h"
64 #include "editor.h"
65 #include "dialogs.h"
66 #include "msgwindow.h"
67 #include "templates.h"
68 #include "sidebar.h"
69 #include "ui_utils.h"
70 #include "utils.h"
71 #include "encodings.h"
72 #include "notebook.h"
73 #include "main.h"
74 #include "vte.h"
75 #include "build.h"
76 #include "symbols.h"
77 #include "highlighting.h"
78 #include "navqueue.h"
79 #include "win32.h"
80 #include "search.h"
83 GeanyFilePrefs file_prefs;
85 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
86 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
87 * to a document over time, but it might no longer represent a notebook tab. To check this,
88 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
89 * file by then.
91 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
92 * although usually you would just use the foreach_document() macro.
94 * Never assume that the order of document pointers is the same as the order of notebook tabs.
95 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
96 GPtrArray *documents_array;
99 /* an undo action, also used for redo actions */
100 typedef struct
102 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
103 guint type; /* to identify the action */
104 gpointer *data; /* the old value (before the change), in case of a redo action
105 * it contains the new value */
106 } undo_action;
109 static void document_undo_clear(GeanyDocument *doc);
110 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
111 static gboolean update_tags_from_buffer(GeanyDocument *doc);
114 /* ignore the case of filenames and paths under WIN32, causes errors if not */
115 #ifdef G_OS_WIN32
116 #define filenamecmp(a, b) utils_str_casecmp((a), (b))
117 #else
118 #define filenamecmp(a, b) strcmp((a), (b))
119 #endif
122 * Finds a document whose @c real_path field matches the given filename.
124 * @param realname The filename to search, which should be identical to the
125 * string returned by @c tm_get_real_path().
127 * @return The matching document, or @c NULL.
128 * @note This is only really useful when passing a @c TMWorkObject::file_name.
129 * @see GeanyDocument::real_path.
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 * Finds a document with the given filename.
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 /** Gets 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 * Finds 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 * Finds 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 * Updates 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, GtkWidget *source_widget)
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 (source_widget == NULL)
528 source_widget = doc->priv->tag_tree;
530 if (focusw == source_widget)
531 gtk_widget_grab_focus(sci);
536 static gboolean on_idle_focus(gpointer doc)
538 document_try_focus(doc, NULL);
539 return FALSE;
543 /* Creates a new document and editor, adding a tab in the notebook.
544 * @return The created document */
545 static GeanyDocument *document_create(const gchar *utf8_filename)
547 GeanyDocument *doc;
548 gint new_idx;
549 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
551 if (cur_pages == 1)
553 GeanyDocument *cur = document_get_current();
554 /* remove the empty document and open a new one */
555 if (cur != NULL && cur->file_name == NULL && ! cur->changed)
556 document_remove_page(0);
559 new_idx = document_get_new_idx();
560 if (new_idx == -1) /* expand the array, no free places */
562 GeanyDocument *new_doc = g_new0(GeanyDocument, 1);
564 new_idx = documents_array->len;
565 g_ptr_array_add(documents_array, new_doc);
567 doc = documents[new_idx];
568 init_doc_struct(doc); /* initialize default document settings */
569 doc->index = new_idx;
571 doc->file_name = g_strdup(utf8_filename);
573 doc->editor = editor_create(doc);
575 sidebar_openfiles_add(doc); /* sets doc->iter */
577 notebook_new_tab(doc);
579 /* select document in sidebar */
581 GtkTreeSelection *sel;
583 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
584 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
587 ui_document_buttons_update();
589 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
590 return doc;
595 * Closes the given document.
597 * @param doc The document to remove.
599 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
601 * @since 0.15
603 gboolean document_close(GeanyDocument *doc)
605 g_return_val_if_fail(doc, FALSE);
607 return document_remove_page(document_get_notebook_page(doc));
612 * Removes the given notebook tab at @a page_num and clears all related information
613 * in the document list.
615 * @param page_num The notebook page number to remove.
617 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
619 gboolean document_remove_page(guint page_num)
621 GeanyDocument *doc = document_get_from_page(page_num);
623 if (G_UNLIKELY(doc == NULL))
625 g_warning("%s: page_num: %d", G_STRFUNC, page_num);
626 return FALSE;
629 if (doc->changed && ! dialogs_show_unsaved_file(doc))
631 return FALSE;
634 /* tell any plugins that the document is about to be closed */
635 g_signal_emit_by_name(geany_object, "document-close", doc);
637 /* Checking real_path makes it likely the file exists on disk */
638 if (! main_status.closing_all && doc->real_path != NULL)
639 ui_add_recent_file(doc->file_name);
641 doc->is_valid = FALSE;
643 notebook_remove_page(page_num);
644 sidebar_remove_document(doc);
645 navqueue_remove_file(doc->file_name);
646 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
647 g_free(doc->encoding);
648 g_free(doc->priv->saved_encoding.encoding);
649 g_free(doc->file_name);
650 g_free(doc->real_path);
651 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
653 editor_destroy(doc->editor);
654 doc->editor = NULL;
656 document_stop_file_monitoring(doc);
658 doc->file_name = NULL;
659 doc->real_path = NULL;
660 doc->file_type = NULL;
661 doc->encoding = NULL;
662 doc->has_bom = FALSE;
663 doc->tm_file = NULL;
664 document_undo_clear(doc);
665 g_free(doc->priv);
667 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
669 sidebar_update_tag_list(NULL, FALSE);
670 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
671 ui_set_window_title(NULL);
672 ui_save_buttons_toggle(FALSE);
673 ui_document_buttons_update();
674 build_menu_update(NULL);
676 return TRUE;
680 /* used to keep a record of the unchanged document state encoding */
681 static void store_saved_encoding(GeanyDocument *doc)
683 g_free(doc->priv->saved_encoding.encoding);
684 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
685 doc->priv->saved_encoding.has_bom = doc->has_bom;
689 /* Opens a new empty document only if there are no other documents open */
690 GeanyDocument *document_new_file_if_non_open(void)
692 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
693 return document_new_file(NULL, NULL, NULL);
695 return NULL;
700 * Creates a new document.
701 * Afterwards, the @c "document-new" signal is emitted for plugins.
703 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
704 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
705 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
707 * @return The new document.
709 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft,
710 const gchar *text)
712 GeanyDocument *doc;
714 if (utf8_filename && g_path_is_absolute(utf8_filename))
716 gchar *tmp;
717 tmp = utils_strdupa(utf8_filename); /* work around const */
718 utils_tidy_path(tmp);
719 utf8_filename = tmp;
721 doc = document_create(utf8_filename);
723 g_assert(doc != NULL);
725 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
726 if (text)
727 sci_set_text(doc->editor->sci, text);
728 else
729 sci_clear_all(doc->editor->sci);
731 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
732 /* convert the eol chars in the template text in case they are different from
733 * from file_prefs.default_eol */
734 if (text != NULL)
735 sci_convert_eols(doc->editor->sci, file_prefs.default_eol_character);
737 sci_set_undo_collection(doc->editor->sci, TRUE);
738 sci_empty_undo_buffer(doc->editor->sci);
740 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
741 /* store the opened encoding for undo/redo */
742 store_saved_encoding(doc);
744 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
745 ft = filetypes_detect_from_document(doc);
747 document_set_filetype(doc, ft); /* also clears taglist */
749 ui_set_window_title(doc);
750 build_menu_update(doc);
751 document_update_tag_list(doc, FALSE);
752 document_set_text_changed(doc, FALSE);
753 ui_document_show_hide(doc); /* update the document menu */
755 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
756 /* bring it in front, jump to the start and grab the focus */
757 editor_goto_pos(doc->editor, 0, FALSE);
758 document_try_focus(doc, NULL);
760 #if USE_GIO_FILEMON
761 monitor_file_setup(doc);
762 #else
763 doc->priv->mtime = time(NULL);
764 #endif
766 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
767 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
769 g_signal_emit_by_name(geany_object, "document-new", doc);
771 msgwin_status_add(_("New file \"%s\" opened."),
772 DOC_FILENAME(doc));
774 return doc;
779 * Opens a document specified by @a locale_filename.
780 * Afterwards, the @c "document-open" signal is emitted for plugins.
782 * @param locale_filename The filename of the document to load, in locale encoding.
783 * @param readonly Whether to open the document in read-only mode.
784 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
785 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
787 * @return The document opened or @c NULL.
789 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
790 GeanyFiletype *ft, const gchar *forced_enc)
792 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
796 typedef struct
798 gchar *data; /* null-terminated file data */
799 gsize size; /* actual file size on disk */
800 gsize len; /* string length of data */
801 gchar *enc;
802 gboolean bom;
803 time_t mtime; /* modification time, read by stat::st_mtime */
804 gboolean readonly;
805 } FileData;
808 /* reload file with specified encoding */
809 static gboolean
810 handle_forced_encoding(FileData *filedata, const gchar *forced_enc)
812 GeanyEncodingIndex enc_idx;
814 if (utils_str_equal(forced_enc, "UTF-8"))
816 if (! g_utf8_validate(filedata->data, filedata->len, NULL))
818 return FALSE;
821 else
823 gchar *converted_text = encodings_convert_to_utf8_from_charset(
824 filedata->data, filedata->size, forced_enc, FALSE);
825 if (converted_text == NULL)
827 return FALSE;
829 else
831 g_free(filedata->data);
832 filedata->data = converted_text;
833 filedata->len = strlen(converted_text);
836 enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
837 filedata->bom = (enc_idx == GEANY_ENCODING_UTF_8);
838 filedata->enc = g_strdup(forced_enc);
839 return TRUE;
843 /* detect encoding and convert to UTF-8 if necessary */
844 static gboolean
845 handle_encoding(FileData *filedata, GeanyEncodingIndex enc_idx)
847 g_return_val_if_fail(filedata->enc == NULL, FALSE);
848 g_return_val_if_fail(filedata->bom == FALSE, FALSE);
850 if (filedata->size == 0)
852 /* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
853 * e.g. UTF32 file with a BOM(so size is 4, len is 0) */
854 filedata->enc = g_strdup("UTF-8");
856 else
858 /* first check for a BOM */
859 if (enc_idx != GEANY_ENCODING_NONE)
861 filedata->enc = g_strdup(encodings[enc_idx].charset);
862 filedata->bom = TRUE;
864 if (enc_idx != GEANY_ENCODING_UTF_8) /* the BOM indicated something else than UTF-8 */
866 gchar *converted_text = encodings_convert_to_utf8_from_charset(
867 filedata->data, filedata->size, filedata->enc, FALSE);
868 if (converted_text != NULL)
870 g_free(filedata->data);
871 filedata->data = converted_text;
872 filedata->len = strlen(converted_text);
874 else
876 /* there was a problem converting data from BOM encoding type */
877 g_free(filedata->enc);
878 filedata->enc = NULL;
879 filedata->bom = FALSE;
884 if (filedata->enc == NULL) /* either there was no BOM or the BOM encoding failed */
886 /* try UTF-8 first */
887 if ((filedata->size == filedata->len) &&
888 g_utf8_validate(filedata->data, filedata->len, NULL))
890 filedata->enc = g_strdup("UTF-8");
892 else
894 /* detect the encoding */
895 gchar *converted_text = encodings_convert_to_utf8(filedata->data,
896 filedata->size, &filedata->enc);
898 if (converted_text == NULL)
900 return FALSE;
902 g_free(filedata->data);
903 filedata->data = converted_text;
904 filedata->len = strlen(converted_text);
908 return TRUE;
912 static void
913 handle_bom(FileData *filedata)
915 guint bom_len;
917 encodings_scan_unicode_bom(filedata->data, filedata->size, &bom_len);
918 g_return_if_fail(bom_len != 0);
920 /* use filedata->len here because the contents are already converted into UTF-8 */
921 filedata->len -= bom_len;
922 /* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
923 g_memmove(filedata->data, filedata->data + bom_len, filedata->len + 1);
924 filedata->data = g_realloc(filedata->data, filedata->len + 1);
928 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
929 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
930 FileData *filedata, const gchar *forced_enc)
932 GError *err = NULL;
933 struct stat st;
934 GeanyEncodingIndex tmp_enc_idx;
936 filedata->data = NULL;
937 filedata->len = 0;
938 filedata->enc = NULL;
939 filedata->bom = FALSE;
940 filedata->readonly = FALSE;
942 if (g_stat(locale_filename, &st) != 0)
944 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
945 display_filename, g_strerror(errno));
946 return FALSE;
949 filedata->mtime = st.st_mtime;
951 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
953 ui_set_statusbar(TRUE, "%s", err->message);
954 g_error_free(err);
955 return FALSE;
958 /* use strlen to check for null chars */
959 filedata->size = (gsize) st.st_size;
960 filedata->len = strlen(filedata->data);
962 /* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
963 * if we have a BOM */
964 tmp_enc_idx = encodings_scan_unicode_bom(filedata->data, filedata->size, NULL);
966 /* check whether the size of the loaded data is equal to the size of the file in the
967 * filesystem file size may be 0 to allow opening files in /proc/ which have typically a
968 * file size of 0 bytes */
969 if (filedata->len != filedata->size && filedata->size != 0 && (
970 tmp_enc_idx == GEANY_ENCODING_UTF_8 || /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
971 tmp_enc_idx == GEANY_ENCODING_UTF_7)) /* filter UTF-7/8 where no NULL bytes are allowed */
973 const gchar *warn_msg = _(
974 "The file \"%s\" could not be opened properly and has been truncated. " \
975 "This can occur if the file contains a NULL byte. " \
976 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
978 if (main_status.main_window_realized)
979 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
981 ui_set_statusbar(TRUE, warn_msg, display_filename);
983 /* set the file to read-only mode because saving it is probably dangerous */
984 filedata->readonly = TRUE;
987 /* Determine character encoding and convert to UTF-8 */
988 if (forced_enc != NULL)
990 /* the encoding should be ignored(requested by user), so open the file "as it is" */
991 if (utils_str_equal(forced_enc, encodings[GEANY_ENCODING_NONE].charset))
993 filedata->bom = FALSE;
994 filedata->enc = g_strdup(encodings[GEANY_ENCODING_NONE].charset);
996 else if (! handle_forced_encoding(filedata, forced_enc))
998 /* For translators: the second wildcard is an encoding name, e.g.
999 * The file \"test.txt\" is not valid UTF-8. */
1000 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
1001 display_filename, forced_enc);
1002 utils_beep();
1003 g_free(filedata->data);
1004 return FALSE;
1007 else if (! handle_encoding(filedata, tmp_enc_idx))
1009 ui_set_statusbar(TRUE,
1010 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1011 display_filename);
1012 utils_beep();
1013 g_free(filedata->data);
1014 return FALSE;
1017 if (filedata->bom)
1018 handle_bom(filedata);
1019 return TRUE;
1023 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1024 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1025 * if cl_options.goto_column is set.
1027 * returns the new position which may have changed */
1028 static gint set_cursor_position(GeanyEditor *editor, gint pos)
1030 if (cl_options.goto_line >= 0)
1031 { /* goto line which was specified on command line and then undefine the line */
1032 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
1033 editor->scroll_percent = 0.5F;
1034 cl_options.goto_line = -1;
1036 else if (pos > 0)
1038 sci_set_current_position(editor->sci, pos, FALSE);
1039 editor->scroll_percent = 0.5F;
1042 if (cl_options.goto_column >= 0)
1043 { /* goto column which was specified on command line and then undefine the column */
1045 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
1046 sci_set_current_position(editor->sci, new_pos, FALSE);
1047 editor->scroll_percent = 0.5F;
1048 cl_options.goto_column = -1;
1049 return new_pos;
1051 return sci_get_current_position(editor->sci);
1055 /* Count lines that start with some hard tabs then a soft tab. */
1056 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
1058 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1059 ScintillaObject *sci = editor->sci;
1060 gsize count = 0;
1061 struct Sci_TextToFind ttf;
1062 gchar *soft_tab = g_strnfill(iprefs->width, ' ');
1063 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
1065 g_free(soft_tab);
1067 ttf.chrg.cpMin = 0;
1068 ttf.chrg.cpMax = sci_get_length(sci);
1069 ttf.lpstrText = regex;
1070 while (1)
1072 gint pos;
1074 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
1075 if (pos == -1)
1076 break; /* no more matches */
1077 count++;
1078 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
1080 g_free(regex);
1081 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1082 return count > sci_get_line_count(sci) * 0.02;
1086 /* Detect the indent type based on counting the leading indent characters for each line. */
1087 static GeanyIndentType detect_indent_type(GeanyEditor *editor)
1089 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1090 ScintillaObject *sci = editor->sci;
1091 guint line, line_count;
1092 gsize tabs = 0, spaces = 0;
1094 if (detect_tabs_and_spaces(editor))
1095 return GEANY_INDENT_TYPE_BOTH;
1097 line_count = sci_get_line_count(sci);
1098 for (line = 0; line < line_count; line++)
1100 gint pos = sci_get_position_from_line(sci, line);
1101 gchar c;
1103 /* most code will have indent total <= 24, otherwise it's more likely to be
1104 * alignment than indentation */
1105 if (sci_get_line_indentation(sci, line) > 24)
1106 continue;
1108 c = sci_get_char_at(sci, pos);
1109 if (c == '\t')
1110 tabs++;
1111 else
1112 if (c == ' ')
1114 /* check for at least 2 spaces */
1115 if (sci_get_char_at(sci, pos + 1) == ' ')
1116 spaces++;
1119 if (spaces == 0 && tabs == 0)
1120 return iprefs->type;
1122 /* the factors may need to be tweaked */
1123 if (spaces > tabs * 4)
1124 return GEANY_INDENT_TYPE_SPACES;
1125 else if (tabs > spaces * 4)
1126 return GEANY_INDENT_TYPE_TABS;
1127 else
1128 return GEANY_INDENT_TYPE_BOTH;
1132 static void set_indentation(GeanyEditor *editor)
1134 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
1136 switch (FILETYPE_ID(editor->document->file_type))
1138 case GEANY_FILETYPES_MAKE:
1139 /* force using tabs for indentation for Makefiles */
1140 editor_set_indent_type(editor, GEANY_INDENT_TYPE_TABS);
1141 return;
1142 case GEANY_FILETYPES_F77:
1143 /* force using spaces for indentation for Fortran 77 */
1144 editor_set_indent_type(editor, GEANY_INDENT_TYPE_SPACES);
1145 return;
1147 if (iprefs->detect_type)
1149 GeanyIndentType type = detect_indent_type(editor);
1151 if (type != iprefs->type)
1153 const gchar *name = NULL;
1155 switch (type)
1157 case GEANY_INDENT_TYPE_SPACES:
1158 name = _("Spaces");
1159 break;
1160 case GEANY_INDENT_TYPE_TABS:
1161 name = _("Tabs");
1162 break;
1163 case GEANY_INDENT_TYPE_BOTH:
1164 name = _("Tabs and Spaces");
1165 break;
1167 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1168 * and Spaces), the second one is the filename */
1169 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1170 DOC_FILENAME(editor->document));
1172 editor_set_indent_type(editor, type);
1177 #if 0
1178 static gboolean auto_update_tag_list(gpointer data)
1180 GeanyDocument *doc = data;
1182 if (! doc || ! doc->is_valid || doc->tm_file == NULL)
1183 return FALSE;
1185 if (gtk_window_get_focus(GTK_WINDOW(main_widgets.window)) != GTK_WIDGET(doc->editor->sci))
1186 return TRUE;
1188 if (update_tags_from_buffer(doc))
1189 sidebar_update_tag_list(doc, TRUE);
1191 return TRUE;
1193 #endif
1196 /* To open a new file, set doc to NULL; filename should be locale encoded.
1197 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1198 * pos is the cursor position, which can be overridden by --line and --column.
1199 * forced_enc can be NULL to detect the file encoding.
1200 * Returns: doc of the opened file or NULL if an error occurred. */
1201 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1202 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1204 gint editor_mode;
1205 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1206 gchar *utf8_filename = NULL;
1207 gchar *display_filename = NULL;
1208 gchar *locale_filename = NULL;
1209 GeanyFiletype *use_ft;
1210 FileData filedata;
1212 if (reload)
1214 utf8_filename = g_strdup(doc->file_name);
1215 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1217 else
1219 /* filename must not be NULL when opening a file */
1220 if (filename == NULL)
1222 ui_set_statusbar(FALSE, _("Invalid filename"));
1223 return NULL;
1226 #ifdef G_OS_WIN32
1227 /* if filename is a shortcut, try to resolve it */
1228 locale_filename = win32_get_shortcut_target(filename);
1229 #else
1230 locale_filename = g_strdup(filename);
1231 #endif
1232 /* remove relative junk */
1233 utils_tidy_path(locale_filename);
1235 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1236 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1238 /* if file is already open, switch to it and go */
1239 doc = document_find_by_filename(utf8_filename);
1240 if (doc != NULL)
1242 ui_add_recent_file(utf8_filename); /* either add or reorder recent item */
1243 /* show the doc before reload dialog */
1244 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1245 gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
1246 (GtkWidget*) doc->editor->sci));
1247 document_check_disk_status(doc, TRUE); /* force a file changed check */
1250 if (reload || doc == NULL)
1251 { /* doc possibly changed */
1252 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1254 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1256 g_free(display_filename);
1257 g_free(utf8_filename);
1258 g_free(locale_filename);
1259 return NULL;
1262 if (! reload)
1264 doc = document_create(utf8_filename);
1265 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1267 /* file exists on disk, set real_path */
1268 setptr(doc->real_path, tm_get_real_path(locale_filename));
1270 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1271 monitor_file_setup(doc);
1274 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1275 sci_empty_undo_buffer(doc->editor->sci);
1277 /* add the text to the ScintillaObject */
1278 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1279 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1280 queue_colourise(doc); /* Ensure the document gets colourised. */
1282 /* detect & set line endings */
1283 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1284 sci_set_eol_mode(doc->editor->sci, editor_mode);
1285 g_free(filedata.data);
1287 sci_set_undo_collection(doc->editor->sci, TRUE);
1289 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1290 g_free(doc->encoding); /* if reloading, free old encoding */
1291 doc->encoding = filedata.enc;
1292 doc->has_bom = filedata.bom;
1293 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1295 doc->readonly = readonly || filedata.readonly;
1296 sci_set_readonly(doc->editor->sci, doc->readonly);
1298 /* update line number margin width */
1299 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1300 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1302 if (! reload)
1305 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1306 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1307 doc->editor);
1309 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1311 else
1312 { /* reloading */
1313 document_undo_clear(doc);
1315 use_ft = ft;
1317 /* update taglist, typedef keywords and build menu if necessary */
1318 document_set_filetype(doc, use_ft);
1320 /* set indentation settings after setting the filetype */
1321 if (reload)
1322 editor_set_indent_type(doc->editor, doc->editor->indent_type); /* resetup sci */
1323 else
1324 set_indentation(doc->editor);
1326 document_set_text_changed(doc, FALSE); /* also updates tab state */
1327 ui_document_show_hide(doc); /* update the document menu */
1329 /* finally add current file to recent files menu, but not the files from the last session */
1330 if (! main_status.opening_session_files)
1331 ui_add_recent_file(utf8_filename);
1333 if (! reload)
1334 g_signal_emit_by_name(geany_object, "document-open", doc);
1336 if (reload)
1337 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1338 else
1339 /* For translators: this is the status window message for opening a file. %d is the number
1340 * of the newly opened file, %s indicates whether the file is opened read-only
1341 * (it is replaced with the string ", read-only"). */
1342 msgwin_status_add(_("File %s opened(%d%s)."),
1343 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1344 (readonly) ? _(", read-only") : "");
1347 g_free(display_filename);
1348 g_free(utf8_filename);
1349 g_free(locale_filename);
1351 /* TODO This could be used to automatically update the symbol list,
1352 * based on a configurable interval */
1353 /*g_timeout_add(10000, auto_update_tag_list, doc);*/
1355 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1356 pos = set_cursor_position(doc->editor, pos);
1357 /* now bring the file in front */
1358 editor_goto_pos(doc->editor, pos, FALSE);
1360 /* finally, let the editor widget grab the focus so you can start coding
1361 * right away */
1362 g_idle_add(on_idle_focus, doc);
1363 return doc;
1367 /* Takes a new line separated list of filename URIs and opens each file.
1368 * length is the length of the string or -1 if it should be detected */
1369 void document_open_file_list(const gchar *data, gssize length)
1371 gint i;
1372 gchar *filename;
1373 gchar **list;
1375 g_return_if_fail(data != NULL);
1377 if (length < 0)
1378 length = strlen(data);
1380 switch (utils_get_line_endings(data, length))
1382 case SC_EOL_CR: list = g_strsplit(data, "\r", 0); break;
1383 case SC_EOL_CRLF: list = g_strsplit(data, "\r\n", 0); break;
1384 case SC_EOL_LF: list = g_strsplit(data, "\n", 0); break;
1385 default: list = g_strsplit(data, "\n", 0);
1388 for (i = 0; ; i++)
1390 if (list[i] == NULL)
1391 break;
1392 filename = g_filename_from_uri(list[i], NULL, NULL);
1393 if (G_UNLIKELY(filename == NULL))
1394 continue;
1395 document_open_file(filename, FALSE, NULL, NULL);
1396 g_free(filename);
1399 g_strfreev(list);
1404 * Opens each file in the list @a filenames.
1405 * Internally, document_open_file() is called for every list item.
1407 * @param filenames A list of filenames to load, in locale encoding.
1408 * @param readonly Whether to open the document in read-only mode.
1409 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1410 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1412 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1413 const gchar *forced_enc)
1415 const GSList *item;
1417 for (item = filenames; item != NULL; item = g_slist_next(item))
1419 document_open_file(item->data, readonly, ft, forced_enc);
1425 * Reloads the document with the specified file encoding
1426 * @a forced_enc or @c NULL to auto-detect the file encoding.
1428 * @param doc The document to reload.
1429 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1431 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1433 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1435 gint pos = 0;
1436 GeanyDocument *new_doc;
1438 g_return_val_if_fail(doc != NULL, FALSE);
1440 /* try to set the cursor to the position before reloading */
1441 pos = sci_get_current_position(doc->editor->sci);
1442 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1444 return (new_doc != NULL);
1448 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1450 #if ! USE_GIO_FILEMON
1451 struct stat st;
1453 g_return_val_if_fail(doc != NULL, FALSE);
1455 /* stat the file to get the timestamp, otherwise on Windows the actual
1456 * timestamp can be ahead of time(NULL) */
1457 if (g_stat(locale_filename, &st) != 0)
1459 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1460 g_strerror(errno));
1461 return FALSE;
1464 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1465 #endif
1466 return TRUE;
1470 /* Sets line and column to the given position byte_pos in the document.
1471 * byte_pos is the position counted in bytes, not characters */
1472 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1474 gint i;
1475 gint line_start;
1477 /* for some reason we can use byte count instead of character count here */
1478 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1479 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1480 /* get the column in the line */
1481 *column = byte_pos - line_start;
1483 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1484 * skip one byte(i++) and decrease the column number which is based on byte count */
1485 for (i = line_start; i < (line_start + *column); i++)
1487 if (sci_get_char_at(doc->editor->sci, i) < 0)
1489 (*column)--;
1490 i++;
1496 static void replace_header_filename(GeanyDocument *doc)
1498 gchar *filebase;
1499 gchar *filename;
1500 struct Sci_TextToFind ttf;
1502 g_return_if_fail(doc != NULL);
1503 g_return_if_fail(doc->file_type != NULL);
1505 if (doc->file_type->extension)
1506 filebase = g_strconcat(GEANY_STRING_UNTITLED, ".", doc->file_type->extension, NULL);
1507 else
1508 filebase = g_strdup(GEANY_STRING_UNTITLED);
1510 filename = g_path_get_basename(doc->file_name);
1512 /* only search the first 3 lines */
1513 ttf.chrg.cpMin = 0;
1514 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 3);
1515 ttf.lpstrText = (gchar*)filebase;
1517 if (sci_find_text(doc->editor->sci, SCFIND_MATCHCASE, &ttf) != -1)
1519 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1520 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1521 sci_replace_target(doc->editor->sci, filename, FALSE);
1524 g_free(filebase);
1525 g_free(filename);
1530 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1531 * you still have to call @ref document_save_file_as() to change the @a doc object.
1532 * It also stops monitoring for file changes to prevent receiving too many file change events
1533 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1535 * @param doc The current document which should be renamed.
1536 * @param new_filename The new filename in UTF-8 encoding.
1538 * @since 0.16
1540 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1542 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1543 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1544 gint result;
1546 /* stop file monitoring to avoid getting events for deleting/creating files,
1547 * it's re-setup in document_save_file_as() */
1548 document_stop_file_monitoring(doc);
1550 result = g_rename(old_locale_filename, new_locale_filename);
1551 if (result != 0)
1553 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1554 _("Error renaming file."), g_strerror(errno));
1556 g_free(old_locale_filename);
1557 g_free(new_locale_filename);
1561 /* Return TRUE if the document hasn't been saved before, i.e. either the filename or
1562 * the real_path is not set. */
1563 gboolean document_need_save_as(GeanyDocument *doc)
1565 g_return_val_if_fail(doc != NULL, FALSE);
1567 return (doc->file_name == NULL || doc->real_path == NULL);
1572 * Saves the document, detecting the filetype.
1574 * @param doc The document for the file to save.
1575 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1576 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1578 * @see document_save_file().
1580 * @since 0.16
1582 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1584 gboolean ret;
1586 g_return_val_if_fail(doc != NULL, FALSE);
1588 if (utf8_fname != NULL)
1589 setptr(doc->file_name, g_strdup(utf8_fname));
1591 /* reset real path, it's retrieved again in document_save() */
1592 setptr(doc->real_path, NULL);
1594 /* detect filetype */
1595 if (FILETYPE_ID(doc->file_type) == GEANY_FILETYPES_NONE)
1597 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1599 document_set_filetype(doc, ft);
1600 if (document_get_current() == doc)
1602 ignore_callback = TRUE;
1603 filetypes_select_radio_item(doc->file_type);
1604 ignore_callback = FALSE;
1607 replace_header_filename(doc);
1609 ret = document_save_file(doc, TRUE);
1611 /* file monitoring support, add file monitoring after the file has been saved
1612 * to ignore any earlier events */
1613 monitor_file_setup(doc);
1614 doc->priv->file_disk_status = FILE_IGNORE;
1616 if (ret)
1617 ui_add_recent_file(doc->file_name);
1618 return ret;
1622 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1624 GError *conv_error = NULL;
1625 gchar* conv_file_contents = NULL;
1626 gsize bytes_read;
1627 gsize conv_len;
1629 g_return_val_if_fail(data != NULL || *data == NULL, FALSE);
1630 g_return_val_if_fail(len != NULL, FALSE);
1632 /* try to convert it from UTF-8 to original encoding */
1633 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1634 &bytes_read, &conv_len, &conv_error);
1636 if (conv_error != NULL)
1638 gchar *text = g_strdup_printf(
1639 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1640 doc->encoding);
1641 gchar *error_text;
1643 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1645 gchar *context = NULL;
1646 gint line, column;
1647 gint context_len;
1648 gunichar unic;
1649 /* don't read over the doc length */
1650 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1651 context = g_malloc(7); /* read 6 bytes from Sci + '\0' */
1652 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1654 /* take only one valid Unicode character from the context and discard the leftover */
1655 unic = g_utf8_get_char_validated(context, -1);
1656 context_len = g_unichar_to_utf8(unic, context);
1657 context[context_len] = '\0';
1658 get_line_column_from_pos(doc, bytes_read, &line, &column);
1660 error_text = g_strdup_printf(
1661 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1662 conv_error->message, context, line + 1, column);
1663 g_free(context);
1665 else
1666 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1668 geany_debug("encoding error: %s", conv_error->message);
1669 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1670 g_error_free(conv_error);
1671 g_free(text);
1672 g_free(error_text);
1673 return FALSE;
1675 else
1677 g_free(*data);
1678 *data = conv_file_contents;
1679 *len = conv_len;
1682 return TRUE;
1686 static gchar *write_data_to_disk(GeanyDocument *doc, const gchar *locale_filename,
1687 const gchar *data, gint len)
1689 FILE *fp;
1690 gint bytes_written;
1691 gint err = 0;
1692 GError *error = NULL;
1694 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1695 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1697 if (! file_prefs.use_safe_file_saving)
1699 fp = g_fopen(locale_filename, "wb");
1700 if (G_UNLIKELY(fp == NULL))
1701 return g_strdup(g_strerror(errno));
1703 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1705 if (G_UNLIKELY(len != bytes_written))
1706 err = errno;
1708 fclose(fp);
1710 if (err != 0)
1711 return g_strdup(g_strerror(err));
1713 else
1715 g_file_set_contents(locale_filename, data, len, &error);
1716 if (error != NULL)
1718 gchar *msg = g_strdup(error->message);
1719 g_error_free(error);
1720 return msg;
1724 /* now the file is on disk, set real_path */
1725 if (doc->real_path == NULL)
1727 doc->real_path = tm_get_real_path(locale_filename);
1728 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1729 monitor_file_setup(doc);
1732 return NULL;
1737 * Saves the document. Saving includes replacing tabs by spaces,
1738 * stripping trailing spaces and adding a final new line at the end of the file (all only if
1739 * user enabled these features). Then the @c "document-before-save" signal is emitted,
1740 * allowing plugins to modify the document before it is saved, and data is
1741 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1742 * Afterwards, the @c "document-save" signal is emitted for plugins.
1744 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1746 * @param doc The document to save.
1747 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1749 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1751 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1753 gchar *errmsg;
1754 gchar *data;
1755 gsize len;
1756 gchar *locale_filename;
1758 g_return_val_if_fail(doc != NULL, FALSE);
1760 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1761 if (! force && ! ui_prefs.allow_always_save && (! doc->changed || doc->readonly))
1762 return FALSE;
1764 if (G_UNLIKELY(doc->file_name == NULL))
1766 ui_set_statusbar(TRUE, _("Error saving file."));
1767 utils_beep();
1768 return FALSE;
1771 /* replaces tabs by spaces but only if the current file is not a Makefile */
1772 if (file_prefs.replace_tabs && FILETYPE_ID(doc->file_type) != GEANY_FILETYPES_MAKE)
1773 editor_replace_tabs(doc->editor);
1774 /* strip trailing spaces */
1775 if (file_prefs.strip_trailing_spaces)
1776 editor_strip_trailing_spaces(doc->editor);
1777 /* ensure the file has a newline at the end */
1778 if (file_prefs.final_new_line)
1779 editor_ensure_final_newline(doc->editor);
1781 /* notify plugins which may wish to modify the document before it's saved */
1782 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1784 len = sci_get_length(doc->editor->sci) + 1;
1785 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1786 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1787 * encoding, it will be converted to doc->encoding below and this conversion
1788 * also changes the BOM */
1789 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1790 data[0] = (gchar) 0xef;
1791 data[1] = (gchar) 0xbb;
1792 data[2] = (gchar) 0xbf;
1793 sci_get_text(doc->editor->sci, len, data + 3);
1794 len += 3;
1796 else
1798 data = (gchar*) g_malloc(len);
1799 sci_get_text(doc->editor->sci, len, data);
1802 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1803 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1804 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1806 if (! save_convert_to_encoding(doc, &data, &len))
1808 g_free(data);
1809 return FALSE;
1812 else
1814 len = strlen(data);
1817 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1819 /* ignore file changed notification when the file is written */
1820 doc->priv->file_disk_status = FILE_IGNORE;
1822 /* actually write the content of data to the file on disk */
1823 errmsg = write_data_to_disk(doc, locale_filename, data, len);
1824 g_free(data);
1826 if (errmsg != NULL)
1828 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1829 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1830 doc->priv->file_disk_status = FILE_OK;
1831 utils_beep();
1832 g_free(locale_filename);
1833 g_free(errmsg);
1834 return FALSE;
1837 /* store the opened encoding for undo/redo */
1838 store_saved_encoding(doc);
1840 /* ignore the following things if we are quitting */
1841 if (! main_status.quitting)
1843 sci_set_savepoint(doc->editor->sci);
1845 if (file_prefs.disk_check_timeout > 0)
1846 document_update_timestamp(doc, locale_filename);
1848 /* update filetype-related things */
1849 document_set_filetype(doc, doc->file_type);
1851 document_update_tab_label(doc);
1853 msgwin_status_add(_("File %s saved."), doc->file_name);
1854 ui_update_statusbar(doc, -1);
1855 #ifdef HAVE_VTE
1856 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1857 #endif
1859 g_free(locale_filename);
1861 g_signal_emit_by_name(geany_object, "document-save", doc);
1863 return TRUE;
1867 /* special search function, used from the find entry in the toolbar
1868 * return TRUE if text was found otherwise FALSE
1869 * return also TRUE if text is empty */
1870 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc)
1872 gint start_pos, search_pos;
1873 struct Sci_TextToFind ttf;
1875 g_return_val_if_fail(text != NULL, FALSE);
1876 g_return_val_if_fail(doc != NULL, FALSE);
1877 if (! *text)
1878 return TRUE;
1880 start_pos = (inc) ? sci_get_selection_start(doc->editor->sci) :
1881 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1883 /* search cursor to end */
1884 ttf.chrg.cpMin = start_pos;
1885 ttf.chrg.cpMax = sci_get_length(doc->editor->sci);
1886 ttf.lpstrText = (gchar *)text;
1887 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1889 /* if no match, search start to cursor */
1890 if (search_pos == -1)
1892 ttf.chrg.cpMin = 0;
1893 ttf.chrg.cpMax = start_pos + strlen(text);
1894 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1897 if (search_pos != -1)
1899 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1901 /* unfold maybe folded results */
1902 sci_ensure_line_is_visible(doc->editor->sci, line);
1904 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1905 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1907 if (! editor_line_in_view(doc->editor, line))
1908 { /* we need to force scrolling in case the cursor is outside of the current visible area
1909 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1910 * while searching */
1911 editor_scroll_to_line(doc->editor, -1, 0.3F);
1913 else
1914 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1915 return TRUE;
1917 else
1919 if (! inc)
1921 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1923 utils_beep();
1924 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1925 return FALSE;
1930 /* General search function, used from the find dialog.
1931 * Returns -1 on failure or the start position of the matching text.
1932 * Will skip past any selection, ignoring it. */
1933 gint document_find_text(GeanyDocument *doc, const gchar *text, gint flags, gboolean search_backwards,
1934 gboolean scroll, GtkWidget *parent)
1936 gint selection_end, selection_start, search_pos;
1938 g_return_val_if_fail(doc != NULL && text != NULL, -1);
1939 if (! *text)
1940 return -1;
1942 /* Sci doesn't support searching backwards with a regex */
1943 if (flags & SCFIND_REGEXP)
1944 search_backwards = FALSE;
1946 selection_start = sci_get_selection_start(doc->editor->sci);
1947 selection_end = sci_get_selection_end(doc->editor->sci);
1948 if ((selection_end - selection_start) > 0)
1949 { /* there's a selection so go to the end */
1950 if (search_backwards)
1951 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1952 else
1953 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1956 sci_set_search_anchor(doc->editor->sci);
1957 if (search_backwards)
1958 search_pos = sci_search_prev(doc->editor->sci, flags, text);
1959 else
1960 search_pos = search_find_next(doc->editor->sci, text, flags);
1962 if (search_pos != -1)
1964 /* unfold maybe folded results */
1965 sci_ensure_line_is_visible(doc->editor->sci,
1966 sci_get_line_from_position(doc->editor->sci, search_pos));
1967 if (scroll)
1968 doc->editor->scroll_percent = 0.3F;
1970 else
1972 gint sci_len = sci_get_length(doc->editor->sci);
1974 /* if we just searched the whole text, give up searching. */
1975 if ((selection_end == 0 && ! search_backwards) ||
1976 (selection_end == sci_len && search_backwards))
1978 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1979 utils_beep();
1980 return -1;
1983 /* we searched only part of the document, so ask whether to wraparound. */
1984 if (search_prefs.suppress_dialogs ||
1985 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
1986 _("Wrap search and find again?"), _("\"%s\" was not found."), text))
1988 gint ret;
1990 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
1991 ret = document_find_text(doc, text, flags, search_backwards, scroll, parent);
1992 if (ret == -1)
1993 { /* return to original cursor position if not found */
1994 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
1996 return ret;
1999 return search_pos;
2003 /* Replaces the selection if it matches, otherwise just finds the next match.
2004 * Returns: start of replaced text, or -1 if no replacement was made */
2005 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2006 gint flags, gboolean search_backwards)
2008 gint selection_end, selection_start, search_pos;
2010 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
2012 if (! *find_text)
2013 return -1;
2015 /* Sci doesn't support searching backwards with a regex */
2016 if (flags & SCFIND_REGEXP)
2017 search_backwards = FALSE;
2019 selection_start = sci_get_selection_start(doc->editor->sci);
2020 selection_end = sci_get_selection_end(doc->editor->sci);
2021 if (selection_end == selection_start)
2023 /* no selection so just find the next match */
2024 document_find_text(doc, find_text, flags, search_backwards, TRUE, NULL);
2025 return -1;
2027 /* there's a selection so go to the start before finding to search through it
2028 * this ensures there is a match */
2029 if (search_backwards)
2030 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
2031 else
2032 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
2034 search_pos = document_find_text(doc, find_text, flags, search_backwards, TRUE, NULL);
2035 /* return if the original selected text did not match (at the start of the selection) */
2036 if (search_pos != selection_start)
2037 return -1;
2039 if (search_pos != -1)
2041 gint replace_len;
2042 /* search next/prev will select matching text, which we use to set the replace target */
2043 sci_target_from_selection(doc->editor->sci);
2044 replace_len = search_replace_target(doc->editor->sci, replace_text, flags & SCFIND_REGEXP);
2045 /* select the replacement - find text will skip past the selected text */
2046 sci_set_selection_start(doc->editor->sci, search_pos);
2047 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2049 else
2051 /* no match in the selection */
2052 utils_beep();
2054 return search_pos;
2058 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *find_text,
2059 const gchar *replace_text, gboolean escaped_chars)
2061 gchar *escaped_find_text, *escaped_replace_text, *filename;
2063 if (count == 0)
2065 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), find_text);
2066 return;
2069 filename = g_path_get_basename(DOC_FILENAME(doc));
2071 if (escaped_chars)
2072 { /* escape special characters for showing */
2073 escaped_find_text = g_strescape(find_text, NULL);
2074 escaped_replace_text = g_strescape(replace_text, NULL);
2075 ui_set_statusbar(TRUE, ngettext(
2076 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2077 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2078 count), filename, count, escaped_find_text, escaped_replace_text);
2079 g_free(escaped_find_text);
2080 g_free(escaped_replace_text);
2082 else
2084 ui_set_statusbar(TRUE, ngettext(
2085 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2086 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2087 count), filename, count, find_text, replace_text);
2089 g_free(filename);
2093 /* Replace all text matches in a certain range within document.
2094 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2095 * or -1 if no text was found.
2096 * scroll_to_match is whether to scroll the last replacement in view (which also
2097 * clears the selection).
2098 * Returns: the number of replacements made. */
2099 static guint
2100 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2101 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2103 gint count = 0;
2104 struct Sci_TextToFind ttf;
2105 ScintillaObject *sci;
2107 if (new_range_end != NULL)
2108 *new_range_end = -1;
2110 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2112 if (! *find_text || doc->readonly)
2113 return 0;
2115 sci = doc->editor->sci;
2117 ttf.chrg.cpMin = start;
2118 ttf.chrg.cpMax = end;
2119 ttf.lpstrText = (gchar*)find_text;
2121 sci_start_undo_action(sci);
2122 count = search_replace_range(sci, &ttf, flags, replace_text);
2123 sci_end_undo_action(sci);
2125 if (count > 0)
2126 { /* scroll last match in view, will destroy the existing selection */
2127 if (scroll_to_match)
2128 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2130 if (new_range_end != NULL)
2131 *new_range_end = ttf.chrg.cpMax;
2133 return count;
2137 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2138 gint flags, gboolean escaped_chars)
2140 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2141 gint max_column = 0, count = 0;
2142 gboolean replaced = FALSE;
2144 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2146 if (! *find_text)
2147 return;
2149 selection_start = sci_get_selection_start(doc->editor->sci);
2150 selection_end = sci_get_selection_end(doc->editor->sci);
2151 /* do we have a selection? */
2152 if ((selection_end - selection_start) == 0)
2154 utils_beep();
2155 return;
2158 selection_mode = sci_get_selection_mode(doc->editor->sci);
2159 selected_lines = sci_get_lines_selected(doc->editor->sci);
2160 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2161 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2163 gint first_line, line;
2165 sci_start_undo_action(doc->editor->sci);
2167 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2168 /* Find the last line with chars selected (not EOL char) */
2169 last_line = sci_get_line_from_position(doc->editor->sci,
2170 selection_end - editor_get_eol_char_len(doc->editor));
2171 last_line = MAX(first_line, last_line);
2172 for (line = first_line; line < (first_line + selected_lines); line++)
2174 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2175 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2177 /* skip line if there is no selection */
2178 if (line_start != INVALID_POSITION)
2180 /* don't let document_replace_range() scroll to match to keep our selection */
2181 gint new_sel_end;
2183 count += document_replace_range(doc, find_text, replace_text, flags,
2184 line_start, line_end, FALSE, &new_sel_end);
2185 if (new_sel_end != -1)
2187 replaced = TRUE;
2188 /* this gets the greatest column within the selection after replacing */
2189 max_column = MAX(max_column,
2190 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2194 sci_end_undo_action(doc->editor->sci);
2196 else /* handle normal line selection */
2198 count += document_replace_range(doc, find_text, replace_text, flags,
2199 selection_start, selection_end, TRUE, &selection_end);
2200 if (selection_end != -1)
2201 replaced = TRUE;
2204 if (replaced)
2205 { /* update the selection for the new endpoint */
2207 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2209 /* now we can scroll to the selection and destroy it because we rebuild it later */
2210 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2212 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2213 * the highest column on the last line. The wrapped selection is completely different
2214 * from the original one, so skip the selection at all */
2215 /* TODO is there a better way to handle the wrapped selection? */
2216 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2217 { /* for keeping and adjusting the selection in multi line rectangle selection we
2218 * need the last line of the original selection and the greatest column number after
2219 * replacing and set the selection end to the last line at the greatest column */
2220 sci_set_selection_start(doc->editor->sci, selection_start);
2221 sci_set_selection_end(doc->editor->sci,
2222 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2223 sci_set_selection_mode(doc->editor->sci, selection_mode);
2226 else
2228 sci_set_selection_start(doc->editor->sci, selection_start);
2229 sci_set_selection_end(doc->editor->sci, selection_end);
2232 else /* no replacements */
2233 utils_beep();
2235 show_replace_summary(doc, count, find_text, replace_text, escaped_chars);
2239 /* returns number of replacements made. */
2240 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2241 gint flags, gboolean escaped_chars)
2243 gint len, count;
2244 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2246 if (! *find_text)
2247 return FALSE;
2249 len = sci_get_length(doc->editor->sci);
2250 count = document_replace_range(
2251 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2253 show_replace_summary(doc, count, find_text, replace_text, escaped_chars);
2254 return count;
2258 static gboolean update_tags_from_buffer(GeanyDocument *doc)
2260 gboolean result;
2261 #if 1
2262 /* old code */
2263 result = tm_source_file_update(doc->tm_file, TRUE, FALSE, TRUE);
2264 #else
2265 gsize len = sci_get_length(doc->editor->sci) + 1;
2266 gchar *text = g_malloc(len);
2268 /* we copy the whole text into memory instead using a direct char pointer from
2269 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2270 sci_get_text(doc->editor->sci, len, text);
2271 result = tm_source_file_buffer_update(doc->tm_file, (guchar*) text, len, TRUE);
2272 g_free(text);
2273 #endif
2274 return result;
2278 void document_update_tag_list(GeanyDocument *doc, gboolean update)
2280 /* We must call sidebar_update_tag_list() before returning,
2281 * to ensure that the symbol list is always updated properly (e.g.
2282 * when creating a new document with a partial filename set. */
2283 gboolean success = FALSE;
2285 /* if the filetype doesn't have a tag parser or it is a new file */
2286 if (doc == NULL || doc->file_type == NULL || app->tm_workspace == NULL ||
2287 ! filetype_has_tags(doc->file_type) || ! doc->file_name)
2289 /* set the default (empty) tag list */
2290 sidebar_update_tag_list(doc, FALSE);
2291 return;
2294 if (doc->tm_file == NULL)
2296 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2297 const gchar *name;
2299 /* lookup the name rather than using filetype name to support custom filetypes */
2300 name = tm_source_file_get_lang_name(doc->file_type->lang);
2301 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2302 g_free(locale_filename);
2304 if (doc->tm_file)
2306 if (!tm_workspace_add_object(doc->tm_file))
2308 tm_work_object_free(doc->tm_file);
2309 doc->tm_file = NULL;
2311 else
2313 if (update)
2314 update_tags_from_buffer(doc);
2315 success = TRUE;
2319 else
2321 success = update_tags_from_buffer(doc);
2322 if (G_UNLIKELY(! success))
2323 geany_debug("tag list updating failed");
2325 sidebar_update_tag_list(doc, success);
2329 /* Caches the list of project typenames, as a space separated GString.
2330 * Returns: TRUE if typenames have changed.
2331 * (*types) is set to the list of typenames, or NULL if there are none. */
2332 static gboolean get_project_typenames(const GString **types, gint lang)
2334 static GString *last_typenames = NULL;
2335 GString *s = NULL;
2337 if (app->tm_workspace)
2339 GPtrArray *tags_array = app->tm_workspace->work_object.tags_array;
2341 if (tags_array)
2343 s = symbols_find_tags_as_string(tags_array, TM_GLOBAL_TYPE_MASK, lang);
2347 if (s && last_typenames && g_string_equal(s, last_typenames))
2349 g_string_free(s, TRUE);
2350 *types = last_typenames;
2351 return FALSE; /* project typenames haven't changed */
2353 /* cache typename list for next time */
2354 if (last_typenames)
2355 g_string_free(last_typenames, TRUE);
2356 last_typenames = s;
2358 *types = s;
2359 if (s == NULL)
2360 return FALSE;
2361 return TRUE;
2365 /* If sci is NULL, update project typenames for all documents that support typenames,
2366 * if typenames have changed.
2367 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2368 * if necessary, and typename keywords are set for sci.
2369 * Returns: TRUE if any scintilla type keywords were updated. */
2370 static gboolean update_type_keywords(GeanyDocument *doc, gint lang)
2372 gboolean ret = FALSE;
2373 guint n;
2374 const GString *s;
2375 ScintillaObject *sci;
2377 g_return_val_if_fail(doc != NULL, FALSE);
2378 sci = doc->editor->sci;
2380 switch (FILETYPE_ID(doc->file_type))
2381 { /* continue working with the following languages, skip on all others */
2382 case GEANY_FILETYPES_C:
2383 case GEANY_FILETYPES_CPP:
2384 case GEANY_FILETYPES_CS:
2385 case GEANY_FILETYPES_D:
2386 case GEANY_FILETYPES_JAVA:
2387 case GEANY_FILETYPES_VALA:
2388 break;
2389 default:
2390 return FALSE;
2393 sci = doc->editor->sci;
2394 if (sci != NULL && editor_lexer_get_type_keyword_idx(sci_get_lexer(sci)) == -1)
2395 return FALSE;
2397 if (! get_project_typenames(&s, lang))
2398 { /* typenames have not changed */
2399 if (s != NULL && sci != NULL)
2401 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(sci));
2403 sci_set_keywords(sci, keyword_idx, s->str);
2404 queue_colourise(doc);
2406 return FALSE;
2408 g_return_val_if_fail(s != NULL, FALSE);
2410 for (n = 0; n < documents_array->len; n++)
2412 if (documents[n]->is_valid)
2414 ScintillaObject *wid = documents[n]->editor->sci;
2415 gint keyword_idx = editor_lexer_get_type_keyword_idx(sci_get_lexer(wid));
2417 if (keyword_idx > 0)
2419 sci_set_keywords(wid, keyword_idx, s->str);
2420 queue_colourise(documents[n]);
2421 ret = TRUE;
2425 return ret;
2429 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2430 gboolean filetype_changed)
2432 g_return_if_fail(doc);
2433 if (type == NULL)
2434 type = filetypes[GEANY_FILETYPES_NONE];
2436 if (filetype_changed)
2438 doc->file_type = type;
2440 /* delete tm file object to force creation of a new one */
2441 if (doc->tm_file != NULL)
2443 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2444 doc->tm_file = NULL;
2446 /* load tags files before highlighting (some lexers highlight global typenames) */
2447 if (type->id != GEANY_FILETYPES_NONE)
2448 symbols_global_tags_loaded(type->id);
2450 highlighting_set_styles(doc->editor->sci, type);
2451 editor_set_indentation_guides(doc->editor);
2452 build_menu_update(doc);
2453 queue_colourise(doc);
2456 document_update_tag_list(doc, TRUE);
2458 /* Update session typename keywords. */
2459 update_type_keywords(doc, type->lang);
2463 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2464 * @param doc The document to use.
2465 * @param type The filetype. */
2466 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2468 gboolean ft_changed;
2469 GeanyFiletype *old_ft;
2471 g_return_if_fail(doc);
2472 if (type == NULL)
2473 type = filetypes[GEANY_FILETYPES_NONE];
2475 old_ft = doc->file_type;
2476 geany_debug("%s : %s (%s)",
2477 (doc->file_name != NULL) ? doc->file_name : "unknown",
2478 (type->name != NULL) ? type->name : "unknown",
2479 (doc->encoding != NULL) ? doc->encoding : "unknown");
2481 ft_changed = (doc->file_type != type); /* filetype has changed */
2482 document_load_config(doc, type, ft_changed);
2484 if (ft_changed)
2485 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2489 void document_reload_config(GeanyDocument *doc)
2491 document_load_config(doc, doc->file_type, TRUE);
2496 * Sets the encoding of a document.
2497 * This function only set the encoding of the %document, it does not any conversions. The new
2498 * encoding is used when e.g. saving the file.
2500 * @param doc The document to use.
2501 * @param new_encoding The encoding to be set for the document.
2503 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2505 if (doc == NULL || new_encoding == NULL ||
2506 utils_str_equal(new_encoding, doc->encoding))
2507 return;
2509 g_free(doc->encoding);
2510 doc->encoding = g_strdup(new_encoding);
2512 ui_update_statusbar(doc, -1);
2513 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2514 encodings_is_unicode_charset(doc->encoding));
2518 /* own Undo / Redo implementation to be able to undo / redo changes
2519 * to the encoding or the Unicode BOM (which are Scintilla independet).
2520 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2522 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2523 void document_undo_clear(GeanyDocument *doc)
2525 undo_action *a;
2527 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2529 a = g_trash_stack_pop(&doc->priv->undo_actions);
2530 if (G_LIKELY(a != NULL))
2532 switch (a->type)
2534 case UNDO_ENCODING: g_free(a->data); break;
2535 default: break;
2537 g_free(a);
2540 doc->priv->undo_actions = NULL;
2542 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2544 a = g_trash_stack_pop(&doc->priv->redo_actions);
2545 if (G_LIKELY(a != NULL))
2547 switch (a->type)
2549 case UNDO_ENCODING: g_free(a->data); break;
2550 default: break;
2552 g_free(a);
2555 doc->priv->redo_actions = NULL;
2557 if (! main_status.quitting && doc->editor != NULL)
2558 document_set_text_changed(doc, FALSE);
2562 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2564 undo_action *action;
2566 g_return_if_fail(doc != NULL);
2568 action = g_new0(undo_action, 1);
2569 action->type = type;
2570 action->data = data;
2572 g_trash_stack_push(&doc->priv->undo_actions, action);
2574 document_set_text_changed(doc, TRUE);
2575 ui_update_popup_reundo_items(doc);
2579 gboolean document_can_undo(GeanyDocument *doc)
2581 g_return_val_if_fail(doc != NULL, FALSE);
2583 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2584 return TRUE;
2585 else
2586 return FALSE;
2590 static void update_changed_state(GeanyDocument *doc)
2592 doc->changed =
2593 (sci_is_modified(doc->editor->sci) ||
2594 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2595 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2596 document_set_text_changed(doc, doc->changed);
2600 void document_undo(GeanyDocument *doc)
2602 undo_action *action;
2604 g_return_if_fail(doc != NULL);
2606 action = g_trash_stack_pop(&doc->priv->undo_actions);
2608 if (G_UNLIKELY(action == NULL))
2610 /* fallback, should not be necessary */
2611 geany_debug("%s: fallback used", G_STRFUNC);
2612 sci_undo(doc->editor->sci);
2614 else
2616 switch (action->type)
2618 case UNDO_SCINTILLA:
2620 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2622 sci_undo(doc->editor->sci);
2623 break;
2625 case UNDO_BOM:
2627 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2629 doc->has_bom = GPOINTER_TO_INT(action->data);
2630 ui_update_statusbar(doc, -1);
2631 ui_document_show_hide(doc);
2632 break;
2634 case UNDO_ENCODING:
2636 /* use the "old" encoding */
2637 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2639 document_set_encoding(doc, (const gchar*)action->data);
2641 ignore_callback = TRUE;
2642 encodings_select_radio_item((const gchar*)action->data);
2643 ignore_callback = FALSE;
2645 g_free(action->data);
2646 break;
2648 default: break;
2651 g_free(action); /* free the action which was taken from the stack */
2653 update_changed_state(doc);
2654 ui_update_popup_reundo_items(doc);
2658 gboolean document_can_redo(GeanyDocument *doc)
2660 g_return_val_if_fail(doc != NULL, FALSE);
2662 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2663 return TRUE;
2664 else
2665 return FALSE;
2669 void document_redo(GeanyDocument *doc)
2671 undo_action *action;
2673 g_return_if_fail(doc != NULL);
2675 action = g_trash_stack_pop(&doc->priv->redo_actions);
2677 if (G_UNLIKELY(action == NULL))
2679 /* fallback, should not be necessary */
2680 geany_debug("%s: fallback used", G_STRFUNC);
2681 sci_redo(doc->editor->sci);
2683 else
2685 switch (action->type)
2687 case UNDO_SCINTILLA:
2689 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2691 sci_redo(doc->editor->sci);
2692 break;
2694 case UNDO_BOM:
2696 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2698 doc->has_bom = GPOINTER_TO_INT(action->data);
2699 ui_update_statusbar(doc, -1);
2700 ui_document_show_hide(doc);
2701 break;
2703 case UNDO_ENCODING:
2705 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2707 document_set_encoding(doc, (const gchar*)action->data);
2709 ignore_callback = TRUE;
2710 encodings_select_radio_item((const gchar*)action->data);
2711 ignore_callback = FALSE;
2713 g_free(action->data);
2714 break;
2716 default: break;
2719 g_free(action); /* free the action which was taken from the stack */
2721 update_changed_state(doc);
2722 ui_update_popup_reundo_items(doc);
2726 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2728 undo_action *action;
2730 g_return_if_fail(doc != NULL);
2732 action = g_new0(undo_action, 1);
2733 action->type = type;
2734 action->data = data;
2736 g_trash_stack_push(&doc->priv->redo_actions, action);
2738 document_set_text_changed(doc, TRUE);
2739 ui_update_popup_reundo_items(doc);
2744 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2745 * Returned colors are red if the document has changes, green if the document is read-only
2746 * or simply @c NULL if the document is unmodified but writable.
2748 * @param doc The document to use.
2750 * @return The color for the document or @c NULL if the default color should be used. The color
2751 * object is owned by Geany and should not be modified or freed.
2753 * @since 0.16
2755 const GdkColor *document_get_status_color(GeanyDocument *doc)
2757 static GdkColor red = {0, 0xFFFF, 0, 0};
2758 static GdkColor green = {0, 0, 0x7FFF, 0};
2759 #if USE_GIO_FILEMON
2760 static GdkColor orange = {0, 0xFFFF, 0x7FFF, 0};
2761 #endif
2762 GdkColor *color = NULL;
2764 g_return_val_if_fail(doc != NULL, NULL);
2766 if (doc->changed)
2767 color = &red;
2768 #if USE_GIO_FILEMON
2769 else if (doc->priv->file_disk_status == FILE_CHANGED)
2770 color = &orange;
2771 #endif
2772 else if (doc->readonly)
2773 color = &green;
2775 return color; /* return pointer to static GdkColor. */
2779 /** Accessor function for @ref GeanyData::documents_array items.
2780 * @warning Always check the returned document is valid (@c doc->is_valid).
2781 * @param idx @c documents_array index.
2782 * @return The document, or @c NULL if @a idx is out of range.
2784 * @since 0.16
2786 GeanyDocument *document_index(gint idx)
2788 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2792 /* create a new file and copy file content and properties */
2793 GeanyDocument *document_clone(GeanyDocument *old_doc, const gchar *utf8_filename)
2795 gint len;
2796 gchar *text;
2797 GeanyDocument *doc;
2799 g_return_val_if_fail(old_doc != NULL, NULL);
2801 len = sci_get_length(old_doc->editor->sci) + 1;
2802 text = (gchar*) g_malloc(len);
2803 sci_get_text(old_doc->editor->sci, len, text);
2804 /* use old file type (or maybe NULL for auto detect would be better?) */
2805 doc = document_new_file(utf8_filename, old_doc->file_type, text);
2806 g_free(text);
2808 /* copy file properties */
2809 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2810 doc->readonly = old_doc->readonly;
2811 doc->has_bom = old_doc->has_bom;
2812 document_set_encoding(doc, old_doc->encoding);
2813 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2814 sci_set_readonly(doc->editor->sci, doc->readonly);
2816 ui_document_show_hide(doc);
2817 return doc;
2821 /* @note If successful, this should always be followed up with a call to
2822 * document_close_all().
2823 * @return TRUE if all files were saved or had their changes discarded. */
2824 gboolean document_account_for_unsaved(void)
2826 guint i, p, page_count, len = documents_array->len;
2827 GeanyDocument *doc;
2829 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2830 for (p = 0; p < page_count; p++)
2832 doc = document_get_from_page(p);
2833 if (doc->changed)
2835 if (! dialogs_show_unsaved_file(doc))
2836 return FALSE;
2839 /* all documents should now be accounted for, so ignore any changes */
2840 for (i = 0; i < len; i++)
2842 doc = documents[i];
2843 if (doc->is_valid && doc->changed)
2845 doc->changed = FALSE;
2848 return TRUE;
2852 static void force_close_all(void)
2854 guint i, len = documents_array->len;
2856 /* check all documents have been accounted for */
2857 for (i = 0; i < len; i++)
2859 if (documents[i]->is_valid)
2861 g_return_if_fail(!documents[i]->changed);
2864 main_status.closing_all = TRUE;
2866 while (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) > 0)
2868 document_remove_page(0);
2871 main_status.closing_all = FALSE;
2875 gboolean document_close_all(void)
2877 if (! document_account_for_unsaved())
2878 return FALSE;
2880 force_close_all();
2882 return TRUE;
2886 static gboolean monitor_reload_file(GeanyDocument *doc)
2888 gchar *base_name = g_path_get_basename(doc->file_name);
2889 gboolean want_reload;
2891 want_reload = dialogs_show_question_full(NULL, _("_Reload"), GTK_STOCK_CANCEL,
2892 _("Do you want to reload it?"),
2893 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2894 base_name);
2896 if (want_reload)
2897 document_reload_file(doc, doc->encoding);
2899 g_free(base_name);
2900 return want_reload;
2904 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2906 gboolean want_reload = FALSE;
2907 gboolean file_saved = FALSE;
2908 gint ret;
2910 ret = dialogs_show_prompt(NULL,
2911 _("Close _without saving"), GTK_RESPONSE_CLOSE,
2912 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2913 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
2914 NULL,
2915 _("File \"%s\" was not found on disk! Try to resave the file?"),
2916 doc->file_name);
2917 if (ret == GTK_RESPONSE_ACCEPT)
2919 file_saved = dialogs_show_save_as();
2920 want_reload = TRUE;
2922 else if (ret == GTK_RESPONSE_CLOSE)
2924 document_close(doc);
2926 if (ret != GTK_RESPONSE_CLOSE && ! file_saved)
2928 /* file is missing - set unsaved state */
2929 document_set_text_changed(doc, TRUE);
2930 /* don't prompt more than once */
2931 setptr(doc->real_path, NULL);
2934 return want_reload;
2938 /* Set force to force a disk check, otherwise it is ignored if there was a check
2939 * in the last file_prefs.disk_check_timeout seconds.
2940 * @return @c TRUE if the file has changed. */
2941 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
2943 gboolean ret = FALSE;
2944 gboolean use_gio_filemon;
2945 time_t cur_time = 0;
2946 struct stat st;
2947 gchar *locale_filename;
2948 FileDiskStatus old_status;
2950 g_return_val_if_fail(doc != NULL, FALSE);
2952 /* ignore remote files and documents that have never been saved to disk */
2953 if (file_prefs.disk_check_timeout == 0 || doc->real_path == NULL || doc->priv->is_remote)
2954 return FALSE;
2956 use_gio_filemon = (doc->priv->monitor != NULL);
2958 if (use_gio_filemon)
2960 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
2961 return FALSE;
2963 else
2965 cur_time = time(NULL);
2966 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
2967 return FALSE;
2969 doc->priv->last_check = cur_time;
2972 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2973 if (g_stat(locale_filename, &st) != 0)
2975 monitor_resave_missing_file(doc);
2976 ret = TRUE;
2978 else if (! use_gio_filemon && /* ignore these checks when using GIO */
2979 (G_UNLIKELY(doc->priv->mtime > cur_time) || G_UNLIKELY(st.st_mtime > cur_time)))
2981 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
2983 else if (doc->priv->mtime < st.st_mtime)
2985 monitor_reload_file(doc);
2986 doc->priv->mtime = st.st_mtime;
2987 ret = TRUE;
2989 g_free(locale_filename);
2991 if (DOC_VALID(doc))
2992 { /* doc can get invalid when a document was closed by monitor_resave_missing_file() */
2993 old_status = doc->priv->file_disk_status;
2994 doc->priv->file_disk_status = FILE_OK;
2995 if (old_status != doc->priv->file_disk_status)
2996 ui_update_tab_status(doc);
2998 return ret;