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.
25 * Document related actions: new, save, open, etc.
26 * Also Scintilla search actions.
31 #ifdef HAVE_SYS_TIME_H
32 # include <sys/time.h>
40 #ifdef HAVE_SYS_TYPES_H
41 # include <sys/types.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*/
55 # undef USE_GIO_FILEMON
60 #include "documentprivate.h"
61 #include "filetypes.h"
63 #include "sciwrappers.h"
66 #include "msgwindow.h"
67 #include "templates.h"
71 #include "encodings.h"
77 #include "highlighting.h"
81 #include "filetypesprivate.h"
84 GeanyFilePrefs file_prefs
;
86 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
87 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
88 * to a document over time, but it might no longer represent a notebook tab. To check this,
89 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
92 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
93 * although usually you would just use the foreach_document() macro.
95 * Never assume that the order of document pointers is the same as the order of notebook tabs.
96 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
97 GPtrArray
*documents_array
= NULL
;
100 /* an undo action, also used for redo actions */
103 GTrashStack
*next
; /* pointer to the next stack element(required for the GTrashStack) */
104 guint type
; /* to identify the action */
105 gpointer
*data
; /* the old value (before the change), in case of a redo action
106 * it contains the new value */
110 static void document_undo_clear(GeanyDocument
*doc
);
111 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
);
112 static gboolean
update_tags_from_buffer(GeanyDocument
*doc
);
115 /* ignore the case of filenames and paths under WIN32, causes errors if not */
117 #define filenamecmp(a, b) utils_str_casecmp((a), (b))
119 #define filenamecmp(a, b) strcmp((a), (b))
123 * Finds a document whose @c real_path field matches the given filename.
125 * @param realname The filename to search, which should be identical to the
126 * string returned by @c tm_get_real_path().
128 * @return The matching document, or @c NULL.
129 * @note This is only really useful when passing a @c TMWorkObject::file_name.
130 * @see GeanyDocument::real_path.
131 * @see document_find_by_filename().
135 GeanyDocument
* document_find_by_real_path(const gchar
*realname
)
140 return NULL
; /* file doesn't exist on disk */
142 for (i
= 0; i
< documents_array
->len
; i
++)
144 GeanyDocument
*doc
= documents
[i
];
146 if (! doc
->is_valid
|| G_UNLIKELY(! doc
->real_path
))
149 if (filenamecmp(realname
, doc
->real_path
) == 0)
158 /* dereference symlinks, /../ junk in path and return locale encoding */
159 static gchar
*get_real_path_from_utf8(const gchar
*utf8_filename
)
161 gchar
*locale_name
= utils_get_locale_from_utf8(utf8_filename
);
162 gchar
*realname
= tm_get_real_path(locale_name
);
170 * Finds a document with the given filename.
171 * This matches either an exact GeanyDocument::file_name string, or variant
172 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
175 * @param utf8_filename The filename to search (in UTF-8 encoding).
177 * @return The matching document, or @c NULL.
178 * @see document_find_by_real_path().
180 GeanyDocument
*document_find_by_filename(const gchar
*utf8_filename
)
186 g_return_val_if_fail(utf8_filename
!= NULL
, NULL
);
188 /* First search GeanyDocument::file_name, so we can find documents with a
189 * filename set but not saved on disk, like vcdiff produces */
190 for (i
= 0; i
< documents_array
->len
; i
++)
194 if (! doc
->is_valid
|| G_UNLIKELY(doc
->file_name
== NULL
))
197 if (filenamecmp(utf8_filename
, doc
->file_name
) == 0)
202 /* Now try matching based on the realpath(), which is unique per file on disk */
203 realname
= get_real_path_from_utf8(utf8_filename
);
204 doc
= document_find_by_real_path(realname
);
210 /* returns the document which has sci, or NULL. */
211 GeanyDocument
*document_find_by_sci(ScintillaObject
*sci
)
215 g_return_val_if_fail(sci
!= NULL
, NULL
);
217 for (i
= 0; i
< documents_array
->len
; i
++)
219 if (documents
[i
]->is_valid
&& documents
[i
]->editor
->sci
== sci
)
226 /** Gets the notebook page index for a document.
227 * @param doc The document.
230 gint
document_get_notebook_page(GeanyDocument
*doc
)
232 g_return_val_if_fail(doc
!= NULL
, -1);
234 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
),
235 GTK_WIDGET(doc
->editor
->sci
));
240 * Finds the document for the given notebook page @a page_num.
242 * @param page_num The notebook page number to search.
244 * @return The corresponding document for the given notebook page, or @c NULL.
246 GeanyDocument
*document_get_from_page(guint page_num
)
248 ScintillaObject
*sci
;
250 if (page_num
>= documents_array
->len
)
253 sci
= (ScintillaObject
*)gtk_notebook_get_nth_page(
254 GTK_NOTEBOOK(main_widgets
.notebook
), page_num
);
256 return document_find_by_sci(sci
);
261 * Finds the current document.
263 * @return A pointer to the current document or @c NULL if there are no opened documents.
265 GeanyDocument
*document_get_current(void)
267 gint cur_page
= gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets
.notebook
));
273 ScintillaObject
*sci
= (ScintillaObject
*)
274 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets
.notebook
), cur_page
);
276 return document_find_by_sci(sci
);
281 void document_init_doclist()
283 documents_array
= g_ptr_array_new();
287 void document_finalize()
289 g_ptr_array_free(documents_array
, TRUE
);
294 * Returns the last part of the filename of the given GeanyDocument. The result is also
295 * truncated to a maximum of @a length characters in case the filename is very long.
297 * @param doc The document to use.
298 * @param length The length of the resulting string or -1 to use a default value.
300 * @return The ellipsized last part of the filename of @a doc, should be freed when no
305 /* TODO make more use of this */
306 gchar
*document_get_basename_for_display(GeanyDocument
*doc
, gint length
)
308 gchar
*base_name
, *short_name
;
310 g_return_val_if_fail(doc
!= NULL
, NULL
);
315 base_name
= g_path_get_basename(DOC_FILENAME(doc
));
316 short_name
= utils_str_middle_truncate(base_name
, length
);
324 void document_update_tab_label(GeanyDocument
*doc
)
329 g_return_if_fail(doc
!= NULL
);
331 short_name
= document_get_basename_for_display(doc
, -1);
333 /* we need to use the event box for the tooltip, labels don't get the necessary events */
334 parent
= gtk_widget_get_parent(doc
->priv
->tab_label
);
335 parent
= gtk_widget_get_parent(parent
);
337 gtk_label_set_text(GTK_LABEL(doc
->priv
->tab_label
), short_name
);
339 ui_widget_set_tooltip_text(parent
, DOC_FILENAME(doc
));
346 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
347 * according to the document's save state.
348 * This is called by Geany mostly when opening or saving files.
350 * @param doc The document to use.
351 * @param changed Whether the document state should indicate changes have been made.
353 void document_set_text_changed(GeanyDocument
*doc
, gboolean changed
)
355 g_return_if_fail(doc
!= NULL
);
357 doc
->changed
= changed
;
359 if (! main_status
.quitting
)
361 ui_update_tab_status(doc
);
362 ui_save_buttons_toggle(changed
);
363 ui_set_window_title(doc
);
364 ui_update_statusbar(doc
, -1);
369 /* Sets is_valid to FALSE and initializes some members to NULL, to mark it uninitialized.
370 * The flag is_valid is set to TRUE in document_create(). */
371 static void init_doc_struct(GeanyDocument
*new_doc
)
373 GeanyDocumentPrivate
*priv
;
375 memset(new_doc
, 0, sizeof(GeanyDocument
));
377 new_doc
->is_valid
= FALSE
;
378 new_doc
->has_tags
= FALSE
;
379 new_doc
->readonly
= FALSE
;
380 new_doc
->file_name
= NULL
;
381 new_doc
->file_type
= NULL
;
382 new_doc
->tm_file
= NULL
;
383 new_doc
->encoding
= NULL
;
384 new_doc
->has_bom
= FALSE
;
385 new_doc
->editor
= NULL
;
386 new_doc
->changed
= FALSE
;
387 new_doc
->real_path
= NULL
;
389 new_doc
->priv
= g_new0(GeanyDocumentPrivate
, 1);
390 priv
= new_doc
->priv
;
391 priv
->tag_store
= NULL
;
392 priv
->tag_tree
= NULL
;
393 priv
->saved_encoding
.encoding
= NULL
;
394 priv
->saved_encoding
.has_bom
= FALSE
;
395 priv
->undo_actions
= NULL
;
396 priv
->redo_actions
= NULL
;
397 priv
->line_count
= 0;
398 #if ! defined(USE_GIO_FILEMON)
399 priv
->last_check
= time(NULL
);
404 /* returns the next free place in the document list,
405 * or -1 if the documents_array is full */
406 static gint
document_get_new_idx(void)
410 for (i
= 0; i
< documents_array
->len
; i
++)
412 if (documents
[i
]->editor
== NULL
)
421 static void queue_colourise(GeanyDocument
*doc
)
423 /* Colourise the editor before it is next drawn */
424 doc
->priv
->colourise_needed
= TRUE
;
426 /* If the editor doesn't need drawing (e.g. after saving the current
427 * document), we need to force a redraw, so the expose event is triggered.
428 * This ensures we don't start colourising before all documents are opened/saved,
429 * only once the editor is drawn. */
430 gtk_widget_queue_draw(GTK_WIDGET(doc
->editor
->sci
));
435 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor
*monitor
, G_GNUC_UNUSED GFile
*file
,
436 G_GNUC_UNUSED GFile
*other_file
, GFileMonitorEvent event
,
439 g_return_if_fail(doc
!= NULL
);
441 if (file_prefs
.disk_check_timeout
== 0)
444 geany_debug("%s: event: %d previous file status: %d",
445 G_STRFUNC
, event
, doc
->priv
->file_disk_status
);
448 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT
:
450 if (doc
->priv
->file_disk_status
== FILE_IGNORE
)
451 doc
->priv
->file_disk_status
= FILE_OK
;
453 doc
->priv
->file_disk_status
= FILE_CHANGED
;
454 g_message("%s: FILE_CHANGED", G_STRFUNC
);
457 case G_FILE_MONITOR_EVENT_DELETED
:
459 doc
->priv
->file_disk_status
= FILE_CHANGED
;
460 g_message("%s: FILE_MISSING", G_STRFUNC
);
466 if (doc
->priv
->file_disk_status
!= FILE_OK
)
468 ui_update_tab_status(doc
);
474 static void document_stop_file_monitoring(GeanyDocument
*doc
)
476 g_return_if_fail(doc
!= NULL
);
478 if (doc
->priv
->monitor
!= NULL
)
480 g_object_unref(doc
->priv
->monitor
);
481 doc
->priv
->monitor
= NULL
;
486 static void monitor_file_setup(GeanyDocument
*doc
)
488 g_return_if_fail(doc
!= NULL
);
489 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
490 * doesn't work at all for remote files and legacy polling is too slow. */
491 if (! doc
->priv
->is_remote
)
494 gchar
*locale_filename
;
496 /* stop any previous monitoring */
497 document_stop_file_monitoring(doc
);
499 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
500 if (locale_filename
!= NULL
&& g_file_test(locale_filename
, G_FILE_TEST_EXISTS
))
502 /* get a file monitor and connect to the 'changed' signal */
503 GFile
*file
= g_file_new_for_path(locale_filename
);
504 doc
->priv
->monitor
= g_file_monitor_file(file
, G_FILE_MONITOR_NONE
, NULL
, NULL
);
505 g_signal_connect(doc
->priv
->monitor
, "changed",
506 G_CALLBACK(monitor_file_changed_cb
), doc
);
508 /* we set the rate limit according to the GUI pref but it's most probably not used */
509 g_file_monitor_set_rate_limit(doc
->priv
->monitor
, file_prefs
.disk_check_timeout
* 1000);
511 g_object_unref(file
);
513 g_free(locale_filename
);
516 doc
->priv
->file_disk_status
= FILE_OK
;
520 void document_try_focus(GeanyDocument
*doc
, GtkWidget
*source_widget
)
522 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
525 GtkWidget
*sci
= GTK_WIDGET(doc
->editor
->sci
);
526 GtkWidget
*focusw
= gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
));
528 if (source_widget
== NULL
)
529 source_widget
= doc
->priv
->tag_tree
;
531 if (focusw
== source_widget
)
532 gtk_widget_grab_focus(sci
);
537 static gboolean
on_idle_focus(gpointer doc
)
539 document_try_focus(doc
, NULL
);
544 static gboolean
remove_page(guint page_num
);
546 /* Creates a new document and editor, adding a tab in the notebook.
547 * @return The created document */
548 static GeanyDocument
*document_create(const gchar
*utf8_filename
)
552 gint cur_pages
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
556 GeanyDocument
*cur
= document_get_current();
557 /* remove the empty document first */
558 if (cur
!= NULL
&& cur
->file_name
== NULL
&& ! cur
->changed
)
559 /* prevent immediately opening another new doc with
560 * new_document_after_close pref */
564 new_idx
= document_get_new_idx();
565 if (new_idx
== -1) /* expand the array, no free places */
567 GeanyDocument
*new_doc
= g_new0(GeanyDocument
, 1);
569 new_idx
= documents_array
->len
;
570 g_ptr_array_add(documents_array
, new_doc
);
572 doc
= documents
[new_idx
];
573 init_doc_struct(doc
); /* initialize default document settings */
574 doc
->index
= new_idx
;
576 doc
->file_name
= g_strdup(utf8_filename
);
578 doc
->editor
= editor_create(doc
);
580 sidebar_openfiles_add(doc
); /* sets doc->iter */
582 notebook_new_tab(doc
);
584 /* select document in sidebar */
586 GtkTreeSelection
*sel
;
588 sel
= gtk_tree_view_get_selection(GTK_TREE_VIEW(tv
.tree_openfiles
));
589 gtk_tree_selection_select_iter(sel
, &doc
->priv
->iter
);
592 ui_document_buttons_update();
594 doc
->is_valid
= TRUE
; /* do this last to prevent UI updating with NULL items. */
600 * Closes the given document.
602 * @param doc The document to remove.
604 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
608 gboolean
document_close(GeanyDocument
*doc
)
610 g_return_val_if_fail(doc
, FALSE
);
612 return document_remove_page(document_get_notebook_page(doc
));
616 /* Call document_remove_page() instead, this is only needed for document_create(). */
617 static gboolean
remove_page(guint page_num
)
619 GeanyDocument
*doc
= document_get_from_page(page_num
);
621 if (G_UNLIKELY(doc
== NULL
))
623 g_warning("%s: page_num: %d", G_STRFUNC
, page_num
);
627 if (doc
->changed
&& ! dialogs_show_unsaved_file(doc
))
632 /* tell any plugins that the document is about to be closed */
633 g_signal_emit_by_name(geany_object
, "document-close", doc
);
635 /* Checking real_path makes it likely the file exists on disk */
636 if (! main_status
.closing_all
&& doc
->real_path
!= NULL
)
637 ui_add_recent_file(doc
->file_name
);
639 doc
->is_valid
= FALSE
;
641 if (! main_status
.quitting
)
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
));
648 g_free(doc
->encoding
);
649 g_free(doc
->priv
->saved_encoding
.encoding
);
650 g_free(doc
->file_name
);
651 g_free(doc
->real_path
);
652 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
654 editor_destroy(doc
->editor
);
657 document_stop_file_monitoring(doc
);
659 doc
->file_name
= NULL
;
660 doc
->real_path
= NULL
;
661 doc
->file_type
= NULL
;
662 doc
->encoding
= NULL
;
663 doc
->has_bom
= FALSE
;
665 document_undo_clear(doc
);
668 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
670 sidebar_update_tag_list(NULL
, FALSE
);
671 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
672 ui_set_window_title(NULL
);
673 ui_save_buttons_toggle(FALSE
);
674 ui_update_popup_reundo_items(NULL
);
675 ui_document_buttons_update();
676 build_menu_update(NULL
);
683 * Removes the given notebook tab at @a page_num and clears all related information
684 * in the document list.
686 * @param page_num The notebook page number to remove.
688 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
690 gboolean
document_remove_page(guint page_num
)
692 gboolean done
= remove_page(page_num
);
694 if (done
&& ui_prefs
.new_document_after_close
)
695 document_new_file_if_non_open();
701 /* used to keep a record of the unchanged document state encoding */
702 static void store_saved_encoding(GeanyDocument
*doc
)
704 g_free(doc
->priv
->saved_encoding
.encoding
);
705 doc
->priv
->saved_encoding
.encoding
= g_strdup(doc
->encoding
);
706 doc
->priv
->saved_encoding
.has_bom
= doc
->has_bom
;
710 /* Opens a new empty document only if there are no other documents open */
711 GeanyDocument
*document_new_file_if_non_open(void)
713 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
714 return document_new_file(NULL
, NULL
, NULL
);
721 * Creates a new document.
722 * Line endings in @a text will be converted to the default setting.
723 * Afterwards, the @c "document-new" signal is emitted for plugins.
725 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
726 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
727 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
729 * @return The new document.
731 GeanyDocument
*document_new_file(const gchar
*utf8_filename
, GeanyFiletype
*ft
, const gchar
*text
)
735 if (utf8_filename
&& g_path_is_absolute(utf8_filename
))
738 tmp
= utils_strdupa(utf8_filename
); /* work around const */
739 utils_tidy_path(tmp
);
742 doc
= document_create(utf8_filename
);
744 g_assert(doc
!= NULL
);
746 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
749 GString
*template = g_string_new(text
);
750 utils_ensure_same_eol_characters(template, file_prefs
.default_eol_character
);
752 sci_set_text(doc
->editor
->sci
, template->str
);
753 g_string_free(template, TRUE
);
756 sci_clear_all(doc
->editor
->sci
);
758 sci_set_eol_mode(doc
->editor
->sci
, file_prefs
.default_eol_character
);
760 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
761 sci_empty_undo_buffer(doc
->editor
->sci
);
763 doc
->encoding
= g_strdup(encodings
[file_prefs
.default_new_encoding
].charset
);
764 /* store the opened encoding for undo/redo */
765 store_saved_encoding(doc
);
767 if (ft
== NULL
&& utf8_filename
!= NULL
) /* guess the filetype from the filename if one is given */
768 ft
= filetypes_detect_from_document(doc
);
770 document_set_filetype(doc
, ft
); /* also clears taglist */
772 ui_set_window_title(doc
);
773 build_menu_update(doc
);
774 document_update_tag_list(doc
, FALSE
);
775 document_set_text_changed(doc
, FALSE
);
776 ui_document_show_hide(doc
); /* update the document menu */
778 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
779 /* bring it in front, jump to the start and grab the focus */
780 editor_goto_pos(doc
->editor
, 0, FALSE
);
781 document_try_focus(doc
, NULL
);
784 monitor_file_setup(doc
);
786 doc
->priv
->mtime
= time(NULL
);
789 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
790 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
), doc
->editor
);
792 g_signal_emit_by_name(geany_object
, "document-new", doc
);
794 msgwin_status_add(_("New file \"%s\" opened."),
802 * Opens a document specified by @a locale_filename.
803 * Afterwards, the @c "document-open" signal is emitted for plugins.
805 * @param locale_filename The filename of the document to load, in locale encoding.
806 * @param readonly Whether to open the document in read-only mode.
807 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
808 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
810 * @return The document opened or @c NULL.
812 GeanyDocument
*document_open_file(const gchar
*locale_filename
, gboolean readonly
,
813 GeanyFiletype
*ft
, const gchar
*forced_enc
)
815 return document_open_file_full(NULL
, locale_filename
, 0, readonly
, ft
, forced_enc
);
821 gchar
*data
; /* null-terminated file data */
822 gsize size
; /* actual file size on disk */
823 gsize len
; /* string length of data */
826 time_t mtime
; /* modification time, read by stat::st_mtime */
831 /* reload file with specified encoding */
833 handle_forced_encoding(FileData
*filedata
, const gchar
*forced_enc
)
835 GeanyEncodingIndex enc_idx
;
837 if (utils_str_equal(forced_enc
, "UTF-8"))
839 if (! g_utf8_validate(filedata
->data
, filedata
->len
, NULL
))
846 gchar
*converted_text
= encodings_convert_to_utf8_from_charset(
847 filedata
->data
, filedata
->size
, forced_enc
, FALSE
);
848 if (converted_text
== NULL
)
854 g_free(filedata
->data
);
855 filedata
->data
= converted_text
;
856 filedata
->len
= strlen(converted_text
);
859 enc_idx
= encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, NULL
);
860 filedata
->bom
= (enc_idx
== GEANY_ENCODING_UTF_8
);
861 filedata
->enc
= g_strdup(forced_enc
);
866 /* detect encoding and convert to UTF-8 if necessary */
868 handle_encoding(FileData
*filedata
, GeanyEncodingIndex enc_idx
)
870 g_return_val_if_fail(filedata
->enc
== NULL
, FALSE
);
871 g_return_val_if_fail(filedata
->bom
== FALSE
, FALSE
);
873 if (filedata
->size
== 0)
875 /* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
876 * e.g. UTF32 file with a BOM(so size is 4, len is 0) */
877 filedata
->enc
= g_strdup("UTF-8");
881 /* first check for a BOM */
882 if (enc_idx
!= GEANY_ENCODING_NONE
)
884 filedata
->enc
= g_strdup(encodings
[enc_idx
].charset
);
885 filedata
->bom
= TRUE
;
887 if (enc_idx
!= GEANY_ENCODING_UTF_8
) /* the BOM indicated something else than UTF-8 */
889 gchar
*converted_text
= encodings_convert_to_utf8_from_charset(
890 filedata
->data
, filedata
->size
, filedata
->enc
, FALSE
);
891 if (converted_text
!= NULL
)
893 g_free(filedata
->data
);
894 filedata
->data
= converted_text
;
895 filedata
->len
= strlen(converted_text
);
899 /* there was a problem converting data from BOM encoding type */
900 g_free(filedata
->enc
);
901 filedata
->enc
= NULL
;
902 filedata
->bom
= FALSE
;
907 if (filedata
->enc
== NULL
) /* either there was no BOM or the BOM encoding failed */
909 /* try UTF-8 first */
910 if ((filedata
->size
== filedata
->len
) &&
911 g_utf8_validate(filedata
->data
, filedata
->len
, NULL
))
913 filedata
->enc
= g_strdup("UTF-8");
917 /* detect the encoding */
918 gchar
*converted_text
= encodings_convert_to_utf8(filedata
->data
,
919 filedata
->size
, &filedata
->enc
);
921 if (converted_text
== NULL
)
925 g_free(filedata
->data
);
926 filedata
->data
= converted_text
;
927 filedata
->len
= strlen(converted_text
);
936 handle_bom(FileData
*filedata
)
940 encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, &bom_len
);
941 g_return_if_fail(bom_len
!= 0);
943 /* use filedata->len here because the contents are already converted into UTF-8 */
944 filedata
->len
-= bom_len
;
945 /* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
946 g_memmove(filedata
->data
, filedata
->data
+ bom_len
, filedata
->len
+ 1);
947 filedata
->data
= g_realloc(filedata
->data
, filedata
->len
+ 1);
951 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
952 static gboolean
load_text_file(const gchar
*locale_filename
, const gchar
*display_filename
,
953 FileData
*filedata
, const gchar
*forced_enc
)
957 GeanyEncodingIndex tmp_enc_idx
;
959 filedata
->data
= NULL
;
961 filedata
->enc
= NULL
;
962 filedata
->bom
= FALSE
;
963 filedata
->readonly
= FALSE
;
965 if (g_stat(locale_filename
, &st
) != 0)
967 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"),
968 display_filename
, g_strerror(errno
));
972 filedata
->mtime
= st
.st_mtime
;
974 if (! g_file_get_contents(locale_filename
, &filedata
->data
, NULL
, &err
))
976 ui_set_statusbar(TRUE
, "%s", err
->message
);
981 /* use strlen to check for null chars */
982 filedata
->size
= (gsize
) st
.st_size
;
983 filedata
->len
= strlen(filedata
->data
);
985 /* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
986 * if we have a BOM */
987 tmp_enc_idx
= encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, NULL
);
989 /* check whether the size of the loaded data is equal to the size of the file in the
990 * filesystem file size may be 0 to allow opening files in /proc/ which have typically a
991 * file size of 0 bytes */
992 if (filedata
->len
!= filedata
->size
&& filedata
->size
!= 0 && (
993 tmp_enc_idx
== GEANY_ENCODING_UTF_8
|| /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
994 tmp_enc_idx
== GEANY_ENCODING_UTF_7
)) /* filter UTF-7/8 where no NULL bytes are allowed */
996 const gchar
*warn_msg
= _(
997 "The file \"%s\" could not be opened properly and has been truncated. " \
998 "This can occur if the file contains a NULL byte. " \
999 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1001 if (main_status
.main_window_realized
)
1002 dialogs_show_msgbox(GTK_MESSAGE_WARNING
, warn_msg
, display_filename
);
1004 ui_set_statusbar(TRUE
, warn_msg
, display_filename
);
1006 /* set the file to read-only mode because saving it is probably dangerous */
1007 filedata
->readonly
= TRUE
;
1010 /* Determine character encoding and convert to UTF-8 */
1011 if (forced_enc
!= NULL
)
1013 /* the encoding should be ignored(requested by user), so open the file "as it is" */
1014 if (utils_str_equal(forced_enc
, encodings
[GEANY_ENCODING_NONE
].charset
))
1016 filedata
->bom
= FALSE
;
1017 filedata
->enc
= g_strdup(encodings
[GEANY_ENCODING_NONE
].charset
);
1019 else if (! handle_forced_encoding(filedata
, forced_enc
))
1021 /* For translators: the second wildcard is an encoding name, e.g.
1022 * The file \"test.txt\" is not valid UTF-8. */
1023 ui_set_statusbar(TRUE
, _("The file \"%s\" is not valid %s."),
1024 display_filename
, forced_enc
);
1026 g_free(filedata
->data
);
1030 else if (! handle_encoding(filedata
, tmp_enc_idx
))
1032 ui_set_statusbar(TRUE
,
1033 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1036 g_free(filedata
->data
);
1041 handle_bom(filedata
);
1046 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1047 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1048 * if cl_options.goto_column is set.
1050 * returns the new position which may have changed */
1051 static gint
set_cursor_position(GeanyEditor
*editor
, gint pos
)
1053 if (cl_options
.goto_line
>= 0)
1054 { /* goto line which was specified on command line and then undefine the line */
1055 sci_goto_line(editor
->sci
, cl_options
.goto_line
- 1, TRUE
);
1056 editor
->scroll_percent
= 0.5F
;
1057 cl_options
.goto_line
= -1;
1061 sci_set_current_position(editor
->sci
, pos
, FALSE
);
1062 editor
->scroll_percent
= 0.5F
;
1065 if (cl_options
.goto_column
>= 0)
1066 { /* goto column which was specified on command line and then undefine the column */
1068 gint new_pos
= sci_get_current_position(editor
->sci
) + cl_options
.goto_column
;
1069 sci_set_current_position(editor
->sci
, new_pos
, FALSE
);
1070 editor
->scroll_percent
= 0.5F
;
1071 cl_options
.goto_column
= -1;
1074 return sci_get_current_position(editor
->sci
);
1078 /* Count lines that start with some hard tabs then a soft tab. */
1079 static gboolean
detect_tabs_and_spaces(GeanyEditor
*editor
)
1081 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1082 ScintillaObject
*sci
= editor
->sci
;
1084 struct Sci_TextToFind ttf
;
1085 gchar
*soft_tab
= g_strnfill(iprefs
->width
, ' ');
1086 gchar
*regex
= g_strconcat("^\t+", soft_tab
, "[^ ]", NULL
);
1091 ttf
.chrg
.cpMax
= sci_get_length(sci
);
1092 ttf
.lpstrText
= regex
;
1097 pos
= sci_find_text(sci
, SCFIND_REGEXP
, &ttf
);
1099 break; /* no more matches */
1101 ttf
.chrg
.cpMin
= ttf
.chrgText
.cpMax
+ 1; /* search after this match */
1104 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1105 return count
> sci_get_line_count(sci
) * 0.02;
1109 /* Detect the indent type based on counting the leading indent characters for each line. */
1110 static GeanyIndentType
detect_indent_type(GeanyEditor
*editor
)
1112 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1113 ScintillaObject
*sci
= editor
->sci
;
1114 guint line
, line_count
;
1115 gsize tabs
= 0, spaces
= 0;
1117 if (detect_tabs_and_spaces(editor
))
1118 return GEANY_INDENT_TYPE_BOTH
;
1120 line_count
= sci_get_line_count(sci
);
1121 for (line
= 0; line
< line_count
; line
++)
1123 gint pos
= sci_get_position_from_line(sci
, line
);
1126 /* most code will have indent total <= 24, otherwise it's more likely to be
1127 * alignment than indentation */
1128 if (sci_get_line_indentation(sci
, line
) > 24)
1131 c
= sci_get_char_at(sci
, pos
);
1137 /* check for at least 2 spaces */
1138 if (sci_get_char_at(sci
, pos
+ 1) == ' ')
1142 if (spaces
== 0 && tabs
== 0)
1143 return iprefs
->type
;
1145 /* the factors may need to be tweaked */
1146 if (spaces
> tabs
* 4)
1147 return GEANY_INDENT_TYPE_SPACES
;
1148 else if (tabs
> spaces
* 4)
1149 return GEANY_INDENT_TYPE_TABS
;
1151 return GEANY_INDENT_TYPE_BOTH
;
1155 void document_apply_indent_settings(GeanyDocument
*doc
)
1157 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
1158 GeanyIndentType type
= iprefs
->type
;
1160 switch (doc
->file_type
->id
)
1162 case GEANY_FILETYPES_MAKE
:
1163 /* force using tabs for indentation for Makefiles */
1164 editor_set_indent(doc
->editor
, GEANY_INDENT_TYPE_TABS
, iprefs
->width
);
1166 case GEANY_FILETYPES_F77
:
1167 /* force using spaces for indentation for Fortran 77 */
1168 editor_set_indent(doc
->editor
, GEANY_INDENT_TYPE_SPACES
, iprefs
->width
);
1173 if (iprefs
->detect_type
)
1175 type
= detect_indent_type(doc
->editor
);
1177 if (type
!= iprefs
->type
)
1179 const gchar
*name
= NULL
;
1183 case GEANY_INDENT_TYPE_SPACES
:
1186 case GEANY_INDENT_TYPE_TABS
:
1189 case GEANY_INDENT_TYPE_BOTH
:
1190 name
= _("Tabs and Spaces");
1193 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1194 * and Spaces), the second one is the filename */
1195 ui_set_statusbar(TRUE
, _("Setting %s indentation mode for %s."), name
,
1199 editor_set_indent(doc
->editor
, type
, iprefs
->width
);
1204 static gboolean
auto_update_tag_list(gpointer data
)
1206 GeanyDocument
*doc
= data
;
1208 if (! doc
|| ! doc
->is_valid
|| doc
->tm_file
== NULL
)
1211 if (gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
)) != GTK_WIDGET(doc
->editor
->sci
))
1214 if (update_tags_from_buffer(doc
))
1215 sidebar_update_tag_list(doc
, TRUE
);
1222 /* To open a new file, set doc to NULL; filename should be locale encoded.
1223 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1224 * pos is the cursor position, which can be overridden by --line and --column.
1225 * forced_enc can be NULL to detect the file encoding.
1226 * Returns: doc of the opened file or NULL if an error occurred. */
1227 GeanyDocument
*document_open_file_full(GeanyDocument
*doc
, const gchar
*filename
, gint pos
,
1228 gboolean readonly
, GeanyFiletype
*ft
, const gchar
*forced_enc
)
1231 gboolean reload
= (doc
== NULL
) ? FALSE
: TRUE
;
1232 gchar
*utf8_filename
= NULL
;
1233 gchar
*display_filename
= NULL
;
1234 gchar
*locale_filename
= NULL
;
1235 GeanyFiletype
*use_ft
;
1240 utf8_filename
= g_strdup(doc
->file_name
);
1241 locale_filename
= utils_get_locale_from_utf8(utf8_filename
);
1245 /* filename must not be NULL when opening a file */
1246 if (filename
== NULL
)
1248 ui_set_statusbar(FALSE
, _("Invalid filename"));
1253 /* if filename is a shortcut, try to resolve it */
1254 locale_filename
= win32_get_shortcut_target(filename
);
1256 locale_filename
= g_strdup(filename
);
1258 /* remove relative junk */
1259 utils_tidy_path(locale_filename
);
1261 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1262 utf8_filename
= utils_get_utf8_from_locale(locale_filename
);
1264 /* if file is already open, switch to it and go */
1265 doc
= document_find_by_filename(utf8_filename
);
1268 ui_add_recent_file(utf8_filename
); /* either add or reorder recent item */
1269 /* show the doc before reload dialog */
1270 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets
.notebook
),
1271 gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
),
1272 (GtkWidget
*) doc
->editor
->sci
));
1273 document_check_disk_status(doc
, TRUE
); /* force a file changed check */
1276 if (reload
|| doc
== NULL
)
1277 { /* doc possibly changed */
1278 display_filename
= utils_str_middle_truncate(utf8_filename
, 100);
1280 if (! load_text_file(locale_filename
, display_filename
, &filedata
, forced_enc
))
1282 g_free(display_filename
);
1283 g_free(utf8_filename
);
1284 g_free(locale_filename
);
1290 doc
= document_create(utf8_filename
);
1291 g_return_val_if_fail(doc
!= NULL
, NULL
); /* really should not happen */
1293 /* file exists on disk, set real_path */
1294 setptr(doc
->real_path
, tm_get_real_path(locale_filename
));
1296 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1297 monitor_file_setup(doc
);
1300 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
1301 sci_empty_undo_buffer(doc
->editor
->sci
);
1303 /* add the text to the ScintillaObject */
1304 sci_set_readonly(doc
->editor
->sci
, FALSE
); /* to allow replacing text */
1305 sci_set_text(doc
->editor
->sci
, filedata
.data
); /* NULL terminated data */
1306 queue_colourise(doc
); /* Ensure the document gets colourised. */
1308 /* detect & set line endings */
1309 editor_mode
= utils_get_line_endings(filedata
.data
, filedata
.len
);
1310 sci_set_eol_mode(doc
->editor
->sci
, editor_mode
);
1311 g_free(filedata
.data
);
1313 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
1315 doc
->priv
->mtime
= filedata
.mtime
; /* get the modification time from file and keep it */
1316 g_free(doc
->encoding
); /* if reloading, free old encoding */
1317 doc
->encoding
= filedata
.enc
;
1318 doc
->has_bom
= filedata
.bom
;
1319 store_saved_encoding(doc
); /* store the opened encoding for undo/redo */
1321 doc
->readonly
= readonly
|| filedata
.readonly
;
1322 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
1324 /* update line number margin width */
1325 doc
->priv
->line_count
= sci_get_line_count(doc
->editor
->sci
);
1326 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
1331 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1332 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
),
1335 use_ft
= (ft
!= NULL
) ? ft
: filetypes_detect_from_document(doc
);
1339 document_undo_clear(doc
);
1343 /* update taglist, typedef keywords and build menu if necessary */
1344 document_set_filetype(doc
, use_ft
);
1346 /* set indentation settings after setting the filetype */
1348 editor_set_indent(doc
->editor
, doc
->editor
->indent_type
, doc
->editor
->indent_width
); /* resetup sci */
1350 document_apply_indent_settings(doc
);
1352 document_set_text_changed(doc
, FALSE
); /* also updates tab state */
1353 ui_document_show_hide(doc
); /* update the document menu */
1355 /* finally add current file to recent files menu, but not the files from the last session */
1356 if (! main_status
.opening_session_files
)
1357 ui_add_recent_file(utf8_filename
);
1360 g_signal_emit_by_name(geany_object
, "document-open", doc
);
1363 ui_set_statusbar(TRUE
, _("File %s reloaded."), display_filename
);
1365 /* For translators: this is the status window message for opening a file. %d is the number
1366 * of the newly opened file, %s indicates whether the file is opened read-only
1367 * (it is replaced with the string ", read-only"). */
1368 msgwin_status_add(_("File %s opened(%d%s)."),
1369 display_filename
, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)),
1370 (readonly
) ? _(", read-only") : "");
1373 g_free(display_filename
);
1374 g_free(utf8_filename
);
1375 g_free(locale_filename
);
1377 /* TODO This could be used to automatically update the symbol list,
1378 * based on a configurable interval */
1379 /*g_timeout_add(10000, auto_update_tag_list, doc);*/
1381 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1382 pos
= set_cursor_position(doc
->editor
, pos
);
1383 /* now bring the file in front */
1384 editor_goto_pos(doc
->editor
, pos
, FALSE
);
1386 /* finally, let the editor widget grab the focus so you can start coding
1388 g_idle_add(on_idle_focus
, doc
);
1393 /* Takes a new line separated list of filename URIs and opens each file.
1394 * length is the length of the string or -1 if it should be detected */
1395 void document_open_file_list(const gchar
*data
, gssize length
)
1401 g_return_if_fail(data
!= NULL
);
1404 length
= strlen(data
);
1406 switch (utils_get_line_endings(data
, length
))
1408 case SC_EOL_CR
: list
= g_strsplit(data
, "\r", 0); break;
1409 case SC_EOL_CRLF
: list
= g_strsplit(data
, "\r\n", 0); break;
1410 case SC_EOL_LF
: list
= g_strsplit(data
, "\n", 0); break;
1411 default: list
= g_strsplit(data
, "\n", 0);
1416 if (list
[i
] == NULL
)
1418 filename
= g_filename_from_uri(list
[i
], NULL
, NULL
);
1419 if (G_UNLIKELY(filename
== NULL
))
1421 document_open_file(filename
, FALSE
, NULL
, NULL
);
1430 * Opens each file in the list @a filenames.
1431 * Internally, document_open_file() is called for every list item.
1433 * @param filenames A list of filenames to load, in locale encoding.
1434 * @param readonly Whether to open the document in read-only mode.
1435 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1436 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1438 void document_open_files(const GSList
*filenames
, gboolean readonly
, GeanyFiletype
*ft
,
1439 const gchar
*forced_enc
)
1443 for (item
= filenames
; item
!= NULL
; item
= g_slist_next(item
))
1445 document_open_file(item
->data
, readonly
, ft
, forced_enc
);
1451 * Reloads the document with the specified file encoding
1452 * @a forced_enc or @c NULL to auto-detect the file encoding.
1454 * @param doc The document to reload.
1455 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1457 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1459 gboolean
document_reload_file(GeanyDocument
*doc
, const gchar
*forced_enc
)
1462 GeanyDocument
*new_doc
;
1464 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1466 /* try to set the cursor to the position before reloading */
1467 pos
= sci_get_current_position(doc
->editor
->sci
);
1468 new_doc
= document_open_file_full(doc
, NULL
, pos
, doc
->readonly
, doc
->file_type
, forced_enc
);
1470 return (new_doc
!= NULL
);
1474 static gboolean
document_update_timestamp(GeanyDocument
*doc
, const gchar
*locale_filename
)
1476 #if ! USE_GIO_FILEMON
1479 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1481 /* stat the file to get the timestamp, otherwise on Windows the actual
1482 * timestamp can be ahead of time(NULL) */
1483 if (g_stat(locale_filename
, &st
) != 0)
1485 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"), doc
->file_name
,
1490 doc
->priv
->mtime
= st
.st_mtime
; /* get the modification time from file and keep it */
1496 /* Sets line and column to the given position byte_pos in the document.
1497 * byte_pos is the position counted in bytes, not characters */
1498 static void get_line_column_from_pos(GeanyDocument
*doc
, guint byte_pos
, gint
*line
, gint
*column
)
1503 /* for some reason we can use byte count instead of character count here */
1504 *line
= sci_get_line_from_position(doc
->editor
->sci
, byte_pos
);
1505 line_start
= sci_get_position_from_line(doc
->editor
->sci
, *line
);
1506 /* get the column in the line */
1507 *column
= byte_pos
- line_start
;
1509 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1510 * skip one byte(i++) and decrease the column number which is based on byte count */
1511 for (i
= line_start
; i
< (line_start
+ *column
); i
++)
1513 if (sci_get_char_at(doc
->editor
->sci
, i
) < 0)
1522 static void replace_header_filename(GeanyDocument
*doc
)
1526 struct Sci_TextToFind ttf
;
1528 g_return_if_fail(doc
!= NULL
);
1529 g_return_if_fail(doc
->file_type
!= NULL
);
1531 if (doc
->file_type
->extension
)
1532 filebase
= g_strconcat("\\<", GEANY_STRING_UNTITLED
, "\\.\\w+", NULL
);
1534 filebase
= g_strdup(GEANY_STRING_UNTITLED
);
1536 filename
= g_path_get_basename(doc
->file_name
);
1538 /* only search the first 3 lines */
1540 ttf
.chrg
.cpMax
= sci_get_position_from_line(doc
->editor
->sci
, 3);
1541 ttf
.lpstrText
= filebase
;
1543 if (search_find_text(doc
->editor
->sci
, SCFIND_MATCHCASE
| SCFIND_REGEXP
, &ttf
) != -1)
1545 sci_set_target_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1546 sci_set_target_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1547 sci_replace_target(doc
->editor
->sci
, filename
, FALSE
);
1555 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1556 * you still have to call @ref document_save_file_as() to change the @a doc object.
1557 * It also stops monitoring for file changes to prevent receiving too many file change events
1558 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1560 * @param doc The current document which should be renamed.
1561 * @param new_filename The new filename in UTF-8 encoding.
1565 void document_rename_file(GeanyDocument
*doc
, const gchar
*new_filename
)
1567 gchar
*old_locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1568 gchar
*new_locale_filename
= utils_get_locale_from_utf8(new_filename
);
1571 /* stop file monitoring to avoid getting events for deleting/creating files,
1572 * it's re-setup in document_save_file_as() */
1573 document_stop_file_monitoring(doc
);
1575 result
= g_rename(old_locale_filename
, new_locale_filename
);
1578 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
,
1579 _("Error renaming file."), g_strerror(errno
));
1581 g_free(old_locale_filename
);
1582 g_free(new_locale_filename
);
1586 /* Return TRUE if the document doesn't have a full filename set.
1587 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1588 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1590 gboolean
document_need_save_as(GeanyDocument
*doc
)
1592 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1594 return (doc
->file_name
== NULL
|| !g_path_is_absolute(doc
->file_name
));
1599 * Saves the document, detecting the filetype.
1601 * @param doc The document for the file to save.
1602 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1603 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1605 * @see document_save_file().
1609 gboolean
document_save_file_as(GeanyDocument
*doc
, const gchar
*utf8_fname
)
1613 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1615 if (utf8_fname
!= NULL
)
1616 setptr(doc
->file_name
, g_strdup(utf8_fname
));
1618 /* reset real path, it's retrieved again in document_save() */
1619 setptr(doc
->real_path
, NULL
);
1621 /* detect filetype */
1622 if (doc
->file_type
->id
== GEANY_FILETYPES_NONE
)
1624 GeanyFiletype
*ft
= filetypes_detect_from_document(doc
);
1626 document_set_filetype(doc
, ft
);
1627 if (document_get_current() == doc
)
1629 ignore_callback
= TRUE
;
1630 filetypes_select_radio_item(doc
->file_type
);
1631 ignore_callback
= FALSE
;
1634 replace_header_filename(doc
);
1636 ret
= document_save_file(doc
, TRUE
);
1638 /* file monitoring support, add file monitoring after the file has been saved
1639 * to ignore any earlier events */
1640 monitor_file_setup(doc
);
1641 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1644 ui_add_recent_file(doc
->file_name
);
1649 static gsize
save_convert_to_encoding(GeanyDocument
*doc
, gchar
**data
, gsize
*len
)
1651 GError
*conv_error
= NULL
;
1652 gchar
* conv_file_contents
= NULL
;
1656 g_return_val_if_fail(data
!= NULL
|| *data
== NULL
, FALSE
);
1657 g_return_val_if_fail(len
!= NULL
, FALSE
);
1659 /* try to convert it from UTF-8 to original encoding */
1660 conv_file_contents
= g_convert(*data
, *len
- 1, doc
->encoding
, "UTF-8",
1661 &bytes_read
, &conv_len
, &conv_error
);
1663 if (conv_error
!= NULL
)
1665 gchar
*text
= g_strdup_printf(
1666 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1670 if (conv_error
->code
== G_CONVERT_ERROR_ILLEGAL_SEQUENCE
)
1672 gchar
*context
= NULL
;
1676 /* don't read over the doc length */
1677 gint max_len
= MIN((gint
)bytes_read
+ 6, (gint
)*len
- 1);
1678 context
= g_malloc(7); /* read 6 bytes from Sci + '\0' */
1679 sci_get_text_range(doc
->editor
->sci
, bytes_read
, max_len
, context
);
1681 /* take only one valid Unicode character from the context and discard the leftover */
1682 unic
= g_utf8_get_char_validated(context
, -1);
1683 context_len
= g_unichar_to_utf8(unic
, context
);
1684 context
[context_len
] = '\0';
1685 get_line_column_from_pos(doc
, bytes_read
, &line
, &column
);
1687 error_text
= g_strdup_printf(
1688 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1689 conv_error
->message
, context
, line
+ 1, column
);
1693 error_text
= g_strdup_printf(_("Error message: %s."), conv_error
->message
);
1695 geany_debug("encoding error: %s", conv_error
->message
);
1696 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, text
, error_text
);
1697 g_error_free(conv_error
);
1705 *data
= conv_file_contents
;
1712 static gchar
*write_data_to_disk(const gchar
*locale_filename
,
1713 const gchar
*data
, gint len
)
1715 GError
*error
= NULL
;
1717 if (! file_prefs
.use_safe_file_saving
)
1722 /* Use GIO API to save file (GVFS-safe) */
1723 fp
= g_file_new_for_path(locale_filename
);
1724 g_file_replace_contents(fp
, data
, len
, NULL
, file_prefs
.gio_unsafe_save_backup
,
1725 G_FILE_CREATE_NONE
, NULL
, NULL
, &error
);
1730 gchar
*display_name
= g_filename_display_name(locale_filename
);
1732 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1733 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1735 fp
= g_fopen(locale_filename
, "wb");
1742 g_file_error_from_errno(save_errno
),
1743 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1745 g_strerror(save_errno
));
1752 bytes_written
= fwrite(data
, sizeof(gchar
), len
, fp
);
1754 if (len
!= bytes_written
)
1760 g_file_error_from_errno(save_errno
),
1761 _("Failed to write file '%s': fwrite() failed: %s"),
1763 g_strerror(save_errno
));
1767 /* preserve the fwrite() error if any */
1768 if (fclose(fp
) != 0 && error
== NULL
)
1774 g_file_error_from_errno(save_errno
),
1775 _("Failed to close file '%s': fclose() failed: %s"),
1777 g_strerror(save_errno
));
1781 g_free(display_name
);
1786 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1787 * This is the only option that handles disk space exhaustion. */
1788 if (g_file_set_contents(locale_filename
, data
, len
, &error
))
1789 geany_debug("Wrote %s with g_file_set_contents().", locale_filename
);
1793 gchar
*msg
= g_strdup(error
->message
);
1794 g_error_free(error
);
1795 /* geany will warn about file truncation for unsafe saving below */
1802 static gchar
*save_doc(GeanyDocument
*doc
, const gchar
*locale_filename
,
1803 const gchar
*data
, gint len
)
1807 g_return_val_if_fail(doc
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1808 g_return_val_if_fail(data
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1810 err
= write_data_to_disk(locale_filename
, data
, len
);
1814 /* now the file is on disk, set real_path */
1815 if (doc
->real_path
== NULL
)
1817 doc
->real_path
= tm_get_real_path(locale_filename
);
1818 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1819 monitor_file_setup(doc
);
1826 * Saves the document. Saving may include replacing tabs by spaces,
1827 * stripping trailing spaces and adding a final new line at the end of the file, depending
1828 * on user preferences. Then the @c "document-before-save" signal is emitted,
1829 * allowing plugins to modify the document before it is saved, and data is
1830 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1831 * Afterwards, the @c "document-save" signal is emitted for plugins.
1833 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1835 * @note You should ensure @c doc->file_name is not @c NULL before calling this; otherwise
1836 * call dialogs_show_save_as().
1838 * @param doc The document to save.
1839 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1841 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1843 gboolean
document_save_file(GeanyDocument
*doc
, gboolean force
)
1848 gchar
*locale_filename
;
1850 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1852 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1853 if (! force
&& ! ui_prefs
.allow_always_save
&& (! doc
->changed
|| doc
->readonly
))
1856 if (G_UNLIKELY(doc
->file_name
== NULL
))
1858 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), _("Invalid filename"));
1863 /* replaces tabs by spaces but only if the current file is not a Makefile */
1864 if (file_prefs
.replace_tabs
&& doc
->file_type
->id
!= GEANY_FILETYPES_MAKE
)
1865 editor_replace_tabs(doc
->editor
);
1866 /* strip trailing spaces */
1867 if (file_prefs
.strip_trailing_spaces
)
1868 editor_strip_trailing_spaces(doc
->editor
);
1869 /* ensure the file has a newline at the end */
1870 if (file_prefs
.final_new_line
)
1871 editor_ensure_final_newline(doc
->editor
);
1872 /* ensure newlines are consistent */
1873 if (file_prefs
.ensure_convert_new_lines
)
1874 sci_convert_eols(doc
->editor
->sci
, sci_get_eol_mode(doc
->editor
->sci
));
1876 /* notify plugins which may wish to modify the document before it's saved */
1877 g_signal_emit_by_name(geany_object
, "document-before-save", doc
);
1879 len
= sci_get_length(doc
->editor
->sci
) + 1;
1880 if (doc
->has_bom
&& encodings_is_unicode_charset(doc
->encoding
))
1881 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1882 * encoding, it will be converted to doc->encoding below and this conversion
1883 * also changes the BOM */
1884 data
= (gchar
*) g_malloc(len
+ 3); /* 3 chars for BOM */
1885 data
[0] = (gchar
) 0xef;
1886 data
[1] = (gchar
) 0xbb;
1887 data
[2] = (gchar
) 0xbf;
1888 sci_get_text(doc
->editor
->sci
, len
, data
+ 3);
1893 data
= (gchar
*) g_malloc(len
);
1894 sci_get_text(doc
->editor
->sci
, len
, data
);
1897 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1898 if (doc
->encoding
!= NULL
&& ! utils_str_equal(doc
->encoding
, "UTF-8") &&
1899 ! utils_str_equal(doc
->encoding
, encodings
[GEANY_ENCODING_NONE
].charset
))
1901 if (! save_convert_to_encoding(doc
, &data
, &len
))
1912 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1914 /* ignore file changed notification when the file is written */
1915 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1917 /* actually write the content of data to the file on disk */
1918 errmsg
= save_doc(doc
, locale_filename
, data
, len
);
1923 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), errmsg
);
1925 if (!file_prefs
.use_safe_file_saving
)
1928 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg
));
1930 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, _("Error saving file."), errmsg
);
1931 doc
->priv
->file_disk_status
= FILE_OK
;
1933 g_free(locale_filename
);
1938 /* store the opened encoding for undo/redo */
1939 store_saved_encoding(doc
);
1941 /* ignore the following things if we are quitting */
1942 if (! main_status
.quitting
)
1944 sci_set_savepoint(doc
->editor
->sci
);
1946 if (file_prefs
.disk_check_timeout
> 0)
1947 document_update_timestamp(doc
, locale_filename
);
1949 /* update filetype-related things */
1950 document_set_filetype(doc
, doc
->file_type
);
1952 document_update_tab_label(doc
);
1954 msgwin_status_add(_("File %s saved."), doc
->file_name
);
1955 ui_update_statusbar(doc
, -1);
1957 vte_cwd((doc
->real_path
!= NULL
) ? doc
->real_path
: doc
->file_name
, FALSE
);
1960 g_free(locale_filename
);
1962 g_signal_emit_by_name(geany_object
, "document-save", doc
);
1968 /* special search function, used from the find entry in the toolbar
1969 * return TRUE if text was found otherwise FALSE
1970 * return also TRUE if text is empty */
1971 gboolean
document_search_bar_find(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean inc
)
1973 gint start_pos
, search_pos
;
1974 struct Sci_TextToFind ttf
;
1976 g_return_val_if_fail(text
!= NULL
, FALSE
);
1977 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1981 start_pos
= (inc
) ? sci_get_selection_start(doc
->editor
->sci
) :
1982 sci_get_selection_end(doc
->editor
->sci
); /* equal if no selection */
1984 /* search cursor to end */
1985 ttf
.chrg
.cpMin
= start_pos
;
1986 ttf
.chrg
.cpMax
= sci_get_length(doc
->editor
->sci
);
1987 ttf
.lpstrText
= (gchar
*)text
;
1988 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1990 /* if no match, search start to cursor */
1991 if (search_pos
== -1)
1994 ttf
.chrg
.cpMax
= start_pos
+ strlen(text
);
1995 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1998 if (search_pos
!= -1)
2000 gint line
= sci_get_line_from_position(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
2002 /* unfold maybe folded results */
2003 sci_ensure_line_is_visible(doc
->editor
->sci
, line
);
2005 sci_set_selection_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
2006 sci_set_selection_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
2008 if (! editor_line_in_view(doc
->editor
, line
))
2009 { /* we need to force scrolling in case the cursor is outside of the current visible area
2010 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2011 * while searching */
2012 editor_scroll_to_line(doc
->editor
, -1, 0.3F
);
2015 sci_scroll_caret(doc
->editor
->sci
); /* may need horizontal scrolling */
2022 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
2025 sci_goto_pos(doc
->editor
->sci
, start_pos
, FALSE
); /* clear selection */
2031 /* General search function, used from the find dialog.
2032 * Returns -1 on failure or the start position of the matching text.
2033 * Will skip past any selection, ignoring it. */
2034 gint
document_find_text(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean search_backwards
,
2035 gboolean scroll
, GtkWidget
*parent
)
2037 gint selection_end
, selection_start
, search_pos
;
2039 g_return_val_if_fail(doc
!= NULL
&& text
!= NULL
, -1);
2043 /* Sci doesn't support searching backwards with a regex */
2044 if (flags
& SCFIND_REGEXP
)
2045 search_backwards
= FALSE
;
2047 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2048 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2049 if ((selection_end
- selection_start
) > 0)
2050 { /* there's a selection so go to the end */
2051 if (search_backwards
)
2052 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2054 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2057 sci_set_search_anchor(doc
->editor
->sci
);
2058 if (search_backwards
)
2059 search_pos
= sci_search_prev(doc
->editor
->sci
, flags
, text
);
2061 search_pos
= search_find_next(doc
->editor
->sci
, text
, flags
);
2063 if (search_pos
!= -1)
2065 /* unfold maybe folded results */
2066 sci_ensure_line_is_visible(doc
->editor
->sci
,
2067 sci_get_line_from_position(doc
->editor
->sci
, search_pos
));
2069 doc
->editor
->scroll_percent
= 0.3F
;
2073 gint sci_len
= sci_get_length(doc
->editor
->sci
);
2075 /* if we just searched the whole text, give up searching. */
2076 if ((selection_end
== 0 && ! search_backwards
) ||
2077 (selection_end
== sci_len
&& search_backwards
))
2079 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
2084 /* we searched only part of the document, so ask whether to wraparound. */
2085 if (search_prefs
.suppress_dialogs
||
2086 dialogs_show_question_full(parent
, GTK_STOCK_FIND
, GTK_STOCK_CANCEL
,
2087 _("Wrap search and find again?"), _("\"%s\" was not found."), text
))
2091 sci_set_current_position(doc
->editor
->sci
, (search_backwards
) ? sci_len
: 0, FALSE
);
2092 ret
= document_find_text(doc
, text
, flags
, search_backwards
, scroll
, parent
);
2094 { /* return to original cursor position if not found */
2095 sci_set_current_position(doc
->editor
->sci
, selection_start
, FALSE
);
2104 /* Replaces the selection if it matches, otherwise just finds the next match.
2105 * Returns: start of replaced text, or -1 if no replacement was made */
2106 gint
document_replace_text(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2107 gint flags
, gboolean search_backwards
)
2109 gint selection_end
, selection_start
, search_pos
;
2111 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, -1);
2116 /* Sci doesn't support searching backwards with a regex */
2117 if (flags
& SCFIND_REGEXP
)
2118 search_backwards
= FALSE
;
2120 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2121 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2122 if (selection_end
== selection_start
)
2124 /* no selection so just find the next match */
2125 document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2128 /* there's a selection so go to the start before finding to search through it
2129 * this ensures there is a match */
2130 if (search_backwards
)
2131 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2133 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2135 search_pos
= document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2136 /* return if the original selected text did not match (at the start of the selection) */
2137 if (search_pos
!= selection_start
)
2140 if (search_pos
!= -1)
2143 /* search next/prev will select matching text, which we use to set the replace target */
2144 sci_target_from_selection(doc
->editor
->sci
);
2145 replace_len
= search_replace_target(doc
->editor
->sci
, replace_text
, flags
& SCFIND_REGEXP
);
2146 /* select the replacement - find text will skip past the selected text */
2147 sci_set_selection_start(doc
->editor
->sci
, search_pos
);
2148 sci_set_selection_end(doc
->editor
->sci
, search_pos
+ replace_len
);
2152 /* no match in the selection */
2159 static void show_replace_summary(GeanyDocument
*doc
, gint count
, const gchar
*find_text
,
2160 const gchar
*replace_text
, gboolean escaped_chars
)
2162 gchar
*escaped_find_text
, *escaped_replace_text
, *filename
;
2166 ui_set_statusbar(FALSE
, _("No matches found for \"%s\"."), find_text
);
2170 filename
= g_path_get_basename(DOC_FILENAME(doc
));
2173 { /* escape special characters for showing */
2174 escaped_find_text
= g_strescape(find_text
, NULL
);
2175 escaped_replace_text
= g_strescape(replace_text
, NULL
);
2176 ui_set_statusbar(TRUE
, ngettext(
2177 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2178 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2179 count
), filename
, count
, escaped_find_text
, escaped_replace_text
);
2180 g_free(escaped_find_text
);
2181 g_free(escaped_replace_text
);
2185 ui_set_statusbar(TRUE
, ngettext(
2186 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2187 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2188 count
), filename
, count
, find_text
, replace_text
);
2194 /* Replace all text matches in a certain range within document.
2195 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2196 * or -1 if no text was found.
2197 * scroll_to_match is whether to scroll the last replacement in view (which also
2198 * clears the selection).
2199 * Returns: the number of replacements made. */
2201 document_replace_range(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2202 gint flags
, gint start
, gint end
, gboolean scroll_to_match
, gint
*new_range_end
)
2205 struct Sci_TextToFind ttf
;
2206 ScintillaObject
*sci
;
2208 if (new_range_end
!= NULL
)
2209 *new_range_end
= -1;
2211 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, 0);
2213 if (! *find_text
|| doc
->readonly
)
2216 sci
= doc
->editor
->sci
;
2218 ttf
.chrg
.cpMin
= start
;
2219 ttf
.chrg
.cpMax
= end
;
2220 ttf
.lpstrText
= (gchar
*)find_text
;
2222 sci_start_undo_action(sci
);
2223 count
= search_replace_range(sci
, &ttf
, flags
, replace_text
);
2224 sci_end_undo_action(sci
);
2227 { /* scroll last match in view, will destroy the existing selection */
2228 if (scroll_to_match
)
2229 sci_goto_pos(sci
, ttf
.chrg
.cpMin
, TRUE
);
2231 if (new_range_end
!= NULL
)
2232 *new_range_end
= ttf
.chrg
.cpMax
;
2238 void document_replace_sel(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2239 gint flags
, gboolean escaped_chars
)
2241 gint selection_end
, selection_start
, selection_mode
, selected_lines
, last_line
= 0;
2242 gint max_column
= 0, count
= 0;
2243 gboolean replaced
= FALSE
;
2245 g_return_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
);
2250 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2251 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2252 /* do we have a selection? */
2253 if ((selection_end
- selection_start
) == 0)
2259 selection_mode
= sci_get_selection_mode(doc
->editor
->sci
);
2260 selected_lines
= sci_get_lines_selected(doc
->editor
->sci
);
2261 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2262 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2264 gint first_line
, line
;
2266 sci_start_undo_action(doc
->editor
->sci
);
2268 first_line
= sci_get_line_from_position(doc
->editor
->sci
, selection_start
);
2269 /* Find the last line with chars selected (not EOL char) */
2270 last_line
= sci_get_line_from_position(doc
->editor
->sci
,
2271 selection_end
- editor_get_eol_char_len(doc
->editor
));
2272 last_line
= MAX(first_line
, last_line
);
2273 for (line
= first_line
; line
< (first_line
+ selected_lines
); line
++)
2275 gint line_start
= sci_get_pos_at_line_sel_start(doc
->editor
->sci
, line
);
2276 gint line_end
= sci_get_pos_at_line_sel_end(doc
->editor
->sci
, line
);
2278 /* skip line if there is no selection */
2279 if (line_start
!= INVALID_POSITION
)
2281 /* don't let document_replace_range() scroll to match to keep our selection */
2284 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2285 line_start
, line_end
, FALSE
, &new_sel_end
);
2286 if (new_sel_end
!= -1)
2289 /* this gets the greatest column within the selection after replacing */
2290 max_column
= MAX(max_column
,
2291 new_sel_end
- sci_get_position_from_line(doc
->editor
->sci
, line
));
2295 sci_end_undo_action(doc
->editor
->sci
);
2297 else /* handle normal line selection */
2299 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2300 selection_start
, selection_end
, TRUE
, &selection_end
);
2301 if (selection_end
!= -1)
2306 { /* update the selection for the new endpoint */
2308 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2310 /* now we can scroll to the selection and destroy it because we rebuild it later */
2311 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2313 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2314 * the highest column on the last line. The wrapped selection is completely different
2315 * from the original one, so skip the selection at all */
2316 /* TODO is there a better way to handle the wrapped selection? */
2317 if ((sci_get_line_length(doc
->editor
->sci
, last_line
) - 1) >= max_column
)
2318 { /* for keeping and adjusting the selection in multi line rectangle selection we
2319 * need the last line of the original selection and the greatest column number after
2320 * replacing and set the selection end to the last line at the greatest column */
2321 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2322 sci_set_selection_end(doc
->editor
->sci
,
2323 sci_get_position_from_line(doc
->editor
->sci
, last_line
) + max_column
);
2324 sci_set_selection_mode(doc
->editor
->sci
, selection_mode
);
2329 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2330 sci_set_selection_end(doc
->editor
->sci
, selection_end
);
2333 else /* no replacements */
2336 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2340 /* returns number of replacements made. */
2341 gint
document_replace_all(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2342 gint flags
, gboolean escaped_chars
)
2345 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, FALSE
);
2350 len
= sci_get_length(doc
->editor
->sci
);
2351 count
= document_replace_range(
2352 doc
, find_text
, replace_text
, flags
, 0, len
, TRUE
, NULL
);
2354 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2359 static gboolean
update_tags_from_buffer(GeanyDocument
*doc
)
2364 result
= tm_source_file_update(doc
->tm_file
, TRUE
, FALSE
, TRUE
);
2366 gsize len
= sci_get_length(doc
->editor
->sci
) + 1;
2367 gchar
*text
= g_malloc(len
);
2369 /* we copy the whole text into memory instead using a direct char pointer from
2370 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2371 sci_get_text(doc
->editor
->sci
, len
, text
);
2372 result
= tm_source_file_buffer_update(doc
->tm_file
, (guchar
*) text
, len
, TRUE
);
2379 void document_update_tag_list(GeanyDocument
*doc
, gboolean update
)
2381 /* We must call sidebar_update_tag_list() before returning,
2382 * to ensure that the symbol list is always updated properly (e.g.
2383 * when creating a new document with a partial filename set. */
2384 gboolean success
= FALSE
;
2386 /* if the filetype doesn't have a tag parser or it is a new file */
2387 if (doc
== NULL
|| doc
->file_type
== NULL
|| app
->tm_workspace
== NULL
||
2388 ! filetype_has_tags(doc
->file_type
) || ! doc
->file_name
)
2390 /* set the default (empty) tag list */
2391 sidebar_update_tag_list(doc
, FALSE
);
2395 if (doc
->tm_file
== NULL
)
2397 gchar
*locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2400 /* lookup the name rather than using filetype name to support custom filetypes */
2401 name
= tm_source_file_get_lang_name(doc
->file_type
->lang
);
2402 doc
->tm_file
= tm_source_file_new(locale_filename
, FALSE
, name
);
2403 g_free(locale_filename
);
2407 if (!tm_workspace_add_object(doc
->tm_file
))
2409 tm_work_object_free(doc
->tm_file
);
2410 doc
->tm_file
= NULL
;
2415 update_tags_from_buffer(doc
);
2422 success
= update_tags_from_buffer(doc
);
2423 if (G_UNLIKELY(! success
))
2424 geany_debug("tag list updating failed");
2426 sidebar_update_tag_list(doc
, success
);
2430 /* Caches the list of project typenames, as a space separated GString.
2431 * Returns: TRUE if typenames have changed.
2432 * (*types) is set to the list of typenames, or NULL if there are none. */
2433 static gboolean
get_project_typenames(const GString
**types
, gint lang
)
2435 static GString
*last_typenames
= NULL
;
2438 if (app
->tm_workspace
)
2440 GPtrArray
*tags_array
= app
->tm_workspace
->work_object
.tags_array
;
2444 s
= symbols_find_tags_as_string(tags_array
, TM_GLOBAL_TYPE_MASK
, lang
);
2448 if (s
&& last_typenames
&& g_string_equal(s
, last_typenames
))
2450 g_string_free(s
, TRUE
);
2451 *types
= last_typenames
;
2452 return FALSE
; /* project typenames haven't changed */
2454 /* cache typename list for next time */
2456 g_string_free(last_typenames
, TRUE
);
2466 /* If sci is NULL, update project typenames for all documents that support typenames,
2467 * if typenames have changed.
2468 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2469 * if necessary, and typename keywords are set for sci.
2470 * Returns: TRUE if any scintilla type keywords were updated. */
2471 static gboolean
update_type_keywords(GeanyDocument
*doc
, gint lang
)
2473 gboolean ret
= FALSE
;
2476 ScintillaObject
*sci
;
2478 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2479 sci
= doc
->editor
->sci
;
2481 switch (doc
->file_type
->id
)
2482 { /* continue working with the following languages, skip on all others */
2483 case GEANY_FILETYPES_C
:
2484 case GEANY_FILETYPES_CPP
:
2485 case GEANY_FILETYPES_CS
:
2486 case GEANY_FILETYPES_D
:
2487 case GEANY_FILETYPES_JAVA
:
2488 case GEANY_FILETYPES_VALA
:
2494 sci
= doc
->editor
->sci
;
2495 if (sci
!= NULL
&& editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
)) == -1)
2498 if (! get_project_typenames(&s
, lang
))
2499 { /* typenames have not changed */
2500 if (s
!= NULL
&& sci
!= NULL
)
2502 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
));
2504 sci_set_keywords(sci
, keyword_idx
, s
->str
);
2505 queue_colourise(doc
);
2509 g_return_val_if_fail(s
!= NULL
, FALSE
);
2511 for (n
= 0; n
< documents_array
->len
; n
++)
2513 if (documents
[n
]->is_valid
)
2515 ScintillaObject
*wid
= documents
[n
]->editor
->sci
;
2516 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(wid
));
2518 if (keyword_idx
> 0)
2520 sci_set_keywords(wid
, keyword_idx
, s
->str
);
2521 queue_colourise(documents
[n
]);
2530 static void document_load_config(GeanyDocument
*doc
, GeanyFiletype
*type
,
2531 gboolean filetype_changed
)
2533 g_return_if_fail(doc
);
2535 type
= filetypes
[GEANY_FILETYPES_NONE
];
2537 if (filetype_changed
)
2539 doc
->file_type
= type
;
2541 /* delete tm file object to force creation of a new one */
2542 if (doc
->tm_file
!= NULL
)
2544 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
2545 doc
->tm_file
= NULL
;
2547 /* load tags files before highlighting (some lexers highlight global typenames) */
2548 if (type
->id
!= GEANY_FILETYPES_NONE
)
2549 symbols_global_tags_loaded(type
->id
);
2551 highlighting_set_styles(doc
->editor
->sci
, type
);
2552 editor_set_indentation_guides(doc
->editor
);
2553 build_menu_update(doc
);
2554 queue_colourise(doc
);
2555 doc
->priv
->symbol_list_sort_mode
= type
->priv
->symbol_list_sort_mode
;
2558 document_update_tag_list(doc
, TRUE
);
2560 /* Update session typename keywords. */
2561 update_type_keywords(doc
, type
->lang
);
2565 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2566 * @param doc The document to use.
2567 * @param type The filetype. */
2568 void document_set_filetype(GeanyDocument
*doc
, GeanyFiletype
*type
)
2570 gboolean ft_changed
;
2571 GeanyFiletype
*old_ft
;
2573 g_return_if_fail(doc
);
2575 type
= filetypes
[GEANY_FILETYPES_NONE
];
2577 old_ft
= doc
->file_type
;
2578 geany_debug("%s : %s (%s)",
2579 (doc
->file_name
!= NULL
) ? doc
->file_name
: "unknown",
2581 (doc
->encoding
!= NULL
) ? doc
->encoding
: "unknown");
2583 ft_changed
= (doc
->file_type
!= type
); /* filetype has changed */
2584 document_load_config(doc
, type
, ft_changed
);
2588 sidebar_openfiles_update(doc
); /* to update the icon */
2589 g_signal_emit_by_name(geany_object
, "document-filetype-set", doc
, old_ft
);
2594 void document_reload_config(GeanyDocument
*doc
)
2596 document_load_config(doc
, doc
->file_type
, TRUE
);
2601 * Sets the encoding of a document.
2602 * This function only set the encoding of the %document, it does not any conversions. The new
2603 * encoding is used when e.g. saving the file.
2605 * @param doc The document to use.
2606 * @param new_encoding The encoding to be set for the document.
2608 void document_set_encoding(GeanyDocument
*doc
, const gchar
*new_encoding
)
2610 if (doc
== NULL
|| new_encoding
== NULL
||
2611 utils_str_equal(new_encoding
, doc
->encoding
))
2614 g_free(doc
->encoding
);
2615 doc
->encoding
= g_strdup(new_encoding
);
2617 ui_update_statusbar(doc
, -1);
2618 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets
.window
, "menu_write_unicode_bom1"),
2619 encodings_is_unicode_charset(doc
->encoding
));
2623 /* own Undo / Redo implementation to be able to undo / redo changes
2624 * to the encoding or the Unicode BOM (which are Scintilla independet).
2625 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2627 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2628 void document_undo_clear(GeanyDocument
*doc
)
2632 while (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0)
2634 a
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2635 if (G_LIKELY(a
!= NULL
))
2639 case UNDO_ENCODING
: g_free(a
->data
); break;
2645 doc
->priv
->undo_actions
= NULL
;
2647 while (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0)
2649 a
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2650 if (G_LIKELY(a
!= NULL
))
2654 case UNDO_ENCODING
: g_free(a
->data
); break;
2660 doc
->priv
->redo_actions
= NULL
;
2662 if (! main_status
.quitting
&& doc
->editor
!= NULL
)
2663 document_set_text_changed(doc
, FALSE
);
2667 void document_undo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2669 undo_action
*action
;
2671 g_return_if_fail(doc
!= NULL
);
2673 action
= g_new0(undo_action
, 1);
2674 action
->type
= type
;
2675 action
->data
= data
;
2677 g_trash_stack_push(&doc
->priv
->undo_actions
, action
);
2679 document_set_text_changed(doc
, TRUE
);
2680 ui_update_popup_reundo_items(doc
);
2684 gboolean
document_can_undo(GeanyDocument
*doc
)
2686 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2688 if (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0 || sci_can_undo(doc
->editor
->sci
))
2695 static void update_changed_state(GeanyDocument
*doc
)
2698 (sci_is_modified(doc
->editor
->sci
) ||
2699 doc
->has_bom
!= doc
->priv
->saved_encoding
.has_bom
||
2700 ! utils_str_equal(doc
->encoding
, doc
->priv
->saved_encoding
.encoding
));
2701 document_set_text_changed(doc
, doc
->changed
);
2705 void document_undo(GeanyDocument
*doc
)
2707 undo_action
*action
;
2709 g_return_if_fail(doc
!= NULL
);
2711 action
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2713 if (G_UNLIKELY(action
== NULL
))
2715 /* fallback, should not be necessary */
2716 geany_debug("%s: fallback used", G_STRFUNC
);
2717 sci_undo(doc
->editor
->sci
);
2721 switch (action
->type
)
2723 case UNDO_SCINTILLA
:
2725 document_redo_add(doc
, UNDO_SCINTILLA
, NULL
);
2727 sci_undo(doc
->editor
->sci
);
2732 document_redo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2734 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2735 ui_update_statusbar(doc
, -1);
2736 ui_document_show_hide(doc
);
2741 /* use the "old" encoding */
2742 document_redo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2744 document_set_encoding(doc
, (const gchar
*)action
->data
);
2746 ignore_callback
= TRUE
;
2747 encodings_select_radio_item((const gchar
*)action
->data
);
2748 ignore_callback
= FALSE
;
2750 g_free(action
->data
);
2756 g_free(action
); /* free the action which was taken from the stack */
2758 update_changed_state(doc
);
2759 ui_update_popup_reundo_items(doc
);
2763 gboolean
document_can_redo(GeanyDocument
*doc
)
2765 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2767 if (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0 || sci_can_redo(doc
->editor
->sci
))
2774 void document_redo(GeanyDocument
*doc
)
2776 undo_action
*action
;
2778 g_return_if_fail(doc
!= NULL
);
2780 action
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2782 if (G_UNLIKELY(action
== NULL
))
2784 /* fallback, should not be necessary */
2785 geany_debug("%s: fallback used", G_STRFUNC
);
2786 sci_redo(doc
->editor
->sci
);
2790 switch (action
->type
)
2792 case UNDO_SCINTILLA
:
2794 document_undo_add(doc
, UNDO_SCINTILLA
, NULL
);
2796 sci_redo(doc
->editor
->sci
);
2801 document_undo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2803 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2804 ui_update_statusbar(doc
, -1);
2805 ui_document_show_hide(doc
);
2810 document_undo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2812 document_set_encoding(doc
, (const gchar
*)action
->data
);
2814 ignore_callback
= TRUE
;
2815 encodings_select_radio_item((const gchar
*)action
->data
);
2816 ignore_callback
= FALSE
;
2818 g_free(action
->data
);
2824 g_free(action
); /* free the action which was taken from the stack */
2826 update_changed_state(doc
);
2827 ui_update_popup_reundo_items(doc
);
2831 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2833 undo_action
*action
;
2835 g_return_if_fail(doc
!= NULL
);
2837 action
= g_new0(undo_action
, 1);
2838 action
->type
= type
;
2839 action
->data
= data
;
2841 g_trash_stack_push(&doc
->priv
->redo_actions
, action
);
2843 document_set_text_changed(doc
, TRUE
);
2844 ui_update_popup_reundo_items(doc
);
2849 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2850 * Returned colors are red if the document has changes, green if the document is read-only
2851 * or simply @c NULL if the document is unmodified but writable.
2853 * @param doc The document to use.
2855 * @return The color for the document or @c NULL if the default color should be used. The color
2856 * object is owned by Geany and should not be modified or freed.
2860 const GdkColor
*document_get_status_color(GeanyDocument
*doc
)
2862 static GdkColor red
= {0, 0xFFFF, 0, 0};
2863 static GdkColor green
= {0, 0, 0x7FFF, 0};
2865 static GdkColor orange
= {0, 0xFFFF, 0x7FFF, 0};
2867 GdkColor
*color
= NULL
;
2869 g_return_val_if_fail(doc
!= NULL
, NULL
);
2874 else if (doc
->priv
->file_disk_status
== FILE_CHANGED
)
2877 else if (doc
->readonly
)
2880 return color
; /* return pointer to static GdkColor. */
2884 /** Accessor function for @ref GeanyData::documents_array items.
2885 * @warning Always check the returned document is valid (@c doc->is_valid).
2886 * @param idx @c documents_array index.
2887 * @return The document, or @c NULL if @a idx is out of range.
2891 GeanyDocument
*document_index(gint idx
)
2893 return (idx
>= 0 && idx
< (gint
) documents_array
->len
) ? documents
[idx
] : NULL
;
2897 /* create a new file and copy file content and properties */
2898 GeanyDocument
*document_clone(GeanyDocument
*old_doc
, const gchar
*utf8_filename
)
2904 g_return_val_if_fail(old_doc
!= NULL
, NULL
);
2906 len
= sci_get_length(old_doc
->editor
->sci
) + 1;
2907 text
= (gchar
*) g_malloc(len
);
2908 sci_get_text(old_doc
->editor
->sci
, len
, text
);
2909 /* use old file type (or maybe NULL for auto detect would be better?) */
2910 doc
= document_new_file(utf8_filename
, old_doc
->file_type
, text
);
2913 /* copy file properties */
2914 doc
->editor
->line_wrapping
= old_doc
->editor
->line_wrapping
;
2915 doc
->readonly
= old_doc
->readonly
;
2916 doc
->has_bom
= old_doc
->has_bom
;
2917 document_set_encoding(doc
, old_doc
->encoding
);
2918 sci_set_lines_wrapped(doc
->editor
->sci
, doc
->editor
->line_wrapping
);
2919 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
2921 ui_document_show_hide(doc
);
2926 /* @note If successful, this should always be followed up with a call to
2927 * document_close_all().
2928 * @return TRUE if all files were saved or had their changes discarded. */
2929 gboolean
document_account_for_unsaved(void)
2931 guint i
, p
, page_count
, len
= documents_array
->len
;
2934 page_count
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
2935 for (p
= 0; p
< page_count
; p
++)
2937 doc
= document_get_from_page(p
);
2938 if (DOC_VALID(doc
) && doc
->changed
)
2940 if (! dialogs_show_unsaved_file(doc
))
2944 /* all documents should now be accounted for, so ignore any changes */
2945 for (i
= 0; i
< len
; i
++)
2948 if (doc
->is_valid
&& doc
->changed
)
2950 doc
->changed
= FALSE
;
2957 static void force_close_all(void)
2959 guint i
, len
= documents_array
->len
;
2961 /* check all documents have been accounted for */
2962 for (i
= 0; i
< len
; i
++)
2964 if (documents
[i
]->is_valid
)
2966 g_return_if_fail(!documents
[i
]->changed
);
2969 main_status
.closing_all
= TRUE
;
2973 document_close(documents
[i
]);
2976 main_status
.closing_all
= FALSE
;
2980 gboolean
document_close_all(void)
2982 if (! document_account_for_unsaved())
2991 static void monitor_reload_file(GeanyDocument
*doc
)
2993 gchar
*base_name
= g_path_get_basename(doc
->file_name
);
2996 ret
= dialogs_show_prompt(NULL
,
2997 GTK_STOCK_CLOSE
, GTK_RESPONSE_CLOSE
,
2998 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
2999 _("_Reload"), GTK_RESPONSE_ACCEPT
,
3000 _("Do you want to reload it?"),
3001 _("The file '%s' on the disk is more recent than\nthe current buffer."),
3005 if (ret
== GTK_RESPONSE_ACCEPT
)
3006 document_reload_file(doc
, doc
->encoding
);
3007 else if (ret
== GTK_RESPONSE_CLOSE
)
3008 document_close(doc
);
3012 static gboolean
monitor_resave_missing_file(GeanyDocument
*doc
)
3014 gboolean want_reload
= FALSE
;
3015 gboolean file_saved
= FALSE
;
3018 ret
= dialogs_show_prompt(NULL
,
3019 _("Close _without saving"), GTK_RESPONSE_CLOSE
,
3020 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
3021 GTK_STOCK_SAVE
, GTK_RESPONSE_ACCEPT
,
3022 _("Try to resave the file?"),
3023 _("File \"%s\" was not found on disk!"),
3025 if (ret
== GTK_RESPONSE_ACCEPT
)
3027 file_saved
= dialogs_show_save_as();
3030 else if (ret
== GTK_RESPONSE_CLOSE
)
3032 document_close(doc
);
3034 if (ret
!= GTK_RESPONSE_CLOSE
&& ! file_saved
)
3036 /* file is missing - set unsaved state */
3037 document_set_text_changed(doc
, TRUE
);
3038 /* don't prompt more than once */
3039 setptr(doc
->real_path
, NULL
);
3046 /* Set force to force a disk check, otherwise it is ignored if there was a check
3047 * in the last file_prefs.disk_check_timeout seconds.
3048 * @return @c TRUE if the file has changed. */
3049 gboolean
document_check_disk_status(GeanyDocument
*doc
, gboolean force
)
3051 gboolean ret
= FALSE
;
3052 gboolean use_gio_filemon
;
3053 time_t cur_time
= 0;
3055 gchar
*locale_filename
;
3056 FileDiskStatus old_status
;
3058 g_return_val_if_fail(doc
!= NULL
, FALSE
);
3060 /* ignore remote files and documents that have never been saved to disk */
3061 if (file_prefs
.disk_check_timeout
== 0 || doc
->real_path
== NULL
|| doc
->priv
->is_remote
)
3064 use_gio_filemon
= (doc
->priv
->monitor
!= NULL
);
3066 if (use_gio_filemon
)
3068 if (doc
->priv
->file_disk_status
!= FILE_CHANGED
&& ! force
)
3073 cur_time
= time(NULL
);
3074 if (! force
&& doc
->priv
->last_check
> (cur_time
- file_prefs
.disk_check_timeout
))
3077 doc
->priv
->last_check
= cur_time
;
3080 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
3081 if (g_stat(locale_filename
, &st
) != 0)
3083 monitor_resave_missing_file(doc
);
3084 /* doc may be closed now */
3087 else if (! use_gio_filemon
&& /* ignore these checks when using GIO */
3088 (G_UNLIKELY(doc
->priv
->mtime
> cur_time
) || G_UNLIKELY(st
.st_mtime
> cur_time
)))
3090 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC
);
3092 else if (doc
->priv
->mtime
< st
.st_mtime
)
3094 doc
->priv
->mtime
= st
.st_mtime
;
3095 monitor_reload_file(doc
);
3096 /* doc may be closed now */
3099 g_free(locale_filename
);
3102 { /* doc can get invalid when a document was closed */
3103 old_status
= doc
->priv
->file_disk_status
;
3104 doc
->priv
->file_disk_status
= FILE_OK
;
3105 if (old_status
!= doc
->priv
->file_disk_status
)
3106 ui_update_tab_status(doc
);