Queue colourise of the Scintilla widget after (re)setting type keywords
[geany-mirror.git] / src / document.c
blobe46718410d8838fe558f3f6c37db02fb7bf7409f
1 /*
2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2011 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2011 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * Document related actions: new, save, open, etc.
24 * Also Scintilla search actions.
27 #include "geany.h"
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #include <time.h>
34 #include <unistd.h>
35 #include <string.h>
36 #include <errno.h>
38 #ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
40 #endif
42 #include <stdlib.h>
44 /* gstdio.h also includes sys/stat.h */
45 #include <glib/gstdio.h>
47 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
48 /*#define USE_GIO_FILEMON 1*/
49 #include <gio/gio.h>
51 #include "document.h"
52 #include "documentprivate.h"
53 #include "filetypes.h"
54 #include "support.h"
55 #include "sciwrappers.h"
56 #include "editor.h"
57 #include "dialogs.h"
58 #include "msgwindow.h"
59 #include "templates.h"
60 #include "sidebar.h"
61 #include "ui_utils.h"
62 #include "utils.h"
63 #include "encodings.h"
64 #include "notebook.h"
65 #include "main.h"
66 #include "vte.h"
67 #include "build.h"
68 #include "symbols.h"
69 #include "highlighting.h"
70 #include "navqueue.h"
71 #include "win32.h"
72 #include "search.h"
73 #include "filetypesprivate.h"
75 #include "SciLexer.h"
78 GeanyFilePrefs file_prefs;
80 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
81 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
82 * to a document over time, but it might no longer represent a notebook tab. To check this,
83 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
84 * file by then.
86 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
87 * although usually you would just use the foreach_document() macro.
89 * Never assume that the order of document pointers is the same as the order of notebook tabs.
90 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
91 GPtrArray *documents_array = NULL;
94 /* an undo action, also used for redo actions */
95 typedef struct
97 GTrashStack *next; /* pointer to the next stack element(required for the GTrashStack) */
98 guint type; /* to identify the action */
99 gpointer *data; /* the old value (before the change), in case of a redo action
100 * it contains the new value */
101 } undo_action;
104 static void document_undo_clear(GeanyDocument *doc);
105 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data);
106 static gboolean remove_page(guint page_num);
110 * Finds a document whose @c real_path field matches the given filename.
112 * @param realname The filename to search, which should be identical to the
113 * string returned by @c tm_get_real_path().
115 * @return The matching document, or @c NULL.
116 * @note This is only really useful when passing a @c TMWorkObject::file_name.
117 * @see GeanyDocument::real_path.
118 * @see document_find_by_filename().
120 * @since 0.15
122 GeanyDocument* document_find_by_real_path(const gchar *realname)
124 guint i;
126 if (! realname)
127 return NULL; /* file doesn't exist on disk */
129 for (i = 0; i < documents_array->len; i++)
131 GeanyDocument *doc = documents[i];
133 if (! doc->is_valid || ! doc->real_path)
134 continue;
136 if (utils_filenamecmp(realname, doc->real_path) == 0)
138 return doc;
141 return NULL;
145 /* dereference symlinks, /../ junk in path and return locale encoding */
146 static gchar *get_real_path_from_utf8(const gchar *utf8_filename)
148 gchar *locale_name = utils_get_locale_from_utf8(utf8_filename);
149 gchar *realname = tm_get_real_path(locale_name);
151 g_free(locale_name);
152 return realname;
157 * Finds a document with the given filename.
158 * This matches either an exact GeanyDocument::file_name string, or variant
159 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
160 * match @c "/name").
162 * @param utf8_filename The filename to search (in UTF-8 encoding).
164 * @return The matching document, or @c NULL.
165 * @see document_find_by_real_path().
167 GeanyDocument *document_find_by_filename(const gchar *utf8_filename)
169 guint i;
170 GeanyDocument *doc;
171 gchar *realname;
173 g_return_val_if_fail(utf8_filename != NULL, NULL);
175 /* First search GeanyDocument::file_name, so we can find documents with a
176 * filename set but not saved on disk, like vcdiff produces */
177 for (i = 0; i < documents_array->len; i++)
179 doc = documents[i];
181 if (! doc->is_valid || doc->file_name == NULL)
182 continue;
184 if (utils_filenamecmp(utf8_filename, doc->file_name) == 0)
186 return doc;
189 /* Now try matching based on the realpath(), which is unique per file on disk */
190 realname = get_real_path_from_utf8(utf8_filename);
191 doc = document_find_by_real_path(realname);
192 g_free(realname);
193 return doc;
197 /* returns the document which has sci, or NULL. */
198 GeanyDocument *document_find_by_sci(ScintillaObject *sci)
200 guint i;
202 g_return_val_if_fail(sci != NULL, NULL);
204 for (i = 0; i < documents_array->len; i++)
206 if (documents[i]->is_valid && documents[i]->editor->sci == sci)
207 return documents[i];
209 return NULL;
213 /** Gets the notebook page index for a document.
214 * @param doc The document.
215 * @return The index.
216 * @since 0.19 */
217 gint document_get_notebook_page(GeanyDocument *doc)
219 g_return_val_if_fail(doc != NULL, -1);
221 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets.notebook),
222 GTK_WIDGET(doc->editor->sci));
227 * Finds the document for the given notebook page @a page_num.
229 * @param page_num The notebook page number to search.
231 * @return The corresponding document for the given notebook page, or @c NULL.
233 GeanyDocument *document_get_from_page(guint page_num)
235 ScintillaObject *sci;
237 if (page_num >= documents_array->len)
238 return NULL;
240 sci = (ScintillaObject*)gtk_notebook_get_nth_page(
241 GTK_NOTEBOOK(main_widgets.notebook), page_num);
243 return document_find_by_sci(sci);
248 * Finds the current document.
250 * @return A pointer to the current document or @c NULL if there are no opened documents.
252 GeanyDocument *document_get_current(void)
254 gint cur_page = gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets.notebook));
256 if (cur_page == -1)
257 return NULL;
258 else
260 ScintillaObject *sci = (ScintillaObject*)
261 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets.notebook), cur_page);
263 return document_find_by_sci(sci);
268 void document_init_doclist()
270 documents_array = g_ptr_array_new();
274 void document_finalize()
276 guint i;
278 for (i = 0; i < documents_array->len; i++)
279 g_free(documents[i]);
280 g_ptr_array_free(documents_array, TRUE);
285 * Returns the last part of the filename of the given GeanyDocument. The result is also
286 * truncated to a maximum of @a length characters in case the filename is very long.
288 * @param doc The document to use.
289 * @param length The length of the resulting string or -1 to use a default value.
291 * @return The ellipsized last part of the filename of @a doc, should be freed when no
292 * longer needed.
294 * @since 0.17
296 /* TODO make more use of this */
297 gchar *document_get_basename_for_display(GeanyDocument *doc, gint length)
299 gchar *base_name, *short_name;
301 g_return_val_if_fail(doc != NULL, NULL);
303 if (length < 0)
304 length = 30;
306 base_name = g_path_get_basename(DOC_FILENAME(doc));
307 short_name = utils_str_middle_truncate(base_name, (guint)length);
309 g_free(base_name);
311 return short_name;
315 void document_update_tab_label(GeanyDocument *doc)
317 gchar *short_name;
318 GtkWidget *parent;
320 g_return_if_fail(doc != NULL);
322 short_name = document_get_basename_for_display(doc, -1);
324 /* we need to use the event box for the tooltip, labels don't get the necessary events */
325 parent = gtk_widget_get_parent(doc->priv->tab_label);
326 parent = gtk_widget_get_parent(parent);
328 gtk_label_set_text(GTK_LABEL(doc->priv->tab_label), short_name);
330 gtk_widget_set_tooltip_text(parent, DOC_FILENAME(doc));
332 g_free(short_name);
337 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
338 * according to the document's save state.
339 * This is called by Geany mostly when opening or saving files.
341 * @param doc The document to use.
342 * @param changed Whether the document state should indicate changes have been made.
344 void document_set_text_changed(GeanyDocument *doc, gboolean changed)
346 g_return_if_fail(doc != NULL);
348 doc->changed = changed;
350 if (! main_status.quitting)
352 ui_update_tab_status(doc);
353 ui_save_buttons_toggle(changed);
354 ui_set_window_title(doc);
355 ui_update_statusbar(doc, -1);
360 /* returns the next free place in the document list,
361 * or -1 if the documents_array is full */
362 static gint document_get_new_idx(void)
364 guint i;
366 for (i = 0; i < documents_array->len; i++)
368 if (documents[i]->editor == NULL)
370 return (gint) i;
373 return -1;
377 static void queue_colourise(GeanyDocument *doc)
379 /* Colourise the editor before it is next drawn */
380 doc->priv->colourise_needed = TRUE;
382 /* If the editor doesn't need drawing (e.g. after saving the current
383 * document), we need to force a redraw, so the expose event is triggered.
384 * This ensures we don't start colourising before all documents are opened/saved,
385 * only once the editor is drawn. */
386 gtk_widget_queue_draw(GTK_WIDGET(doc->editor->sci));
390 #ifdef USE_GIO_FILEMON
391 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor *monitor, G_GNUC_UNUSED GFile *file,
392 G_GNUC_UNUSED GFile *other_file, GFileMonitorEvent event,
393 GeanyDocument *doc)
395 g_return_if_fail(doc != NULL);
397 if (file_prefs.disk_check_timeout == 0)
398 return;
400 geany_debug("%s: event: %d previous file status: %d",
401 G_STRFUNC, event, doc->priv->file_disk_status);
402 switch (event)
404 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT:
406 if (doc->priv->file_disk_status == FILE_IGNORE)
407 doc->priv->file_disk_status = FILE_OK;
408 else
409 doc->priv->file_disk_status = FILE_CHANGED;
410 g_message("%s: FILE_CHANGED", G_STRFUNC);
411 break;
413 case G_FILE_MONITOR_EVENT_DELETED:
415 doc->priv->file_disk_status = FILE_CHANGED;
416 g_message("%s: FILE_MISSING", G_STRFUNC);
417 break;
419 default:
420 break;
422 if (doc->priv->file_disk_status != FILE_OK)
424 ui_update_tab_status(doc);
427 #endif
430 static void document_stop_file_monitoring(GeanyDocument *doc)
432 g_return_if_fail(doc != NULL);
434 if (doc->priv->monitor != NULL)
436 g_object_unref(doc->priv->monitor);
437 doc->priv->monitor = NULL;
442 static void monitor_file_setup(GeanyDocument *doc)
444 g_return_if_fail(doc != NULL);
445 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
446 * doesn't work at all for remote files and legacy polling is too slow. */
447 if (! doc->priv->is_remote)
449 #ifdef USE_GIO_FILEMON
450 gchar *locale_filename;
452 /* stop any previous monitoring */
453 document_stop_file_monitoring(doc);
455 locale_filename = utils_get_locale_from_utf8(doc->file_name);
456 if (locale_filename != NULL && g_file_test(locale_filename, G_FILE_TEST_EXISTS))
458 /* get a file monitor and connect to the 'changed' signal */
459 GFile *file = g_file_new_for_path(locale_filename);
460 doc->priv->monitor = g_file_monitor_file(file, G_FILE_MONITOR_NONE, NULL, NULL);
461 g_signal_connect(doc->priv->monitor, "changed",
462 G_CALLBACK(monitor_file_changed_cb), doc);
464 /* we set the rate limit according to the GUI pref but it's most probably not used */
465 g_file_monitor_set_rate_limit(doc->priv->monitor, file_prefs.disk_check_timeout * 1000);
467 g_object_unref(file);
469 g_free(locale_filename);
470 #endif
472 doc->priv->file_disk_status = FILE_OK;
476 void document_try_focus(GeanyDocument *doc, GtkWidget *source_widget)
478 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
479 if (DOC_VALID(doc))
481 GtkWidget *sci = GTK_WIDGET(doc->editor->sci);
482 GtkWidget *focusw = gtk_window_get_focus(GTK_WINDOW(main_widgets.window));
484 if (source_widget == NULL)
485 source_widget = doc->priv->tag_tree;
487 if (focusw == source_widget)
488 gtk_widget_grab_focus(sci);
493 static gboolean on_idle_focus(gpointer doc)
495 document_try_focus(doc, NULL);
496 return FALSE;
500 /* Creates a new document and editor, adding a tab in the notebook.
501 * @return The created document */
502 static GeanyDocument *document_create(const gchar *utf8_filename)
504 GeanyDocument *doc;
505 gint new_idx;
506 gint cur_pages = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
508 if (cur_pages == 1)
510 doc = document_get_current();
511 /* remove the empty document first */
512 if (doc != NULL && doc->file_name == NULL && ! doc->changed)
513 /* prevent immediately opening another new doc with
514 * new_document_after_close pref */
515 remove_page(0);
518 new_idx = document_get_new_idx();
519 if (new_idx == -1) /* expand the array, no free places */
521 doc = g_new0(GeanyDocument, 1);
523 new_idx = documents_array->len;
524 g_ptr_array_add(documents_array, doc);
527 doc = documents[new_idx];
529 /* initialize default document settings */
530 doc->priv = g_new0(GeanyDocumentPrivate, 1);
531 doc->index = new_idx;
532 doc->file_name = g_strdup(utf8_filename);
533 doc->editor = editor_create(doc);
534 #ifndef USE_GIO_FILEMON
535 doc->priv->last_check = time(NULL);
536 #endif
538 sidebar_openfiles_add(doc); /* sets doc->iter */
540 notebook_new_tab(doc);
542 /* select document in sidebar */
544 GtkTreeSelection *sel;
546 sel = gtk_tree_view_get_selection(GTK_TREE_VIEW(tv.tree_openfiles));
547 gtk_tree_selection_select_iter(sel, &doc->priv->iter);
550 ui_document_buttons_update();
552 doc->is_valid = TRUE; /* do this last to prevent UI updating with NULL items. */
553 return doc;
558 * Closes the given document.
560 * @param doc The document to remove.
562 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
564 * @since 0.15
566 gboolean document_close(GeanyDocument *doc)
568 g_return_val_if_fail(doc, FALSE);
570 return document_remove_page(document_get_notebook_page(doc));
574 /* Call document_remove_page() instead, this is only needed for document_create()
575 * to prevent re-opening a new document when the last document is closed (if enabled). */
576 static gboolean remove_page(guint page_num)
578 GeanyDocument *doc = document_get_from_page(page_num);
580 g_return_val_if_fail(doc != NULL, FALSE);
582 if (doc->changed && ! dialogs_show_unsaved_file(doc))
583 return FALSE;
585 /* tell any plugins that the document is about to be closed */
586 g_signal_emit_by_name(geany_object, "document-close", doc);
588 /* Checking real_path makes it likely the file exists on disk */
589 if (! main_status.closing_all && doc->real_path != NULL)
590 ui_add_recent_document(doc);
592 doc->is_valid = FALSE;
594 if (! main_status.quitting)
596 notebook_remove_page(page_num);
597 sidebar_remove_document(doc);
598 navqueue_remove_file(doc->file_name);
599 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc));
601 g_free(doc->encoding);
602 g_free(doc->priv->saved_encoding.encoding);
603 g_free(doc->file_name);
604 g_free(doc->real_path);
605 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
607 editor_destroy(doc->editor);
608 doc->editor = NULL; /* needs to be NULL for document_undo_clear() call below */
610 document_stop_file_monitoring(doc);
612 document_undo_clear(doc);
614 g_free(doc->priv);
616 /* reset document settings to defaults for re-use */
617 memset(doc, 0, sizeof(GeanyDocument));
619 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
621 sidebar_update_tag_list(NULL, FALSE);
622 ui_set_window_title(NULL);
623 ui_save_buttons_toggle(FALSE);
624 ui_update_popup_reundo_items(NULL);
625 ui_document_buttons_update();
626 build_menu_update(NULL);
628 return TRUE;
633 * Removes the given notebook tab at @a page_num and clears all related information
634 * in the document list.
636 * @param page_num The notebook page number to remove.
638 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
640 gboolean document_remove_page(guint page_num)
642 gboolean done = remove_page(page_num);
644 if (done && ui_prefs.new_document_after_close)
645 document_new_file_if_non_open();
647 return done;
651 /* used to keep a record of the unchanged document state encoding */
652 static void store_saved_encoding(GeanyDocument *doc)
654 g_free(doc->priv->saved_encoding.encoding);
655 doc->priv->saved_encoding.encoding = g_strdup(doc->encoding);
656 doc->priv->saved_encoding.has_bom = doc->has_bom;
660 /* Opens a new empty document only if there are no other documents open */
661 GeanyDocument *document_new_file_if_non_open(void)
663 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)) == 0)
664 return document_new_file(NULL, NULL, NULL);
666 return NULL;
671 * Creates a new document.
672 * Line endings in @a text will be converted to the default setting.
673 * Afterwards, the @c "document-new" signal is emitted for plugins.
675 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
676 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
677 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
679 * @return The new document.
681 GeanyDocument *document_new_file(const gchar *utf8_filename, GeanyFiletype *ft, const gchar *text)
683 GeanyDocument *doc;
685 if (utf8_filename && g_path_is_absolute(utf8_filename))
687 gchar *tmp;
688 tmp = utils_strdupa(utf8_filename); /* work around const */
689 utils_tidy_path(tmp);
690 utf8_filename = tmp;
692 doc = document_create(utf8_filename);
694 g_assert(doc != NULL);
696 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
697 if (text)
699 GString *template = g_string_new(text);
700 utils_ensure_same_eol_characters(template, file_prefs.default_eol_character);
702 sci_set_text(doc->editor->sci, template->str);
703 g_string_free(template, TRUE);
705 else
706 sci_clear_all(doc->editor->sci);
708 sci_set_eol_mode(doc->editor->sci, file_prefs.default_eol_character);
710 sci_set_undo_collection(doc->editor->sci, TRUE);
711 sci_empty_undo_buffer(doc->editor->sci);
713 doc->encoding = g_strdup(encodings[file_prefs.default_new_encoding].charset);
714 /* store the opened encoding for undo/redo */
715 store_saved_encoding(doc);
717 if (ft == NULL && utf8_filename != NULL) /* guess the filetype from the filename if one is given */
718 ft = filetypes_detect_from_document(doc);
720 document_set_filetype(doc, ft); /* also re-parses tags */
722 ui_set_window_title(doc);
723 build_menu_update(doc);
724 document_set_text_changed(doc, FALSE);
725 ui_document_show_hide(doc); /* update the document menu */
727 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
728 /* bring it in front, jump to the start and grab the focus */
729 editor_goto_pos(doc->editor, 0, FALSE);
730 document_try_focus(doc, NULL);
732 #ifdef USE_GIO_FILEMON
733 monitor_file_setup(doc);
734 #else
735 doc->priv->mtime = time(NULL);
736 #endif
738 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
739 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb), doc->editor);
741 g_signal_emit_by_name(geany_object, "document-new", doc);
743 msgwin_status_add(_("New file \"%s\" opened."),
744 DOC_FILENAME(doc));
746 return doc;
751 * Opens a document specified by @a locale_filename.
752 * Afterwards, the @c "document-open" signal is emitted for plugins.
754 * @param locale_filename The filename of the document to load, in locale encoding.
755 * @param readonly Whether to open the document in read-only mode.
756 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
757 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
759 * @return The document opened or @c NULL.
761 GeanyDocument *document_open_file(const gchar *locale_filename, gboolean readonly,
762 GeanyFiletype *ft, const gchar *forced_enc)
764 return document_open_file_full(NULL, locale_filename, 0, readonly, ft, forced_enc);
768 typedef struct
770 gchar *data; /* null-terminated file data */
771 gsize len; /* string length of data */
772 gchar *enc;
773 gboolean bom;
774 time_t mtime; /* modification time, read by stat::st_mtime */
775 gboolean readonly;
776 } FileData;
779 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
780 static gboolean load_text_file(const gchar *locale_filename, const gchar *display_filename,
781 FileData *filedata, const gchar *forced_enc)
783 GError *err = NULL;
784 struct stat st;
786 filedata->data = NULL;
787 filedata->len = 0;
788 filedata->enc = NULL;
789 filedata->bom = FALSE;
790 filedata->readonly = FALSE;
792 if (g_stat(locale_filename, &st) != 0)
794 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"),
795 display_filename, g_strerror(errno));
796 return FALSE;
799 filedata->mtime = st.st_mtime;
801 if (! g_file_get_contents(locale_filename, &filedata->data, NULL, &err))
803 ui_set_statusbar(TRUE, "%s", err->message);
804 g_error_free(err);
805 return FALSE;
808 filedata->len = (gsize) st.st_size;
809 if (! encodings_convert_to_utf8_auto(&filedata->data, &filedata->len, forced_enc,
810 &filedata->enc, &filedata->bom, &filedata->readonly))
812 if (forced_enc)
814 ui_set_statusbar(TRUE, _("The file \"%s\" is not valid %s."),
815 display_filename, forced_enc);
817 else
819 ui_set_statusbar(TRUE,
820 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
821 display_filename);
823 g_free(filedata->data);
824 return FALSE;
827 if (filedata->readonly)
829 const gchar *warn_msg = _(
830 "The file \"%s\" could not be opened properly and has been truncated. " \
831 "This can occur if the file contains a NULL byte. " \
832 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
834 if (main_status.main_window_realized)
835 dialogs_show_msgbox(GTK_MESSAGE_WARNING, warn_msg, display_filename);
837 ui_set_statusbar(TRUE, warn_msg, display_filename);
840 return TRUE;
844 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
845 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
846 * if cl_options.goto_column is set.
848 * returns the new position which may have changed */
849 static gint set_cursor_position(GeanyEditor *editor, gint pos)
851 if (cl_options.goto_line >= 0)
852 { /* goto line which was specified on command line and then undefine the line */
853 sci_goto_line(editor->sci, cl_options.goto_line - 1, TRUE);
854 editor->scroll_percent = 0.5F;
855 cl_options.goto_line = -1;
857 else if (pos > 0)
859 sci_set_current_position(editor->sci, pos, FALSE);
860 editor->scroll_percent = 0.5F;
863 if (cl_options.goto_column >= 0)
864 { /* goto column which was specified on command line and then undefine the column */
866 gint new_pos = sci_get_current_position(editor->sci) + cl_options.goto_column;
867 sci_set_current_position(editor->sci, new_pos, FALSE);
868 editor->scroll_percent = 0.5F;
869 cl_options.goto_column = -1;
870 return new_pos;
872 return sci_get_current_position(editor->sci);
876 /* Count lines that start with some hard tabs then a soft tab. */
877 static gboolean detect_tabs_and_spaces(GeanyEditor *editor)
879 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
880 ScintillaObject *sci = editor->sci;
881 gsize count = 0;
882 struct Sci_TextToFind ttf;
883 gchar *soft_tab = g_strnfill((gsize)iprefs->width, ' ');
884 gchar *regex = g_strconcat("^\t+", soft_tab, "[^ ]", NULL);
886 g_free(soft_tab);
888 ttf.chrg.cpMin = 0;
889 ttf.chrg.cpMax = sci_get_length(sci);
890 ttf.lpstrText = regex;
891 while (1)
893 gint pos;
895 pos = sci_find_text(sci, SCFIND_REGEXP, &ttf);
896 if (pos == -1)
897 break; /* no more matches */
898 count++;
899 ttf.chrg.cpMin = ttf.chrgText.cpMax + 1; /* search after this match */
901 g_free(regex);
902 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
903 return count > sci_get_line_count(sci) * 0.02;
907 /* Detect the indent type based on counting the leading indent characters for each line.
908 * Returns whether detection succeeded, and the detected type in *type_ upon success */
909 gboolean document_detect_indent_type(GeanyDocument *doc, GeanyIndentType *type_)
911 GeanyEditor *editor = doc->editor;
912 ScintillaObject *sci = editor->sci;
913 gint line, line_count;
914 gsize tabs = 0, spaces = 0;
916 if (detect_tabs_and_spaces(editor))
918 *type_ = GEANY_INDENT_TYPE_BOTH;
919 return TRUE;
922 line_count = sci_get_line_count(sci);
923 for (line = 0; line < line_count; line++)
925 gint pos = sci_get_position_from_line(sci, line);
926 gchar c;
928 /* most code will have indent total <= 24, otherwise it's more likely to be
929 * alignment than indentation */
930 if (sci_get_line_indentation(sci, line) > 24)
931 continue;
933 c = sci_get_char_at(sci, pos);
934 if (c == '\t')
935 tabs++;
936 /* check for at least 2 spaces */
937 else if (c == ' ' && sci_get_char_at(sci, pos + 1) == ' ')
938 spaces++;
940 if (spaces == 0 && tabs == 0)
941 return FALSE;
943 /* the factors may need to be tweaked */
944 if (spaces > tabs * 4)
945 *type_ = GEANY_INDENT_TYPE_SPACES;
946 else if (tabs > spaces * 4)
947 *type_ = GEANY_INDENT_TYPE_TABS;
948 else
949 *type_ = GEANY_INDENT_TYPE_BOTH;
951 return TRUE;
955 /* Detect the indent width based on counting the leading indent characters for each line.
956 * Returns whether detection succeeded, and the detected width in *width_ upon success */
957 static gboolean detect_indent_width(GeanyEditor *editor, GeanyIndentType type, gint *width_)
959 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(editor);
960 ScintillaObject *sci = editor->sci;
961 gint line, line_count;
962 gint widths[7] = { 0 }; /* width can be from 2 to 8 */
963 gint count, width, i;
965 /* can't easily detect the supposed width of a tab, guess the default is OK */
966 if (type == GEANY_INDENT_TYPE_TABS)
967 return FALSE;
969 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
970 sci_set_tab_width(sci, 8);
972 line_count = sci_get_line_count(sci);
973 for (line = 0; line < line_count; line++)
975 width = sci_get_line_indentation(sci, line);
976 /* most code will have indent total <= 24, otherwise it's more likely to be
977 * alignment than indentation */
978 if (width > 24)
979 continue;
980 /* < 2 is no indentation */
981 if (width < 2)
982 continue;
984 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
986 if ((width % (i + 2)) == 0)
987 widths[i]++;
990 count = 0;
991 width = iprefs->width;
992 for (i = G_N_ELEMENTS(widths) - 1; i >= 0; i--)
994 /* give large indents higher weight not to be fooled by spurious indents */
995 if (widths[i] >= count * 1.5)
997 width = i + 2;
998 count = widths[i];
1002 if (count == 0)
1003 return FALSE;
1005 *width_ = width;
1006 return TRUE;
1010 /* same as detect_indent_width() but uses editor's indent type */
1011 gboolean document_detect_indent_width(GeanyDocument *doc, gint *width_)
1013 return detect_indent_width(doc->editor, doc->editor->indent_type, width_);
1017 void document_apply_indent_settings(GeanyDocument *doc)
1019 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
1020 GeanyIndentType type = iprefs->type;
1021 gint width = iprefs->width;
1023 if (iprefs->detect_type && document_detect_indent_type(doc, &type))
1025 if (type != iprefs->type)
1027 const gchar *name = NULL;
1029 switch (type)
1031 case GEANY_INDENT_TYPE_SPACES:
1032 name = _("Spaces");
1033 break;
1034 case GEANY_INDENT_TYPE_TABS:
1035 name = _("Tabs");
1036 break;
1037 case GEANY_INDENT_TYPE_BOTH:
1038 name = _("Tabs and Spaces");
1039 break;
1041 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1042 * and Spaces), the second one is the filename */
1043 ui_set_statusbar(TRUE, _("Setting %s indentation mode for %s."), name,
1044 DOC_FILENAME(doc));
1047 else if (doc->file_type->indent_type > -1)
1048 type = doc->file_type->indent_type;
1050 if (iprefs->detect_width && detect_indent_width(doc->editor, type, &width))
1052 if (width != iprefs->width)
1054 ui_set_statusbar(TRUE, _("Setting indentation width to %d for %s."), width,
1055 DOC_FILENAME(doc));
1058 else if (doc->file_type->indent_width > -1)
1059 width = doc->file_type->indent_width;
1061 editor_set_indent(doc->editor, type, width);
1065 void document_show_tab(GeanyDocument *doc)
1067 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets.notebook),
1068 document_get_notebook_page(doc));
1072 /* To open a new file, set doc to NULL; filename should be locale encoded.
1073 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1074 * pos is the cursor position, which can be overridden by --line and --column.
1075 * forced_enc can be NULL to detect the file encoding.
1076 * Returns: doc of the opened file or NULL if an error occurred. */
1077 GeanyDocument *document_open_file_full(GeanyDocument *doc, const gchar *filename, gint pos,
1078 gboolean readonly, GeanyFiletype *ft, const gchar *forced_enc)
1080 gint editor_mode;
1081 gboolean reload = (doc == NULL) ? FALSE : TRUE;
1082 gchar *utf8_filename = NULL;
1083 gchar *display_filename = NULL;
1084 gchar *locale_filename = NULL;
1085 GeanyFiletype *use_ft;
1086 FileData filedata;
1088 if (reload)
1090 utf8_filename = g_strdup(doc->file_name);
1091 locale_filename = utils_get_locale_from_utf8(utf8_filename);
1093 else
1095 /* filename must not be NULL when opening a file */
1096 g_return_val_if_fail(filename, NULL);
1098 #ifdef G_OS_WIN32
1099 /* if filename is a shortcut, try to resolve it */
1100 locale_filename = win32_get_shortcut_target(filename);
1101 #else
1102 locale_filename = g_strdup(filename);
1103 #endif
1104 /* remove relative junk */
1105 utils_tidy_path(locale_filename);
1107 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1108 utf8_filename = utils_get_utf8_from_locale(locale_filename);
1110 /* if file is already open, switch to it and go */
1111 doc = document_find_by_filename(utf8_filename);
1112 if (doc != NULL)
1114 ui_add_recent_document(doc); /* either add or reorder recent item */
1115 /* show the doc before reload dialog */
1116 document_show_tab(doc);
1117 document_check_disk_status(doc, TRUE); /* force a file changed check */
1120 if (reload || doc == NULL)
1121 { /* doc possibly changed */
1122 display_filename = utils_str_middle_truncate(utf8_filename, 100);
1124 if (! load_text_file(locale_filename, display_filename, &filedata, forced_enc))
1126 g_free(display_filename);
1127 g_free(utf8_filename);
1128 g_free(locale_filename);
1129 return NULL;
1132 if (! reload)
1134 doc = document_create(utf8_filename);
1135 g_return_val_if_fail(doc != NULL, NULL); /* really should not happen */
1137 /* file exists on disk, set real_path */
1138 setptr(doc->real_path, tm_get_real_path(locale_filename));
1140 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1141 monitor_file_setup(doc);
1144 sci_set_undo_collection(doc->editor->sci, FALSE); /* avoid creation of an undo action */
1145 sci_empty_undo_buffer(doc->editor->sci);
1147 /* add the text to the ScintillaObject */
1148 sci_set_readonly(doc->editor->sci, FALSE); /* to allow replacing text */
1149 sci_set_text(doc->editor->sci, filedata.data); /* NULL terminated data */
1150 queue_colourise(doc); /* Ensure the document gets colourised. */
1152 /* detect & set line endings */
1153 editor_mode = utils_get_line_endings(filedata.data, filedata.len);
1154 sci_set_eol_mode(doc->editor->sci, editor_mode);
1155 g_free(filedata.data);
1157 sci_set_undo_collection(doc->editor->sci, TRUE);
1159 doc->priv->mtime = filedata.mtime; /* get the modification time from file and keep it */
1160 g_free(doc->encoding); /* if reloading, free old encoding */
1161 doc->encoding = filedata.enc;
1162 doc->has_bom = filedata.bom;
1163 store_saved_encoding(doc); /* store the opened encoding for undo/redo */
1165 doc->readonly = readonly || filedata.readonly;
1166 sci_set_readonly(doc->editor->sci, doc->readonly);
1168 /* update line number margin width */
1169 doc->priv->line_count = sci_get_line_count(doc->editor->sci);
1170 sci_set_line_numbers(doc->editor->sci, editor_prefs.show_linenumber_margin, 0);
1172 if (! reload)
1175 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1176 g_signal_connect(doc->editor->sci, "sci-notify", G_CALLBACK(editor_sci_notify_cb),
1177 doc->editor);
1179 use_ft = (ft != NULL) ? ft : filetypes_detect_from_document(doc);
1181 else
1182 { /* reloading */
1183 document_undo_clear(doc);
1185 use_ft = ft;
1187 /* update taglist, typedef keywords and build menu if necessary */
1188 document_set_filetype(doc, use_ft);
1190 /* set indentation settings after setting the filetype */
1191 if (reload)
1192 editor_set_indent(doc->editor, doc->editor->indent_type, doc->editor->indent_width); /* resetup sci */
1193 else
1194 document_apply_indent_settings(doc);
1196 document_set_text_changed(doc, FALSE); /* also updates tab state */
1197 ui_document_show_hide(doc); /* update the document menu */
1199 /* finally add current file to recent files menu, but not the files from the last session */
1200 if (! main_status.opening_session_files)
1201 ui_add_recent_document(doc);
1203 if (reload)
1205 g_signal_emit_by_name(geany_object, "document-reload", doc);
1206 ui_set_statusbar(TRUE, _("File %s reloaded."), display_filename);
1208 else
1210 g_signal_emit_by_name(geany_object, "document-open", doc);
1211 /* For translators: this is the status window message for opening a file. %d is the number
1212 * of the newly opened file, %s indicates whether the file is opened read-only
1213 * (it is replaced with the string ", read-only"). */
1214 msgwin_status_add(_("File %s opened(%d%s)."),
1215 display_filename, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook)),
1216 (readonly) ? _(", read-only") : "");
1220 g_free(display_filename);
1221 g_free(utf8_filename);
1222 g_free(locale_filename);
1224 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1225 pos = set_cursor_position(doc->editor, pos);
1226 /* now bring the file in front */
1227 editor_goto_pos(doc->editor, pos, FALSE);
1229 /* finally, let the editor widget grab the focus so you can start coding
1230 * right away */
1231 g_idle_add(on_idle_focus, doc);
1232 return doc;
1236 /* Takes a new line separated list of filename URIs and opens each file.
1237 * length is the length of the string */
1238 void document_open_file_list(const gchar *data, gsize length)
1240 guint i;
1241 gchar *filename;
1242 gchar **list;
1244 g_return_if_fail(data != NULL);
1246 list = g_strsplit(data, utils_get_eol_char(utils_get_line_endings(data, length)), 0);
1248 for (i = 0; list[i] != NULL; i++)
1250 filename = g_filename_from_uri(list[i], NULL, NULL);
1251 if (G_UNLIKELY(filename == NULL))
1252 continue;
1253 document_open_file(filename, FALSE, NULL, NULL);
1254 g_free(filename);
1257 g_strfreev(list);
1262 * Opens each file in the list @a filenames.
1263 * Internally, document_open_file() is called for every list item.
1265 * @param filenames A list of filenames to load, in locale encoding.
1266 * @param readonly Whether to open the document in read-only mode.
1267 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1268 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1270 void document_open_files(const GSList *filenames, gboolean readonly, GeanyFiletype *ft,
1271 const gchar *forced_enc)
1273 const GSList *item;
1275 for (item = filenames; item != NULL; item = g_slist_next(item))
1277 document_open_file(item->data, readonly, ft, forced_enc);
1283 * Reloads the document with the specified file encoding
1284 * @a forced_enc or @c NULL to auto-detect the file encoding.
1286 * @param doc The document to reload.
1287 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1289 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1291 gboolean document_reload_file(GeanyDocument *doc, const gchar *forced_enc)
1293 gint pos = 0;
1294 GeanyDocument *new_doc;
1296 g_return_val_if_fail(doc != NULL, FALSE);
1298 /* try to set the cursor to the position before reloading */
1299 pos = sci_get_current_position(doc->editor->sci);
1300 new_doc = document_open_file_full(doc, NULL, pos, doc->readonly, doc->file_type, forced_enc);
1302 return (new_doc != NULL);
1306 static gboolean document_update_timestamp(GeanyDocument *doc, const gchar *locale_filename)
1308 #ifndef USE_GIO_FILEMON
1309 struct stat st;
1311 g_return_val_if_fail(doc != NULL, FALSE);
1313 /* stat the file to get the timestamp, otherwise on Windows the actual
1314 * timestamp can be ahead of time(NULL) */
1315 if (g_stat(locale_filename, &st) != 0)
1317 ui_set_statusbar(TRUE, _("Could not open file %s (%s)"), doc->file_name,
1318 g_strerror(errno));
1319 return FALSE;
1322 doc->priv->mtime = st.st_mtime; /* get the modification time from file and keep it */
1323 #endif
1324 return TRUE;
1328 /* Sets line and column to the given position byte_pos in the document.
1329 * byte_pos is the position counted in bytes, not characters */
1330 static void get_line_column_from_pos(GeanyDocument *doc, guint byte_pos, gint *line, gint *column)
1332 gint i;
1333 gint line_start;
1335 /* for some reason we can use byte count instead of character count here */
1336 *line = sci_get_line_from_position(doc->editor->sci, byte_pos);
1337 line_start = sci_get_position_from_line(doc->editor->sci, *line);
1338 /* get the column in the line */
1339 *column = byte_pos - line_start;
1341 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1342 * skip one byte(i++) and decrease the column number which is based on byte count */
1343 for (i = line_start; i < (line_start + *column); i++)
1345 if (sci_get_char_at(doc->editor->sci, i) < 0)
1347 (*column)--;
1348 i++;
1354 static void replace_header_filename(GeanyDocument *doc)
1356 gchar *filebase;
1357 gchar *filename;
1358 struct Sci_TextToFind ttf;
1360 g_return_if_fail(doc != NULL);
1361 g_return_if_fail(doc->file_type != NULL);
1363 if (doc->file_type->extension)
1364 filebase = g_strconcat("\\<", GEANY_STRING_UNTITLED, "\\.\\w+", NULL);
1365 else
1366 filebase = g_strdup(GEANY_STRING_UNTITLED);
1368 filename = g_path_get_basename(doc->file_name);
1370 /* only search the first 3 lines */
1371 ttf.chrg.cpMin = 0;
1372 ttf.chrg.cpMax = sci_get_position_from_line(doc->editor->sci, 3);
1373 ttf.lpstrText = filebase;
1375 if (search_find_text(doc->editor->sci, SCFIND_MATCHCASE | SCFIND_REGEXP, &ttf) != -1)
1377 sci_set_target_start(doc->editor->sci, ttf.chrgText.cpMin);
1378 sci_set_target_end(doc->editor->sci, ttf.chrgText.cpMax);
1379 sci_replace_target(doc->editor->sci, filename, FALSE);
1381 g_free(filebase);
1382 g_free(filename);
1387 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1388 * you still have to call @ref document_save_file_as() to change the @a doc object.
1389 * It also stops monitoring for file changes to prevent receiving too many file change events
1390 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1392 * @param doc The current document which should be renamed.
1393 * @param new_filename The new filename in UTF-8 encoding.
1395 * @since 0.16
1397 void document_rename_file(GeanyDocument *doc, const gchar *new_filename)
1399 gchar *old_locale_filename = utils_get_locale_from_utf8(doc->file_name);
1400 gchar *new_locale_filename = utils_get_locale_from_utf8(new_filename);
1401 gint result;
1403 /* stop file monitoring to avoid getting events for deleting/creating files,
1404 * it's re-setup in document_save_file_as() */
1405 document_stop_file_monitoring(doc);
1407 result = g_rename(old_locale_filename, new_locale_filename);
1408 if (result != 0)
1410 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR,
1411 _("Error renaming file."), g_strerror(errno));
1413 g_free(old_locale_filename);
1414 g_free(new_locale_filename);
1418 /* Return TRUE if the document doesn't have a full filename set.
1419 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1420 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1421 * new files. */
1422 gboolean document_need_save_as(GeanyDocument *doc)
1424 g_return_val_if_fail(doc != NULL, FALSE);
1426 return (doc->file_name == NULL || !g_path_is_absolute(doc->file_name));
1431 * Saves the document, detecting the filetype.
1433 * @param doc The document for the file to save.
1434 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1435 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1437 * @see document_save_file().
1439 * @since 0.16
1441 gboolean document_save_file_as(GeanyDocument *doc, const gchar *utf8_fname)
1443 gboolean ret;
1445 g_return_val_if_fail(doc != NULL, FALSE);
1447 if (utf8_fname != NULL)
1448 setptr(doc->file_name, g_strdup(utf8_fname));
1450 /* reset real path, it's retrieved again in document_save() */
1451 setptr(doc->real_path, NULL);
1453 /* detect filetype */
1454 if (doc->file_type->id == GEANY_FILETYPES_NONE)
1456 GeanyFiletype *ft = filetypes_detect_from_document(doc);
1458 document_set_filetype(doc, ft);
1459 if (document_get_current() == doc)
1461 ignore_callback = TRUE;
1462 filetypes_select_radio_item(doc->file_type);
1463 ignore_callback = FALSE;
1466 replace_header_filename(doc);
1468 ret = document_save_file(doc, TRUE);
1470 /* file monitoring support, add file monitoring after the file has been saved
1471 * to ignore any earlier events */
1472 monitor_file_setup(doc);
1473 doc->priv->file_disk_status = FILE_IGNORE;
1475 if (ret)
1476 ui_add_recent_document(doc);
1477 return ret;
1481 static gsize save_convert_to_encoding(GeanyDocument *doc, gchar **data, gsize *len)
1483 GError *conv_error = NULL;
1484 gchar* conv_file_contents = NULL;
1485 gsize bytes_read;
1486 gsize conv_len;
1488 g_return_val_if_fail(data != NULL || *data == NULL, FALSE);
1489 g_return_val_if_fail(len != NULL, FALSE);
1491 /* try to convert it from UTF-8 to original encoding */
1492 conv_file_contents = g_convert(*data, *len - 1, doc->encoding, "UTF-8",
1493 &bytes_read, &conv_len, &conv_error);
1495 if (conv_error != NULL)
1497 gchar *text = g_strdup_printf(
1498 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1499 doc->encoding);
1500 gchar *error_text;
1502 if (conv_error->code == G_CONVERT_ERROR_ILLEGAL_SEQUENCE)
1504 gchar *context = NULL;
1505 gint line, column;
1506 gint context_len;
1507 gunichar unic;
1508 /* don't read over the doc length */
1509 gint max_len = MIN((gint)bytes_read + 6, (gint)*len - 1);
1510 context = g_malloc(7); /* read 6 bytes from Sci + '\0' */
1511 sci_get_text_range(doc->editor->sci, bytes_read, max_len, context);
1513 /* take only one valid Unicode character from the context and discard the leftover */
1514 unic = g_utf8_get_char_validated(context, -1);
1515 context_len = g_unichar_to_utf8(unic, context);
1516 context[context_len] = '\0';
1517 get_line_column_from_pos(doc, bytes_read, &line, &column);
1519 error_text = g_strdup_printf(
1520 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1521 conv_error->message, context, line + 1, column);
1522 g_free(context);
1524 else
1525 error_text = g_strdup_printf(_("Error message: %s."), conv_error->message);
1527 geany_debug("encoding error: %s", conv_error->message);
1528 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, text, error_text);
1529 g_error_free(conv_error);
1530 g_free(text);
1531 g_free(error_text);
1532 return FALSE;
1534 else
1536 g_free(*data);
1537 *data = conv_file_contents;
1538 *len = conv_len;
1540 return TRUE;
1544 static gchar *write_data_to_disk(const gchar *locale_filename,
1545 const gchar *data, gint len)
1547 GError *error = NULL;
1549 if (file_prefs.use_safe_file_saving)
1551 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1552 * This is the only option that handles disk space exhaustion. */
1553 if (g_file_set_contents(locale_filename, data, len, &error))
1554 geany_debug("Wrote %s with g_file_set_contents().", locale_filename);
1556 else if (file_prefs.use_gio_unsafe_file_saving)
1558 GFile *fp;
1560 /* Use GIO API to save file (GVFS-safe)
1561 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1562 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1563 fp = g_file_new_for_path(locale_filename);
1564 g_file_replace_contents(fp, data, len, NULL, file_prefs.gio_unsafe_save_backup,
1565 G_FILE_CREATE_NONE, NULL, NULL, &error);
1566 g_object_unref(fp);
1568 else
1570 FILE *fp;
1571 int save_errno;
1572 gchar *display_name = g_filename_display_name(locale_filename);
1574 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1575 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1576 errno = 0;
1577 fp = g_fopen(locale_filename, "wb");
1578 if (fp == NULL)
1580 save_errno = errno;
1582 g_set_error(&error,
1583 G_FILE_ERROR,
1584 g_file_error_from_errno(save_errno),
1585 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1586 display_name,
1587 g_strerror(save_errno));
1589 else
1591 gint bytes_written;
1593 errno = 0;
1594 bytes_written = fwrite(data, sizeof(gchar), len, fp);
1596 if (len != bytes_written)
1598 save_errno = errno;
1600 g_set_error(&error,
1601 G_FILE_ERROR,
1602 g_file_error_from_errno(save_errno),
1603 _("Failed to write file '%s': fwrite() failed: %s"),
1604 display_name,
1605 g_strerror(save_errno));
1608 errno = 0;
1609 /* preserve the fwrite() error if any */
1610 if (fclose(fp) != 0 && error == NULL)
1612 save_errno = errno;
1614 g_set_error(&error,
1615 G_FILE_ERROR,
1616 g_file_error_from_errno(save_errno),
1617 _("Failed to close file '%s': fclose() failed: %s"),
1618 display_name,
1619 g_strerror(save_errno));
1623 g_free(display_name);
1625 if (error != NULL)
1627 gchar *msg = g_strdup(error->message);
1628 g_error_free(error);
1629 /* geany will warn about file truncation for unsafe saving below */
1630 return msg;
1632 return NULL;
1636 static gchar *save_doc(GeanyDocument *doc, const gchar *locale_filename,
1637 const gchar *data, gint len)
1639 gchar *err;
1641 g_return_val_if_fail(doc != NULL, g_strdup(g_strerror(EINVAL)));
1642 g_return_val_if_fail(data != NULL, g_strdup(g_strerror(EINVAL)));
1644 err = write_data_to_disk(locale_filename, data, len);
1645 if (err)
1646 return err;
1648 /* now the file is on disk, set real_path */
1649 if (doc->real_path == NULL)
1651 doc->real_path = tm_get_real_path(locale_filename);
1652 doc->priv->is_remote = utils_is_remote_path(locale_filename);
1653 monitor_file_setup(doc);
1655 return NULL;
1660 * Saves the document.
1661 * Also shows the Save As dialog if necessary.
1662 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1664 * Saving may include replacing tabs by spaces,
1665 * stripping trailing spaces and adding a final new line at the end of the file, depending
1666 * on user preferences. Then the @c "document-before-save" signal is emitted,
1667 * allowing plugins to modify the document before it is saved, and data is
1668 * actually written to disk.
1670 * On successful saving:
1671 * - GeanyDocument::real_path is set.
1672 * - The filetype is set again or auto-detected if it wasn't set yet.
1673 * - The @c "document-save" signal is emitted for plugins.
1675 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1676 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1677 * added in Geany 1.22.
1679 * @param doc The document to save.
1680 * @param force Whether to save the file even if it is not modified.
1682 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1684 gboolean document_save_file(GeanyDocument *doc, gboolean force)
1686 gchar *errmsg;
1687 gchar *data;
1688 gsize len;
1689 gchar *locale_filename;
1691 g_return_val_if_fail(doc != NULL, FALSE);
1693 if (document_need_save_as(doc))
1695 /* ensure doc is the current tab before showing the dialog */
1696 document_show_tab(doc);
1697 return dialogs_show_save_as();
1700 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1701 if (! force && ! ui_prefs.allow_always_save && (! doc->changed || doc->readonly))
1702 return FALSE;
1704 /* replaces tabs by spaces but only if the current file is not a Makefile */
1705 if (file_prefs.replace_tabs && doc->file_type->id != GEANY_FILETYPES_MAKE)
1706 editor_replace_tabs(doc->editor);
1707 /* strip trailing spaces */
1708 if (file_prefs.strip_trailing_spaces)
1709 editor_strip_trailing_spaces(doc->editor);
1710 /* ensure the file has a newline at the end */
1711 if (file_prefs.final_new_line)
1712 editor_ensure_final_newline(doc->editor);
1713 /* ensure newlines are consistent */
1714 if (file_prefs.ensure_convert_new_lines)
1715 sci_convert_eols(doc->editor->sci, sci_get_eol_mode(doc->editor->sci));
1717 /* notify plugins which may wish to modify the document before it's saved */
1718 g_signal_emit_by_name(geany_object, "document-before-save", doc);
1720 len = sci_get_length(doc->editor->sci) + 1;
1721 if (doc->has_bom && encodings_is_unicode_charset(doc->encoding))
1722 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1723 * encoding, it will be converted to doc->encoding below and this conversion
1724 * also changes the BOM */
1725 data = (gchar*) g_malloc(len + 3); /* 3 chars for BOM */
1726 data[0] = (gchar) 0xef;
1727 data[1] = (gchar) 0xbb;
1728 data[2] = (gchar) 0xbf;
1729 sci_get_text(doc->editor->sci, len, data + 3);
1730 len += 3;
1732 else
1734 data = (gchar*) g_malloc(len);
1735 sci_get_text(doc->editor->sci, len, data);
1738 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1739 if (doc->encoding != NULL && ! utils_str_equal(doc->encoding, "UTF-8") &&
1740 ! utils_str_equal(doc->encoding, encodings[GEANY_ENCODING_NONE].charset))
1742 if (! save_convert_to_encoding(doc, &data, &len))
1744 g_free(data);
1745 return FALSE;
1748 else
1750 len = strlen(data);
1753 locale_filename = utils_get_locale_from_utf8(doc->file_name);
1755 /* ignore file changed notification when the file is written */
1756 doc->priv->file_disk_status = FILE_IGNORE;
1758 /* actually write the content of data to the file on disk */
1759 errmsg = save_doc(doc, locale_filename, data, len);
1760 g_free(data);
1762 if (errmsg != NULL)
1764 ui_set_statusbar(TRUE, _("Error saving file (%s)."), errmsg);
1766 if (!file_prefs.use_safe_file_saving)
1768 setptr(errmsg,
1769 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg));
1771 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR, _("Error saving file."), errmsg);
1772 doc->priv->file_disk_status = FILE_OK;
1773 utils_beep();
1774 g_free(locale_filename);
1775 g_free(errmsg);
1776 return FALSE;
1779 /* store the opened encoding for undo/redo */
1780 store_saved_encoding(doc);
1782 /* ignore the following things if we are quitting */
1783 if (! main_status.quitting)
1785 sci_set_savepoint(doc->editor->sci);
1787 if (file_prefs.disk_check_timeout > 0)
1788 document_update_timestamp(doc, locale_filename);
1790 /* update filetype-related things */
1791 document_set_filetype(doc, doc->file_type);
1793 document_update_tab_label(doc);
1795 msgwin_status_add(_("File %s saved."), doc->file_name);
1796 ui_update_statusbar(doc, -1);
1797 #ifdef HAVE_VTE
1798 vte_cwd((doc->real_path != NULL) ? doc->real_path : doc->file_name, FALSE);
1799 #endif
1801 g_free(locale_filename);
1803 g_signal_emit_by_name(geany_object, "document-save", doc);
1805 return TRUE;
1809 /* special search function, used from the find entry in the toolbar
1810 * return TRUE if text was found otherwise FALSE
1811 * return also TRUE if text is empty */
1812 gboolean document_search_bar_find(GeanyDocument *doc, const gchar *text, gint flags, gboolean inc,
1813 gboolean backwards)
1815 gint start_pos, search_pos;
1816 struct Sci_TextToFind ttf;
1818 g_return_val_if_fail(text != NULL, FALSE);
1819 g_return_val_if_fail(doc != NULL, FALSE);
1820 if (! *text)
1821 return TRUE;
1823 start_pos = (inc || backwards) ? sci_get_selection_start(doc->editor->sci) :
1824 sci_get_selection_end(doc->editor->sci); /* equal if no selection */
1826 /* search cursor to end or start */
1827 ttf.chrg.cpMin = start_pos;
1828 ttf.chrg.cpMax = backwards ? 0 : sci_get_length(doc->editor->sci);
1829 ttf.lpstrText = (gchar *)text;
1830 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1832 /* if no match, search start (or end) to cursor */
1833 if (search_pos == -1)
1835 if (backwards)
1837 ttf.chrg.cpMin = sci_get_length(doc->editor->sci);
1838 ttf.chrg.cpMax = start_pos;
1840 else
1842 ttf.chrg.cpMin = 0;
1843 ttf.chrg.cpMax = start_pos + strlen(text);
1845 search_pos = sci_find_text(doc->editor->sci, flags, &ttf);
1848 if (search_pos != -1)
1850 gint line = sci_get_line_from_position(doc->editor->sci, ttf.chrgText.cpMin);
1852 /* unfold maybe folded results */
1853 sci_ensure_line_is_visible(doc->editor->sci, line);
1855 sci_set_selection_start(doc->editor->sci, ttf.chrgText.cpMin);
1856 sci_set_selection_end(doc->editor->sci, ttf.chrgText.cpMax);
1858 if (! editor_line_in_view(doc->editor, line))
1859 { /* we need to force scrolling in case the cursor is outside of the current visible area
1860 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1861 * while searching */
1862 editor_scroll_to_line(doc->editor, -1, 0.3F);
1864 else
1865 sci_scroll_caret(doc->editor->sci); /* may need horizontal scrolling */
1866 return TRUE;
1868 else
1870 if (! inc)
1872 ui_set_statusbar(FALSE, _("\"%s\" was not found."), text);
1874 utils_beep();
1875 sci_goto_pos(doc->editor->sci, start_pos, FALSE); /* clear selection */
1876 return FALSE;
1881 /* General search function, used from the find dialog.
1882 * Returns -1 on failure or the start position of the matching text.
1883 * Will skip past any selection, ignoring it.
1885 * @param text Text to find.
1886 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1888 gint document_find_text(GeanyDocument *doc, const gchar *text, const gchar *original_text,
1889 gint flags, gboolean search_backwards, gboolean scroll, GtkWidget *parent)
1891 gint selection_end, selection_start, search_pos;
1893 g_return_val_if_fail(doc != NULL && text != NULL, -1);
1894 if (! *text)
1895 return -1;
1897 /* Sci doesn't support searching backwards with a regex */
1898 if (flags & SCFIND_REGEXP)
1899 search_backwards = FALSE;
1901 if (!original_text)
1902 original_text = text;
1904 selection_start = sci_get_selection_start(doc->editor->sci);
1905 selection_end = sci_get_selection_end(doc->editor->sci);
1906 if ((selection_end - selection_start) > 0)
1907 { /* there's a selection so go to the end */
1908 if (search_backwards)
1909 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1910 else
1911 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1914 sci_set_search_anchor(doc->editor->sci);
1915 if (search_backwards)
1916 search_pos = sci_search_prev(doc->editor->sci, flags, text);
1917 else
1918 search_pos = search_find_next(doc->editor->sci, text, flags);
1920 if (search_pos != -1)
1922 /* unfold maybe folded results */
1923 sci_ensure_line_is_visible(doc->editor->sci,
1924 sci_get_line_from_position(doc->editor->sci, search_pos));
1925 if (scroll)
1926 doc->editor->scroll_percent = 0.3F;
1928 else
1930 gint sci_len = sci_get_length(doc->editor->sci);
1932 /* if we just searched the whole text, give up searching. */
1933 if ((selection_end == 0 && ! search_backwards) ||
1934 (selection_end == sci_len && search_backwards))
1936 ui_set_statusbar(FALSE, _("\"%s\" was not found."), original_text);
1937 utils_beep();
1938 return -1;
1941 /* we searched only part of the document, so ask whether to wraparound. */
1942 if (search_prefs.suppress_dialogs ||
1943 dialogs_show_question_full(parent, GTK_STOCK_FIND, GTK_STOCK_CANCEL,
1944 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text))
1946 gint ret;
1948 sci_set_current_position(doc->editor->sci, (search_backwards) ? sci_len : 0, FALSE);
1949 ret = document_find_text(doc, text, original_text, flags, search_backwards, scroll, parent);
1950 if (ret == -1)
1951 { /* return to original cursor position if not found */
1952 sci_set_current_position(doc->editor->sci, selection_start, FALSE);
1954 return ret;
1957 return search_pos;
1961 /* Replaces the selection if it matches, otherwise just finds the next match.
1962 * Returns: start of replaced text, or -1 if no replacement was made
1964 * @param find_text Text to find.
1965 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
1967 gint document_replace_text(GeanyDocument *doc, const gchar *find_text, const gchar *original_find_text,
1968 const gchar *replace_text, gint flags, gboolean search_backwards)
1970 gint selection_end, selection_start, search_pos;
1972 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, -1);
1974 if (! *find_text)
1975 return -1;
1977 /* Sci doesn't support searching backwards with a regex */
1978 if (flags & SCFIND_REGEXP)
1979 search_backwards = FALSE;
1981 if (!original_find_text)
1982 original_find_text = find_text;
1984 selection_start = sci_get_selection_start(doc->editor->sci);
1985 selection_end = sci_get_selection_end(doc->editor->sci);
1986 if (selection_end == selection_start)
1988 /* no selection so just find the next match */
1989 document_find_text(doc, find_text, original_find_text, flags, search_backwards, TRUE, NULL);
1990 return -1;
1992 /* there's a selection so go to the start before finding to search through it
1993 * this ensures there is a match */
1994 if (search_backwards)
1995 sci_goto_pos(doc->editor->sci, selection_end, TRUE);
1996 else
1997 sci_goto_pos(doc->editor->sci, selection_start, TRUE);
1999 search_pos = document_find_text(doc, find_text, original_find_text, flags, search_backwards, TRUE, NULL);
2000 /* return if the original selected text did not match (at the start of the selection) */
2001 if (search_pos != selection_start)
2002 return -1;
2004 if (search_pos != -1)
2006 gint replace_len;
2007 /* search next/prev will select matching text, which we use to set the replace target */
2008 sci_target_from_selection(doc->editor->sci);
2009 replace_len = search_replace_target(doc->editor->sci, replace_text, flags & SCFIND_REGEXP);
2010 /* select the replacement - find text will skip past the selected text */
2011 sci_set_selection_start(doc->editor->sci, search_pos);
2012 sci_set_selection_end(doc->editor->sci, search_pos + replace_len);
2014 else
2016 /* no match in the selection */
2017 utils_beep();
2019 return search_pos;
2023 static void show_replace_summary(GeanyDocument *doc, gint count, const gchar *original_find_text,
2024 const gchar *original_replace_text)
2026 gchar *filename;
2028 if (count == 0)
2030 ui_set_statusbar(FALSE, _("No matches found for \"%s\"."), original_find_text);
2031 return;
2034 filename = g_path_get_basename(DOC_FILENAME(doc));
2035 ui_set_statusbar(TRUE, ngettext(
2036 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2037 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2038 count), filename, count, original_find_text, original_replace_text);
2039 g_free(filename);
2043 /* Replace all text matches in a certain range within document.
2044 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2045 * or -1 if no text was found.
2046 * scroll_to_match is whether to scroll the last replacement in view (which also
2047 * clears the selection).
2048 * Returns: the number of replacements made. */
2049 static guint
2050 document_replace_range(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2051 gint flags, gint start, gint end, gboolean scroll_to_match, gint *new_range_end)
2053 gint count = 0;
2054 struct Sci_TextToFind ttf;
2055 ScintillaObject *sci;
2057 if (new_range_end != NULL)
2058 *new_range_end = -1;
2060 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, 0);
2062 if (! *find_text || doc->readonly)
2063 return 0;
2065 sci = doc->editor->sci;
2067 ttf.chrg.cpMin = start;
2068 ttf.chrg.cpMax = end;
2069 ttf.lpstrText = (gchar*)find_text;
2071 sci_start_undo_action(sci);
2072 count = search_replace_range(sci, &ttf, flags, replace_text);
2073 sci_end_undo_action(sci);
2075 if (count > 0)
2076 { /* scroll last match in view, will destroy the existing selection */
2077 if (scroll_to_match)
2078 sci_goto_pos(sci, ttf.chrg.cpMin, TRUE);
2080 if (new_range_end != NULL)
2081 *new_range_end = ttf.chrg.cpMax;
2083 return count;
2087 void document_replace_sel(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2088 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2090 gint selection_end, selection_start, selection_mode, selected_lines, last_line = 0;
2091 gint max_column = 0, count = 0;
2092 gboolean replaced = FALSE;
2094 g_return_if_fail(doc != NULL && find_text != NULL && replace_text != NULL);
2096 if (! *find_text)
2097 return;
2099 selection_start = sci_get_selection_start(doc->editor->sci);
2100 selection_end = sci_get_selection_end(doc->editor->sci);
2101 /* do we have a selection? */
2102 if ((selection_end - selection_start) == 0)
2104 utils_beep();
2105 return;
2108 selection_mode = sci_get_selection_mode(doc->editor->sci);
2109 selected_lines = sci_get_lines_selected(doc->editor->sci);
2110 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2111 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2113 gint first_line, line;
2115 sci_start_undo_action(doc->editor->sci);
2117 first_line = sci_get_line_from_position(doc->editor->sci, selection_start);
2118 /* Find the last line with chars selected (not EOL char) */
2119 last_line = sci_get_line_from_position(doc->editor->sci,
2120 selection_end - editor_get_eol_char_len(doc->editor));
2121 last_line = MAX(first_line, last_line);
2122 for (line = first_line; line < (first_line + selected_lines); line++)
2124 gint line_start = sci_get_pos_at_line_sel_start(doc->editor->sci, line);
2125 gint line_end = sci_get_pos_at_line_sel_end(doc->editor->sci, line);
2127 /* skip line if there is no selection */
2128 if (line_start != INVALID_POSITION)
2130 /* don't let document_replace_range() scroll to match to keep our selection */
2131 gint new_sel_end;
2133 count += document_replace_range(doc, find_text, replace_text, flags,
2134 line_start, line_end, FALSE, &new_sel_end);
2135 if (new_sel_end != -1)
2137 replaced = TRUE;
2138 /* this gets the greatest column within the selection after replacing */
2139 max_column = MAX(max_column,
2140 new_sel_end - sci_get_position_from_line(doc->editor->sci, line));
2144 sci_end_undo_action(doc->editor->sci);
2146 else /* handle normal line selection */
2148 count += document_replace_range(doc, find_text, replace_text, flags,
2149 selection_start, selection_end, TRUE, &selection_end);
2150 if (selection_end != -1)
2151 replaced = TRUE;
2154 if (replaced)
2155 { /* update the selection for the new endpoint */
2157 if (selection_mode == SC_SEL_RECTANGLE && selected_lines > 1)
2159 /* now we can scroll to the selection and destroy it because we rebuild it later */
2160 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2162 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2163 * the highest column on the last line. The wrapped selection is completely different
2164 * from the original one, so skip the selection at all */
2165 /* TODO is there a better way to handle the wrapped selection? */
2166 if ((sci_get_line_length(doc->editor->sci, last_line) - 1) >= max_column)
2167 { /* for keeping and adjusting the selection in multi line rectangle selection we
2168 * need the last line of the original selection and the greatest column number after
2169 * replacing and set the selection end to the last line at the greatest column */
2170 sci_set_selection_start(doc->editor->sci, selection_start);
2171 sci_set_selection_end(doc->editor->sci,
2172 sci_get_position_from_line(doc->editor->sci, last_line) + max_column);
2173 sci_set_selection_mode(doc->editor->sci, selection_mode);
2176 else
2178 sci_set_selection_start(doc->editor->sci, selection_start);
2179 sci_set_selection_end(doc->editor->sci, selection_end);
2182 else /* no replacements */
2183 utils_beep();
2185 show_replace_summary(doc, count, original_find_text, original_replace_text);
2189 /* returns number of replacements made. */
2190 gint document_replace_all(GeanyDocument *doc, const gchar *find_text, const gchar *replace_text,
2191 const gchar *original_find_text, const gchar *original_replace_text, gint flags)
2193 gint len, count;
2194 g_return_val_if_fail(doc != NULL && find_text != NULL && replace_text != NULL, FALSE);
2196 if (! *find_text)
2197 return FALSE;
2199 len = sci_get_length(doc->editor->sci);
2200 count = document_replace_range(
2201 doc, find_text, replace_text, flags, 0, len, TRUE, NULL);
2203 show_replace_summary(doc, count, original_find_text, original_replace_text);
2204 return count;
2209 * Parses or re-parses the document's buffer and updates the type
2210 * keywords and symbol list.
2212 * @param doc The document.
2214 void document_update_tags(GeanyDocument *doc)
2216 guchar *buffer_ptr;
2217 gsize len;
2218 GString *keywords_str;
2219 gchar *keywords;
2220 gint keyword_idx;
2222 g_return_if_fail(DOC_VALID(doc));
2223 g_return_if_fail(app->tm_workspace != NULL);
2225 /* early out if it's a new file or doesn't support tags */
2226 if (! doc->file_name || ! doc->file_type || !filetype_has_tags(doc->file_type))
2228 /* We must call sidebar_update_tag_list() before returning,
2229 * to ensure that the symbol list is always updated properly (e.g.
2230 * when creating a new document with a partial filename set. */
2231 sidebar_update_tag_list(doc, FALSE);
2232 return;
2235 /* create a new TM file if there isn't one yet */
2236 if (! doc->tm_file)
2238 gchar *locale_filename = utils_get_locale_from_utf8(doc->file_name);
2239 const gchar *name;
2241 /* lookup the name rather than using filetype name to support custom filetypes */
2242 name = tm_source_file_get_lang_name(doc->file_type->lang);
2243 doc->tm_file = tm_source_file_new(locale_filename, FALSE, name);
2244 g_free(locale_filename);
2246 if (doc->tm_file && !tm_workspace_add_object(doc->tm_file))
2248 tm_work_object_free(doc->tm_file);
2249 doc->tm_file = NULL;
2253 /* early out if there's no work object and we couldn't create one */
2254 if (doc->tm_file == NULL)
2256 /* We must call sidebar_update_tag_list() before returning,
2257 * to ensure that the symbol list is always updated properly (e.g.
2258 * when creating a new document with a partial filename set. */
2259 sidebar_update_tag_list(doc, FALSE);
2260 return;
2263 /* Parse Scintilla's buffer directly using TagManager
2264 * Note: this buffer *MUST NOT* be modified */
2265 len = sci_get_length(doc->editor->sci);
2266 buffer_ptr = (guchar *) scintilla_send_message(doc->editor->sci, SCI_GETCHARACTERPOINTER, 0, 0);
2267 tm_source_file_buffer_update(doc->tm_file, buffer_ptr, len, TRUE);
2269 sidebar_update_tag_list(doc, TRUE);
2271 /* some filetypes support type keywords (such as struct names), but not
2272 * necessarily all filetypes for a particular scintilla lexer. this
2273 * tells us whether the filetype supports keywords, and if so
2274 * which index to use for the scintilla keywords set. */
2275 switch (doc->file_type->id)
2277 case GEANY_FILETYPES_C:
2278 case GEANY_FILETYPES_CPP:
2279 case GEANY_FILETYPES_CS:
2280 case GEANY_FILETYPES_D:
2281 case GEANY_FILETYPES_JAVA:
2282 case GEANY_FILETYPES_OBJECTIVEC:
2283 case GEANY_FILETYPES_VALA:
2286 /* index of the keyword set in the Scintilla lexer, for
2287 * example in LexCPP.cxx, see "cppWordLists" global array.
2288 * TODO: this magic number should be a member of the filetype */
2289 keyword_idx = 3;
2290 break;
2292 default:
2293 return; /* early out if type keywords are not supported */
2296 /* get any type keywords and tell scintilla about them
2297 * this will cause the type keywords to be colourized in scintilla */
2298 keywords_str = symbols_find_tags_as_string(app->tm_workspace->work_object.tags_array,
2299 TM_GLOBAL_TYPE_MASK, doc->file_type->lang);
2300 if (keywords_str)
2302 keywords = g_string_free(keywords_str, FALSE);
2303 sci_set_keywords(doc->editor->sci, keyword_idx, keywords);
2304 g_free(keywords);
2305 queue_colourise(doc); /* force re-highlighting the entire document */
2310 static gboolean on_document_update_tag_list_idle(gpointer data)
2312 GeanyDocument *doc = data;
2314 if (! DOC_VALID(doc))
2315 return FALSE;
2317 if (! main_status.quitting)
2318 document_update_tags(doc);
2320 doc->priv->tag_list_update_source = 0;
2322 /* don't update the tags until another modification of the buffer */
2323 return FALSE;
2327 void document_update_tag_list_in_idle(GeanyDocument *doc)
2329 if (editor_prefs.autocompletion_update_freq <= 0 || ! filetype_has_tags(doc->file_type))
2330 return;
2332 /* prevent "stacking up" callback handlers, we only need one to run soon */
2333 if (doc->priv->tag_list_update_source != 0)
2334 g_source_remove(doc->priv->tag_list_update_source);
2336 doc->priv->tag_list_update_source = g_timeout_add_full(G_PRIORITY_LOW,
2337 editor_prefs.autocompletion_update_freq, on_document_update_tag_list_idle, doc, NULL);
2341 static void document_load_config(GeanyDocument *doc, GeanyFiletype *type,
2342 gboolean filetype_changed)
2344 g_return_if_fail(doc);
2345 if (type == NULL)
2346 type = filetypes[GEANY_FILETYPES_NONE];
2348 if (filetype_changed)
2350 doc->file_type = type;
2352 /* delete tm file object to force creation of a new one */
2353 if (doc->tm_file != NULL)
2355 tm_workspace_remove_object(doc->tm_file, TRUE, TRUE);
2356 doc->tm_file = NULL;
2358 /* load tags files before highlighting (some lexers highlight global typenames) */
2359 if (type->id != GEANY_FILETYPES_NONE)
2360 symbols_global_tags_loaded(type->id);
2362 highlighting_set_styles(doc->editor->sci, type);
2363 editor_set_indentation_guides(doc->editor);
2364 build_menu_update(doc);
2365 queue_colourise(doc);
2366 doc->priv->symbol_list_sort_mode = type->priv->symbol_list_sort_mode;
2369 document_update_tags(doc);
2373 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2374 * @param doc The document to use.
2375 * @param type The filetype. */
2376 void document_set_filetype(GeanyDocument *doc, GeanyFiletype *type)
2378 gboolean ft_changed;
2379 GeanyFiletype *old_ft;
2381 g_return_if_fail(doc);
2382 if (type == NULL)
2383 type = filetypes[GEANY_FILETYPES_NONE];
2385 old_ft = doc->file_type;
2386 geany_debug("%s : %s (%s)",
2387 (doc->file_name != NULL) ? doc->file_name : "unknown",
2388 type->name,
2389 (doc->encoding != NULL) ? doc->encoding : "unknown");
2391 ft_changed = (doc->file_type != type); /* filetype has changed */
2392 document_load_config(doc, type, ft_changed);
2394 if (ft_changed)
2396 const GeanyIndentPrefs *iprefs = editor_get_indent_prefs(NULL);
2398 /* assume that if previous filetype was none and the settings are the default ones, this
2399 * is the first time the filetype is carefully set, so we should apply indent settings */
2400 if (old_ft && old_ft->id == GEANY_FILETYPES_NONE &&
2401 doc->editor->indent_type == iprefs->type &&
2402 doc->editor->indent_width == iprefs->width)
2404 document_apply_indent_settings(doc);
2405 ui_document_show_hide(doc);
2408 sidebar_openfiles_update(doc); /* to update the icon */
2409 g_signal_emit_by_name(geany_object, "document-filetype-set", doc, old_ft);
2414 void document_reload_config(GeanyDocument *doc)
2416 document_load_config(doc, doc->file_type, TRUE);
2421 * Sets the encoding of a document.
2422 * This function only set the encoding of the %document, it does not any conversions. The new
2423 * encoding is used when e.g. saving the file.
2425 * @param doc The document to use.
2426 * @param new_encoding The encoding to be set for the document.
2428 void document_set_encoding(GeanyDocument *doc, const gchar *new_encoding)
2430 if (doc == NULL || new_encoding == NULL ||
2431 utils_str_equal(new_encoding, doc->encoding))
2432 return;
2434 g_free(doc->encoding);
2435 doc->encoding = g_strdup(new_encoding);
2437 ui_update_statusbar(doc, -1);
2438 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets.window, "menu_write_unicode_bom1"),
2439 encodings_is_unicode_charset(doc->encoding));
2443 /* own Undo / Redo implementation to be able to undo / redo changes
2444 * to the encoding or the Unicode BOM (which are Scintilla independet).
2445 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2447 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2448 void document_undo_clear(GeanyDocument *doc)
2450 undo_action *a;
2452 while (g_trash_stack_height(&doc->priv->undo_actions) > 0)
2454 a = g_trash_stack_pop(&doc->priv->undo_actions);
2455 if (G_LIKELY(a != NULL))
2457 switch (a->type)
2459 case UNDO_ENCODING: g_free(a->data); break;
2460 default: break;
2462 g_free(a);
2465 doc->priv->undo_actions = NULL;
2467 while (g_trash_stack_height(&doc->priv->redo_actions) > 0)
2469 a = g_trash_stack_pop(&doc->priv->redo_actions);
2470 if (G_LIKELY(a != NULL))
2472 switch (a->type)
2474 case UNDO_ENCODING: g_free(a->data); break;
2475 default: break;
2477 g_free(a);
2480 doc->priv->redo_actions = NULL;
2482 if (! main_status.quitting && doc->editor != NULL)
2483 document_set_text_changed(doc, FALSE);
2487 void document_undo_add(GeanyDocument *doc, guint type, gpointer data)
2489 undo_action *action;
2491 g_return_if_fail(doc != NULL);
2493 action = g_new0(undo_action, 1);
2494 action->type = type;
2495 action->data = data;
2497 g_trash_stack_push(&doc->priv->undo_actions, action);
2499 document_set_text_changed(doc, TRUE);
2500 ui_update_popup_reundo_items(doc);
2504 gboolean document_can_undo(GeanyDocument *doc)
2506 g_return_val_if_fail(doc != NULL, FALSE);
2508 if (g_trash_stack_height(&doc->priv->undo_actions) > 0 || sci_can_undo(doc->editor->sci))
2509 return TRUE;
2510 else
2511 return FALSE;
2515 static void update_changed_state(GeanyDocument *doc)
2517 doc->changed =
2518 (sci_is_modified(doc->editor->sci) ||
2519 doc->has_bom != doc->priv->saved_encoding.has_bom ||
2520 ! utils_str_equal(doc->encoding, doc->priv->saved_encoding.encoding));
2521 document_set_text_changed(doc, doc->changed);
2525 void document_undo(GeanyDocument *doc)
2527 undo_action *action;
2529 g_return_if_fail(doc != NULL);
2531 action = g_trash_stack_pop(&doc->priv->undo_actions);
2533 if (G_UNLIKELY(action == NULL))
2535 /* fallback, should not be necessary */
2536 geany_debug("%s: fallback used", G_STRFUNC);
2537 sci_undo(doc->editor->sci);
2539 else
2541 switch (action->type)
2543 case UNDO_SCINTILLA:
2545 document_redo_add(doc, UNDO_SCINTILLA, NULL);
2547 sci_undo(doc->editor->sci);
2548 break;
2550 case UNDO_BOM:
2552 document_redo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2554 doc->has_bom = GPOINTER_TO_INT(action->data);
2555 ui_update_statusbar(doc, -1);
2556 ui_document_show_hide(doc);
2557 break;
2559 case UNDO_ENCODING:
2561 /* use the "old" encoding */
2562 document_redo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2564 document_set_encoding(doc, (const gchar*)action->data);
2566 ignore_callback = TRUE;
2567 encodings_select_radio_item((const gchar*)action->data);
2568 ignore_callback = FALSE;
2570 g_free(action->data);
2571 break;
2573 default: break;
2576 g_free(action); /* free the action which was taken from the stack */
2578 update_changed_state(doc);
2579 ui_update_popup_reundo_items(doc);
2583 gboolean document_can_redo(GeanyDocument *doc)
2585 g_return_val_if_fail(doc != NULL, FALSE);
2587 if (g_trash_stack_height(&doc->priv->redo_actions) > 0 || sci_can_redo(doc->editor->sci))
2588 return TRUE;
2589 else
2590 return FALSE;
2594 void document_redo(GeanyDocument *doc)
2596 undo_action *action;
2598 g_return_if_fail(doc != NULL);
2600 action = g_trash_stack_pop(&doc->priv->redo_actions);
2602 if (G_UNLIKELY(action == NULL))
2604 /* fallback, should not be necessary */
2605 geany_debug("%s: fallback used", G_STRFUNC);
2606 sci_redo(doc->editor->sci);
2608 else
2610 switch (action->type)
2612 case UNDO_SCINTILLA:
2614 document_undo_add(doc, UNDO_SCINTILLA, NULL);
2616 sci_redo(doc->editor->sci);
2617 break;
2619 case UNDO_BOM:
2621 document_undo_add(doc, UNDO_BOM, GINT_TO_POINTER(doc->has_bom));
2623 doc->has_bom = GPOINTER_TO_INT(action->data);
2624 ui_update_statusbar(doc, -1);
2625 ui_document_show_hide(doc);
2626 break;
2628 case UNDO_ENCODING:
2630 document_undo_add(doc, UNDO_ENCODING, g_strdup(doc->encoding));
2632 document_set_encoding(doc, (const gchar*)action->data);
2634 ignore_callback = TRUE;
2635 encodings_select_radio_item((const gchar*)action->data);
2636 ignore_callback = FALSE;
2638 g_free(action->data);
2639 break;
2641 default: break;
2644 g_free(action); /* free the action which was taken from the stack */
2646 update_changed_state(doc);
2647 ui_update_popup_reundo_items(doc);
2651 static void document_redo_add(GeanyDocument *doc, guint type, gpointer data)
2653 undo_action *action;
2655 g_return_if_fail(doc != NULL);
2657 action = g_new0(undo_action, 1);
2658 action->type = type;
2659 action->data = data;
2661 g_trash_stack_push(&doc->priv->redo_actions, action);
2663 document_set_text_changed(doc, TRUE);
2664 ui_update_popup_reundo_items(doc);
2669 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2670 * Returned colors are red if the document has changes, green if the document is read-only
2671 * or simply @c NULL if the document is unmodified but writable.
2673 * @param doc The document to use.
2675 * @return The color for the document or @c NULL if the default color should be used. The color
2676 * object is owned by Geany and should not be modified or freed.
2678 * @since 0.16
2680 const GdkColor *document_get_status_color(GeanyDocument *doc)
2682 static GdkColor red = {0, 0xFFFF, 0, 0};
2683 static GdkColor green = {0, 0, 0x7FFF, 0};
2684 #ifdef USE_GIO_FILEMON
2685 static GdkColor orange = {0, 0xFFFF, 0x7FFF, 0};
2686 #endif
2687 GdkColor *color = NULL;
2689 g_return_val_if_fail(doc != NULL, NULL);
2691 if (doc->changed)
2692 color = &red;
2693 #ifdef USE_GIO_FILEMON
2694 else if (doc->priv->file_disk_status == FILE_CHANGED)
2695 color = &orange;
2696 #endif
2697 else if (doc->readonly)
2698 color = &green;
2700 return color; /* return pointer to static GdkColor. */
2704 /** Accessor function for @ref GeanyData::documents_array items.
2705 * @warning Always check the returned document is valid (@c doc->is_valid).
2706 * @param idx @c documents_array index.
2707 * @return The document, or @c NULL if @a idx is out of range.
2709 * @since 0.16
2711 GeanyDocument *document_index(gint idx)
2713 return (idx >= 0 && idx < (gint) documents_array->len) ? documents[idx] : NULL;
2717 /* create a new file and copy file content and properties */
2718 GeanyDocument *document_clone(GeanyDocument *old_doc, const gchar *utf8_filename)
2720 gint len;
2721 gchar *text;
2722 GeanyDocument *doc;
2724 g_return_val_if_fail(old_doc != NULL, NULL);
2726 len = sci_get_length(old_doc->editor->sci) + 1;
2727 text = (gchar*) g_malloc(len);
2728 sci_get_text(old_doc->editor->sci, len, text);
2729 /* use old file type (or maybe NULL for auto detect would be better?) */
2730 doc = document_new_file(utf8_filename, old_doc->file_type, text);
2731 g_free(text);
2733 /* copy file properties */
2734 doc->editor->line_wrapping = old_doc->editor->line_wrapping;
2735 doc->readonly = old_doc->readonly;
2736 doc->has_bom = old_doc->has_bom;
2737 document_set_encoding(doc, old_doc->encoding);
2738 sci_set_lines_wrapped(doc->editor->sci, doc->editor->line_wrapping);
2739 sci_set_readonly(doc->editor->sci, doc->readonly);
2741 ui_document_show_hide(doc);
2742 return doc;
2746 /* @note If successful, this should always be followed up with a call to
2747 * document_close_all().
2748 * @return TRUE if all files were saved or had their changes discarded. */
2749 gboolean document_account_for_unsaved(void)
2751 guint i, p, page_count;
2753 page_count = gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets.notebook));
2754 /* iterate over documents in tabs order */
2755 for (p = 0; p < page_count; p++)
2757 GeanyDocument *doc = document_get_from_page(p);
2759 if (DOC_VALID(doc) && doc->changed)
2761 if (! dialogs_show_unsaved_file(doc))
2762 return FALSE;
2765 /* all documents should now be accounted for, so ignore any changes */
2766 foreach_document (i)
2768 documents[i]->changed = FALSE;
2770 return TRUE;
2774 static void force_close_all(void)
2776 guint i, len = documents_array->len;
2778 /* check all documents have been accounted for */
2779 for (i = 0; i < len; i++)
2781 if (documents[i]->is_valid)
2783 g_return_if_fail(!documents[i]->changed);
2786 main_status.closing_all = TRUE;
2788 foreach_document(i)
2790 document_close(documents[i]);
2793 main_status.closing_all = FALSE;
2797 gboolean document_close_all(void)
2799 if (! document_account_for_unsaved())
2800 return FALSE;
2802 force_close_all();
2804 return TRUE;
2808 static void monitor_reload_file(GeanyDocument *doc)
2810 gchar *base_name = g_path_get_basename(doc->file_name);
2811 gint ret;
2813 ret = dialogs_show_prompt(NULL,
2814 GTK_STOCK_CLOSE, GTK_RESPONSE_CLOSE,
2815 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2816 _("_Reload"), GTK_RESPONSE_ACCEPT,
2817 _("Do you want to reload it?"),
2818 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2819 base_name);
2820 g_free(base_name);
2822 if (ret == GTK_RESPONSE_ACCEPT)
2823 document_reload_file(doc, doc->encoding);
2824 else if (ret == GTK_RESPONSE_CLOSE)
2825 document_close(doc);
2829 static gboolean monitor_resave_missing_file(GeanyDocument *doc)
2831 gboolean want_reload = FALSE;
2832 gboolean file_saved = FALSE;
2833 gint ret;
2835 ret = dialogs_show_prompt(NULL,
2836 _("Close _without saving"), GTK_RESPONSE_CLOSE,
2837 GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
2838 GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
2839 _("Try to resave the file?"),
2840 _("File \"%s\" was not found on disk!"),
2841 doc->file_name);
2842 if (ret == GTK_RESPONSE_ACCEPT)
2844 file_saved = dialogs_show_save_as();
2845 want_reload = TRUE;
2847 else if (ret == GTK_RESPONSE_CLOSE)
2849 document_close(doc);
2851 if (ret != GTK_RESPONSE_CLOSE && ! file_saved)
2853 /* file is missing - set unsaved state */
2854 document_set_text_changed(doc, TRUE);
2855 /* don't prompt more than once */
2856 setptr(doc->real_path, NULL);
2859 return want_reload;
2863 /* Set force to force a disk check, otherwise it is ignored if there was a check
2864 * in the last file_prefs.disk_check_timeout seconds.
2865 * @return @c TRUE if the file has changed. */
2866 gboolean document_check_disk_status(GeanyDocument *doc, gboolean force)
2868 gboolean ret = FALSE;
2869 gboolean use_gio_filemon;
2870 time_t cur_time = 0;
2871 struct stat st;
2872 gchar *locale_filename;
2873 FileDiskStatus old_status;
2875 g_return_val_if_fail(doc != NULL, FALSE);
2877 /* ignore remote files and documents that have never been saved to disk */
2878 if (file_prefs.disk_check_timeout == 0 || doc->real_path == NULL || doc->priv->is_remote)
2879 return FALSE;
2881 use_gio_filemon = (doc->priv->monitor != NULL);
2883 if (use_gio_filemon)
2885 if (doc->priv->file_disk_status != FILE_CHANGED && ! force)
2886 return FALSE;
2888 else
2890 cur_time = time(NULL);
2891 if (! force && doc->priv->last_check > (cur_time - file_prefs.disk_check_timeout))
2892 return FALSE;
2894 doc->priv->last_check = cur_time;
2897 locale_filename = utils_get_locale_from_utf8(doc->file_name);
2898 if (g_stat(locale_filename, &st) != 0)
2900 monitor_resave_missing_file(doc);
2901 /* doc may be closed now */
2902 ret = TRUE;
2904 else if (! use_gio_filemon && /* ignore check when using GIO */
2905 doc->priv->mtime > cur_time)
2907 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC);
2908 /* Note: on Windows st.st_mtime can be newer than cur_time */
2910 else if (doc->priv->mtime < st.st_mtime)
2912 doc->priv->mtime = st.st_mtime;
2913 monitor_reload_file(doc);
2914 /* doc may be closed now */
2915 ret = TRUE;
2917 g_free(locale_filename);
2919 if (DOC_VALID(doc))
2920 { /* doc can get invalid when a document was closed */
2921 old_status = doc->priv->file_disk_status;
2922 doc->priv->file_disk_status = FILE_OK;
2923 if (old_status != doc->priv->file_disk_status)
2924 ui_update_tab_status(doc);
2926 return ret;
2930 /** Compares documents by their display names.
2931 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2932 * @note 'Display name' means the base name of the document's filename.
2934 * @param a @c GeanyDocument**.
2935 * @param b @c GeanyDocument**.
2936 * @warning The arguments take the address of each document pointer.
2937 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2939 * @since 0.21
2941 gint document_compare_by_display_name(gconstpointer a, gconstpointer b)
2943 GeanyDocument *doc_a = *((GeanyDocument**) a);
2944 GeanyDocument *doc_b = *((GeanyDocument**) b);
2945 gchar *base_name_a, *base_name_b;
2946 gint result;
2948 base_name_a = g_path_get_basename(DOC_FILENAME(doc_a));
2949 base_name_b = g_path_get_basename(DOC_FILENAME(doc_b));
2951 result = strcmp(base_name_a, base_name_b);
2953 g_free(base_name_a);
2954 g_free(base_name_b);
2956 return result;
2960 /** Compares documents by their tab order.
2961 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2963 * @param a @c GeanyDocument**.
2964 * @param b @c GeanyDocument**.
2965 * @warning The arguments take the address of each document pointer.
2966 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2968 * @since 0.21 (GEANY_API_VERSION 209)
2970 gint document_compare_by_tab_order(gconstpointer a, gconstpointer b)
2972 GeanyDocument *doc_a = *((GeanyDocument**) a);
2973 GeanyDocument *doc_b = *((GeanyDocument**) b);
2974 gint notebook_position_doc_a;
2975 gint notebook_position_doc_b;
2977 notebook_position_doc_a = document_get_notebook_page(doc_a);
2978 notebook_position_doc_b = document_get_notebook_page(doc_b);
2980 if (notebook_position_doc_a < notebook_position_doc_b)
2981 return -1;
2982 if (notebook_position_doc_a > notebook_position_doc_b)
2983 return 1;
2984 /* equality */
2985 return 0;
2989 /** Compares documents by their tab order, in reverse order.
2990 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2992 * @param a @c GeanyDocument**.
2993 * @param b @c GeanyDocument**.
2994 * @warning The arguments take the address of each document pointer.
2995 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2997 * @since 0.21 (GEANY_API_VERSION 209)
2999 gint document_compare_by_tab_order_reverse(gconstpointer a, gconstpointer b)
3001 GeanyDocument *doc_a = *((GeanyDocument**) a);
3002 GeanyDocument *doc_b = *((GeanyDocument**) b);
3003 gint notebook_position_doc_a;
3004 gint notebook_position_doc_b;
3006 notebook_position_doc_a = document_get_notebook_page(doc_a);
3007 notebook_position_doc_b = document_get_notebook_page(doc_b);
3009 if (notebook_position_doc_a < notebook_position_doc_b)
3010 return 1;
3011 if (notebook_position_doc_a > notebook_position_doc_b)
3012 return -1;
3013 /* equality */
3014 return 0;
3018 void document_grab_focus(GeanyDocument *doc)
3020 g_return_if_fail(doc != NULL);
3022 gtk_widget_grab_focus(GTK_WIDGET(doc->editor->sci));