2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2010 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2010 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
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
, FALSE
,
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
);
1801 static gchar
*save_doc(GeanyDocument
*doc
, const gchar
*locale_filename
,
1802 const gchar
*data
, gint len
)
1806 g_return_val_if_fail(doc
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1807 g_return_val_if_fail(data
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1809 err
= write_data_to_disk(locale_filename
, data
, len
);
1813 /* now the file is on disk, set real_path */
1814 if (doc
->real_path
== NULL
)
1816 doc
->real_path
= tm_get_real_path(locale_filename
);
1817 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1818 monitor_file_setup(doc
);
1825 * Saves the document. Saving includes replacing tabs by spaces,
1826 * stripping trailing spaces and adding a final new line at the end of the file (all only if
1827 * user enabled these features). Then the @c "document-before-save" signal is emitted,
1828 * allowing plugins to modify the document before it is saved, and data is
1829 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1830 * Afterwards, the @c "document-save" signal is emitted for plugins.
1832 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1834 * @param doc The document to save.
1835 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1837 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1839 gboolean
document_save_file(GeanyDocument
*doc
, gboolean force
)
1844 gchar
*locale_filename
;
1846 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1848 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1849 if (! force
&& ! ui_prefs
.allow_always_save
&& (! doc
->changed
|| doc
->readonly
))
1852 if (G_UNLIKELY(doc
->file_name
== NULL
))
1854 ui_set_statusbar(TRUE
, _("Error saving file."));
1859 /* replaces tabs by spaces but only if the current file is not a Makefile */
1860 if (file_prefs
.replace_tabs
&& doc
->file_type
->id
!= GEANY_FILETYPES_MAKE
)
1861 editor_replace_tabs(doc
->editor
);
1862 /* strip trailing spaces */
1863 if (file_prefs
.strip_trailing_spaces
)
1864 editor_strip_trailing_spaces(doc
->editor
);
1865 /* ensure the file has a newline at the end */
1866 if (file_prefs
.final_new_line
)
1867 editor_ensure_final_newline(doc
->editor
);
1868 /* ensure newlines are consistent */
1869 if (file_prefs
.ensure_convert_new_lines
)
1870 sci_convert_eols(doc
->editor
->sci
, sci_get_eol_mode(doc
->editor
->sci
));
1872 /* notify plugins which may wish to modify the document before it's saved */
1873 g_signal_emit_by_name(geany_object
, "document-before-save", doc
);
1875 len
= sci_get_length(doc
->editor
->sci
) + 1;
1876 if (doc
->has_bom
&& encodings_is_unicode_charset(doc
->encoding
))
1877 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1878 * encoding, it will be converted to doc->encoding below and this conversion
1879 * also changes the BOM */
1880 data
= (gchar
*) g_malloc(len
+ 3); /* 3 chars for BOM */
1881 data
[0] = (gchar
) 0xef;
1882 data
[1] = (gchar
) 0xbb;
1883 data
[2] = (gchar
) 0xbf;
1884 sci_get_text(doc
->editor
->sci
, len
, data
+ 3);
1889 data
= (gchar
*) g_malloc(len
);
1890 sci_get_text(doc
->editor
->sci
, len
, data
);
1893 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1894 if (doc
->encoding
!= NULL
&& ! utils_str_equal(doc
->encoding
, "UTF-8") &&
1895 ! utils_str_equal(doc
->encoding
, encodings
[GEANY_ENCODING_NONE
].charset
))
1897 if (! save_convert_to_encoding(doc
, &data
, &len
))
1908 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1910 /* ignore file changed notification when the file is written */
1911 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1913 /* actually write the content of data to the file on disk */
1914 errmsg
= save_doc(doc
, locale_filename
, data
, len
);
1919 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), errmsg
);
1920 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, _("Error saving file."), errmsg
);
1921 doc
->priv
->file_disk_status
= FILE_OK
;
1923 g_free(locale_filename
);
1928 /* store the opened encoding for undo/redo */
1929 store_saved_encoding(doc
);
1931 /* ignore the following things if we are quitting */
1932 if (! main_status
.quitting
)
1934 sci_set_savepoint(doc
->editor
->sci
);
1936 if (file_prefs
.disk_check_timeout
> 0)
1937 document_update_timestamp(doc
, locale_filename
);
1939 /* update filetype-related things */
1940 document_set_filetype(doc
, doc
->file_type
);
1942 document_update_tab_label(doc
);
1944 msgwin_status_add(_("File %s saved."), doc
->file_name
);
1945 ui_update_statusbar(doc
, -1);
1947 vte_cwd((doc
->real_path
!= NULL
) ? doc
->real_path
: doc
->file_name
, FALSE
);
1950 g_free(locale_filename
);
1952 g_signal_emit_by_name(geany_object
, "document-save", doc
);
1958 /* special search function, used from the find entry in the toolbar
1959 * return TRUE if text was found otherwise FALSE
1960 * return also TRUE if text is empty */
1961 gboolean
document_search_bar_find(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean inc
)
1963 gint start_pos
, search_pos
;
1964 struct Sci_TextToFind ttf
;
1966 g_return_val_if_fail(text
!= NULL
, FALSE
);
1967 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1971 start_pos
= (inc
) ? sci_get_selection_start(doc
->editor
->sci
) :
1972 sci_get_selection_end(doc
->editor
->sci
); /* equal if no selection */
1974 /* search cursor to end */
1975 ttf
.chrg
.cpMin
= start_pos
;
1976 ttf
.chrg
.cpMax
= sci_get_length(doc
->editor
->sci
);
1977 ttf
.lpstrText
= (gchar
*)text
;
1978 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1980 /* if no match, search start to cursor */
1981 if (search_pos
== -1)
1984 ttf
.chrg
.cpMax
= start_pos
+ strlen(text
);
1985 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1988 if (search_pos
!= -1)
1990 gint line
= sci_get_line_from_position(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1992 /* unfold maybe folded results */
1993 sci_ensure_line_is_visible(doc
->editor
->sci
, line
);
1995 sci_set_selection_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1996 sci_set_selection_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1998 if (! editor_line_in_view(doc
->editor
, line
))
1999 { /* we need to force scrolling in case the cursor is outside of the current visible area
2000 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2001 * while searching */
2002 editor_scroll_to_line(doc
->editor
, -1, 0.3F
);
2005 sci_scroll_caret(doc
->editor
->sci
); /* may need horizontal scrolling */
2012 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
2015 sci_goto_pos(doc
->editor
->sci
, start_pos
, FALSE
); /* clear selection */
2021 /* General search function, used from the find dialog.
2022 * Returns -1 on failure or the start position of the matching text.
2023 * Will skip past any selection, ignoring it. */
2024 gint
document_find_text(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean search_backwards
,
2025 gboolean scroll
, GtkWidget
*parent
)
2027 gint selection_end
, selection_start
, search_pos
;
2029 g_return_val_if_fail(doc
!= NULL
&& text
!= NULL
, -1);
2033 /* Sci doesn't support searching backwards with a regex */
2034 if (flags
& SCFIND_REGEXP
)
2035 search_backwards
= FALSE
;
2037 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2038 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2039 if ((selection_end
- selection_start
) > 0)
2040 { /* there's a selection so go to the end */
2041 if (search_backwards
)
2042 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2044 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2047 sci_set_search_anchor(doc
->editor
->sci
);
2048 if (search_backwards
)
2049 search_pos
= sci_search_prev(doc
->editor
->sci
, flags
, text
);
2051 search_pos
= search_find_next(doc
->editor
->sci
, text
, flags
);
2053 if (search_pos
!= -1)
2055 /* unfold maybe folded results */
2056 sci_ensure_line_is_visible(doc
->editor
->sci
,
2057 sci_get_line_from_position(doc
->editor
->sci
, search_pos
));
2059 doc
->editor
->scroll_percent
= 0.3F
;
2063 gint sci_len
= sci_get_length(doc
->editor
->sci
);
2065 /* if we just searched the whole text, give up searching. */
2066 if ((selection_end
== 0 && ! search_backwards
) ||
2067 (selection_end
== sci_len
&& search_backwards
))
2069 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
2074 /* we searched only part of the document, so ask whether to wraparound. */
2075 if (search_prefs
.suppress_dialogs
||
2076 dialogs_show_question_full(parent
, GTK_STOCK_FIND
, GTK_STOCK_CANCEL
,
2077 _("Wrap search and find again?"), _("\"%s\" was not found."), text
))
2081 sci_set_current_position(doc
->editor
->sci
, (search_backwards
) ? sci_len
: 0, FALSE
);
2082 ret
= document_find_text(doc
, text
, flags
, search_backwards
, scroll
, parent
);
2084 { /* return to original cursor position if not found */
2085 sci_set_current_position(doc
->editor
->sci
, selection_start
, FALSE
);
2094 /* Replaces the selection if it matches, otherwise just finds the next match.
2095 * Returns: start of replaced text, or -1 if no replacement was made */
2096 gint
document_replace_text(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2097 gint flags
, gboolean search_backwards
)
2099 gint selection_end
, selection_start
, search_pos
;
2101 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, -1);
2106 /* Sci doesn't support searching backwards with a regex */
2107 if (flags
& SCFIND_REGEXP
)
2108 search_backwards
= FALSE
;
2110 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2111 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2112 if (selection_end
== selection_start
)
2114 /* no selection so just find the next match */
2115 document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2118 /* there's a selection so go to the start before finding to search through it
2119 * this ensures there is a match */
2120 if (search_backwards
)
2121 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2123 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2125 search_pos
= document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2126 /* return if the original selected text did not match (at the start of the selection) */
2127 if (search_pos
!= selection_start
)
2130 if (search_pos
!= -1)
2133 /* search next/prev will select matching text, which we use to set the replace target */
2134 sci_target_from_selection(doc
->editor
->sci
);
2135 replace_len
= search_replace_target(doc
->editor
->sci
, replace_text
, flags
& SCFIND_REGEXP
);
2136 /* select the replacement - find text will skip past the selected text */
2137 sci_set_selection_start(doc
->editor
->sci
, search_pos
);
2138 sci_set_selection_end(doc
->editor
->sci
, search_pos
+ replace_len
);
2142 /* no match in the selection */
2149 static void show_replace_summary(GeanyDocument
*doc
, gint count
, const gchar
*find_text
,
2150 const gchar
*replace_text
, gboolean escaped_chars
)
2152 gchar
*escaped_find_text
, *escaped_replace_text
, *filename
;
2156 ui_set_statusbar(FALSE
, _("No matches found for \"%s\"."), find_text
);
2160 filename
= g_path_get_basename(DOC_FILENAME(doc
));
2163 { /* escape special characters for showing */
2164 escaped_find_text
= g_strescape(find_text
, NULL
);
2165 escaped_replace_text
= g_strescape(replace_text
, NULL
);
2166 ui_set_statusbar(TRUE
, ngettext(
2167 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2168 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2169 count
), filename
, count
, escaped_find_text
, escaped_replace_text
);
2170 g_free(escaped_find_text
);
2171 g_free(escaped_replace_text
);
2175 ui_set_statusbar(TRUE
, ngettext(
2176 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2177 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2178 count
), filename
, count
, find_text
, replace_text
);
2184 /* Replace all text matches in a certain range within document.
2185 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2186 * or -1 if no text was found.
2187 * scroll_to_match is whether to scroll the last replacement in view (which also
2188 * clears the selection).
2189 * Returns: the number of replacements made. */
2191 document_replace_range(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2192 gint flags
, gint start
, gint end
, gboolean scroll_to_match
, gint
*new_range_end
)
2195 struct Sci_TextToFind ttf
;
2196 ScintillaObject
*sci
;
2198 if (new_range_end
!= NULL
)
2199 *new_range_end
= -1;
2201 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, 0);
2203 if (! *find_text
|| doc
->readonly
)
2206 sci
= doc
->editor
->sci
;
2208 ttf
.chrg
.cpMin
= start
;
2209 ttf
.chrg
.cpMax
= end
;
2210 ttf
.lpstrText
= (gchar
*)find_text
;
2212 sci_start_undo_action(sci
);
2213 count
= search_replace_range(sci
, &ttf
, flags
, replace_text
);
2214 sci_end_undo_action(sci
);
2217 { /* scroll last match in view, will destroy the existing selection */
2218 if (scroll_to_match
)
2219 sci_goto_pos(sci
, ttf
.chrg
.cpMin
, TRUE
);
2221 if (new_range_end
!= NULL
)
2222 *new_range_end
= ttf
.chrg
.cpMax
;
2228 void document_replace_sel(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2229 gint flags
, gboolean escaped_chars
)
2231 gint selection_end
, selection_start
, selection_mode
, selected_lines
, last_line
= 0;
2232 gint max_column
= 0, count
= 0;
2233 gboolean replaced
= FALSE
;
2235 g_return_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
);
2240 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2241 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2242 /* do we have a selection? */
2243 if ((selection_end
- selection_start
) == 0)
2249 selection_mode
= sci_get_selection_mode(doc
->editor
->sci
);
2250 selected_lines
= sci_get_lines_selected(doc
->editor
->sci
);
2251 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2252 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2254 gint first_line
, line
;
2256 sci_start_undo_action(doc
->editor
->sci
);
2258 first_line
= sci_get_line_from_position(doc
->editor
->sci
, selection_start
);
2259 /* Find the last line with chars selected (not EOL char) */
2260 last_line
= sci_get_line_from_position(doc
->editor
->sci
,
2261 selection_end
- editor_get_eol_char_len(doc
->editor
));
2262 last_line
= MAX(first_line
, last_line
);
2263 for (line
= first_line
; line
< (first_line
+ selected_lines
); line
++)
2265 gint line_start
= sci_get_pos_at_line_sel_start(doc
->editor
->sci
, line
);
2266 gint line_end
= sci_get_pos_at_line_sel_end(doc
->editor
->sci
, line
);
2268 /* skip line if there is no selection */
2269 if (line_start
!= INVALID_POSITION
)
2271 /* don't let document_replace_range() scroll to match to keep our selection */
2274 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2275 line_start
, line_end
, FALSE
, &new_sel_end
);
2276 if (new_sel_end
!= -1)
2279 /* this gets the greatest column within the selection after replacing */
2280 max_column
= MAX(max_column
,
2281 new_sel_end
- sci_get_position_from_line(doc
->editor
->sci
, line
));
2285 sci_end_undo_action(doc
->editor
->sci
);
2287 else /* handle normal line selection */
2289 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2290 selection_start
, selection_end
, TRUE
, &selection_end
);
2291 if (selection_end
!= -1)
2296 { /* update the selection for the new endpoint */
2298 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2300 /* now we can scroll to the selection and destroy it because we rebuild it later */
2301 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2303 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2304 * the highest column on the last line. The wrapped selection is completely different
2305 * from the original one, so skip the selection at all */
2306 /* TODO is there a better way to handle the wrapped selection? */
2307 if ((sci_get_line_length(doc
->editor
->sci
, last_line
) - 1) >= max_column
)
2308 { /* for keeping and adjusting the selection in multi line rectangle selection we
2309 * need the last line of the original selection and the greatest column number after
2310 * replacing and set the selection end to the last line at the greatest column */
2311 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2312 sci_set_selection_end(doc
->editor
->sci
,
2313 sci_get_position_from_line(doc
->editor
->sci
, last_line
) + max_column
);
2314 sci_set_selection_mode(doc
->editor
->sci
, selection_mode
);
2319 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2320 sci_set_selection_end(doc
->editor
->sci
, selection_end
);
2323 else /* no replacements */
2326 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2330 /* returns number of replacements made. */
2331 gint
document_replace_all(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2332 gint flags
, gboolean escaped_chars
)
2335 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, FALSE
);
2340 len
= sci_get_length(doc
->editor
->sci
);
2341 count
= document_replace_range(
2342 doc
, find_text
, replace_text
, flags
, 0, len
, TRUE
, NULL
);
2344 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2349 static gboolean
update_tags_from_buffer(GeanyDocument
*doc
)
2354 result
= tm_source_file_update(doc
->tm_file
, TRUE
, FALSE
, TRUE
);
2356 gsize len
= sci_get_length(doc
->editor
->sci
) + 1;
2357 gchar
*text
= g_malloc(len
);
2359 /* we copy the whole text into memory instead using a direct char pointer from
2360 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2361 sci_get_text(doc
->editor
->sci
, len
, text
);
2362 result
= tm_source_file_buffer_update(doc
->tm_file
, (guchar
*) text
, len
, TRUE
);
2369 void document_update_tag_list(GeanyDocument
*doc
, gboolean update
)
2371 /* We must call sidebar_update_tag_list() before returning,
2372 * to ensure that the symbol list is always updated properly (e.g.
2373 * when creating a new document with a partial filename set. */
2374 gboolean success
= FALSE
;
2376 /* if the filetype doesn't have a tag parser or it is a new file */
2377 if (doc
== NULL
|| doc
->file_type
== NULL
|| app
->tm_workspace
== NULL
||
2378 ! filetype_has_tags(doc
->file_type
) || ! doc
->file_name
)
2380 /* set the default (empty) tag list */
2381 sidebar_update_tag_list(doc
, FALSE
);
2385 if (doc
->tm_file
== NULL
)
2387 gchar
*locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2390 /* lookup the name rather than using filetype name to support custom filetypes */
2391 name
= tm_source_file_get_lang_name(doc
->file_type
->lang
);
2392 doc
->tm_file
= tm_source_file_new(locale_filename
, FALSE
, name
);
2393 g_free(locale_filename
);
2397 if (!tm_workspace_add_object(doc
->tm_file
))
2399 tm_work_object_free(doc
->tm_file
);
2400 doc
->tm_file
= NULL
;
2405 update_tags_from_buffer(doc
);
2412 success
= update_tags_from_buffer(doc
);
2413 if (G_UNLIKELY(! success
))
2414 geany_debug("tag list updating failed");
2416 sidebar_update_tag_list(doc
, success
);
2420 /* Caches the list of project typenames, as a space separated GString.
2421 * Returns: TRUE if typenames have changed.
2422 * (*types) is set to the list of typenames, or NULL if there are none. */
2423 static gboolean
get_project_typenames(const GString
**types
, gint lang
)
2425 static GString
*last_typenames
= NULL
;
2428 if (app
->tm_workspace
)
2430 GPtrArray
*tags_array
= app
->tm_workspace
->work_object
.tags_array
;
2434 s
= symbols_find_tags_as_string(tags_array
, TM_GLOBAL_TYPE_MASK
, lang
);
2438 if (s
&& last_typenames
&& g_string_equal(s
, last_typenames
))
2440 g_string_free(s
, TRUE
);
2441 *types
= last_typenames
;
2442 return FALSE
; /* project typenames haven't changed */
2444 /* cache typename list for next time */
2446 g_string_free(last_typenames
, TRUE
);
2456 /* If sci is NULL, update project typenames for all documents that support typenames,
2457 * if typenames have changed.
2458 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2459 * if necessary, and typename keywords are set for sci.
2460 * Returns: TRUE if any scintilla type keywords were updated. */
2461 static gboolean
update_type_keywords(GeanyDocument
*doc
, gint lang
)
2463 gboolean ret
= FALSE
;
2466 ScintillaObject
*sci
;
2468 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2469 sci
= doc
->editor
->sci
;
2471 switch (doc
->file_type
->id
)
2472 { /* continue working with the following languages, skip on all others */
2473 case GEANY_FILETYPES_C
:
2474 case GEANY_FILETYPES_CPP
:
2475 case GEANY_FILETYPES_CS
:
2476 case GEANY_FILETYPES_D
:
2477 case GEANY_FILETYPES_JAVA
:
2478 case GEANY_FILETYPES_VALA
:
2484 sci
= doc
->editor
->sci
;
2485 if (sci
!= NULL
&& editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
)) == -1)
2488 if (! get_project_typenames(&s
, lang
))
2489 { /* typenames have not changed */
2490 if (s
!= NULL
&& sci
!= NULL
)
2492 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
));
2494 sci_set_keywords(sci
, keyword_idx
, s
->str
);
2495 queue_colourise(doc
);
2499 g_return_val_if_fail(s
!= NULL
, FALSE
);
2501 for (n
= 0; n
< documents_array
->len
; n
++)
2503 if (documents
[n
]->is_valid
)
2505 ScintillaObject
*wid
= documents
[n
]->editor
->sci
;
2506 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(wid
));
2508 if (keyword_idx
> 0)
2510 sci_set_keywords(wid
, keyword_idx
, s
->str
);
2511 queue_colourise(documents
[n
]);
2520 static void document_load_config(GeanyDocument
*doc
, GeanyFiletype
*type
,
2521 gboolean filetype_changed
)
2523 g_return_if_fail(doc
);
2525 type
= filetypes
[GEANY_FILETYPES_NONE
];
2527 if (filetype_changed
)
2529 doc
->file_type
= type
;
2531 /* delete tm file object to force creation of a new one */
2532 if (doc
->tm_file
!= NULL
)
2534 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
2535 doc
->tm_file
= NULL
;
2537 /* load tags files before highlighting (some lexers highlight global typenames) */
2538 if (type
->id
!= GEANY_FILETYPES_NONE
)
2539 symbols_global_tags_loaded(type
->id
);
2541 highlighting_set_styles(doc
->editor
->sci
, type
);
2542 editor_set_indentation_guides(doc
->editor
);
2543 build_menu_update(doc
);
2544 queue_colourise(doc
);
2545 doc
->priv
->symbol_list_sort_mode
= type
->priv
->symbol_list_sort_mode
;
2548 document_update_tag_list(doc
, TRUE
);
2550 /* Update session typename keywords. */
2551 update_type_keywords(doc
, type
->lang
);
2555 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2556 * @param doc The document to use.
2557 * @param type The filetype. */
2558 void document_set_filetype(GeanyDocument
*doc
, GeanyFiletype
*type
)
2560 gboolean ft_changed
;
2561 GeanyFiletype
*old_ft
;
2563 g_return_if_fail(doc
);
2565 type
= filetypes
[GEANY_FILETYPES_NONE
];
2567 old_ft
= doc
->file_type
;
2568 geany_debug("%s : %s (%s)",
2569 (doc
->file_name
!= NULL
) ? doc
->file_name
: "unknown",
2571 (doc
->encoding
!= NULL
) ? doc
->encoding
: "unknown");
2573 ft_changed
= (doc
->file_type
!= type
); /* filetype has changed */
2574 document_load_config(doc
, type
, ft_changed
);
2578 sidebar_openfiles_update(doc
); /* to update the icon */
2579 g_signal_emit_by_name(geany_object
, "document-filetype-set", doc
, old_ft
);
2584 void document_reload_config(GeanyDocument
*doc
)
2586 document_load_config(doc
, doc
->file_type
, TRUE
);
2591 * Sets the encoding of a document.
2592 * This function only set the encoding of the %document, it does not any conversions. The new
2593 * encoding is used when e.g. saving the file.
2595 * @param doc The document to use.
2596 * @param new_encoding The encoding to be set for the document.
2598 void document_set_encoding(GeanyDocument
*doc
, const gchar
*new_encoding
)
2600 if (doc
== NULL
|| new_encoding
== NULL
||
2601 utils_str_equal(new_encoding
, doc
->encoding
))
2604 g_free(doc
->encoding
);
2605 doc
->encoding
= g_strdup(new_encoding
);
2607 ui_update_statusbar(doc
, -1);
2608 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets
.window
, "menu_write_unicode_bom1"),
2609 encodings_is_unicode_charset(doc
->encoding
));
2613 /* own Undo / Redo implementation to be able to undo / redo changes
2614 * to the encoding or the Unicode BOM (which are Scintilla independet).
2615 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2617 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2618 void document_undo_clear(GeanyDocument
*doc
)
2622 while (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0)
2624 a
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2625 if (G_LIKELY(a
!= NULL
))
2629 case UNDO_ENCODING
: g_free(a
->data
); break;
2635 doc
->priv
->undo_actions
= NULL
;
2637 while (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0)
2639 a
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2640 if (G_LIKELY(a
!= NULL
))
2644 case UNDO_ENCODING
: g_free(a
->data
); break;
2650 doc
->priv
->redo_actions
= NULL
;
2652 if (! main_status
.quitting
&& doc
->editor
!= NULL
)
2653 document_set_text_changed(doc
, FALSE
);
2657 void document_undo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2659 undo_action
*action
;
2661 g_return_if_fail(doc
!= NULL
);
2663 action
= g_new0(undo_action
, 1);
2664 action
->type
= type
;
2665 action
->data
= data
;
2667 g_trash_stack_push(&doc
->priv
->undo_actions
, action
);
2669 document_set_text_changed(doc
, TRUE
);
2670 ui_update_popup_reundo_items(doc
);
2674 gboolean
document_can_undo(GeanyDocument
*doc
)
2676 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2678 if (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0 || sci_can_undo(doc
->editor
->sci
))
2685 static void update_changed_state(GeanyDocument
*doc
)
2688 (sci_is_modified(doc
->editor
->sci
) ||
2689 doc
->has_bom
!= doc
->priv
->saved_encoding
.has_bom
||
2690 ! utils_str_equal(doc
->encoding
, doc
->priv
->saved_encoding
.encoding
));
2691 document_set_text_changed(doc
, doc
->changed
);
2695 void document_undo(GeanyDocument
*doc
)
2697 undo_action
*action
;
2699 g_return_if_fail(doc
!= NULL
);
2701 action
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2703 if (G_UNLIKELY(action
== NULL
))
2705 /* fallback, should not be necessary */
2706 geany_debug("%s: fallback used", G_STRFUNC
);
2707 sci_undo(doc
->editor
->sci
);
2711 switch (action
->type
)
2713 case UNDO_SCINTILLA
:
2715 document_redo_add(doc
, UNDO_SCINTILLA
, NULL
);
2717 sci_undo(doc
->editor
->sci
);
2722 document_redo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2724 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2725 ui_update_statusbar(doc
, -1);
2726 ui_document_show_hide(doc
);
2731 /* use the "old" encoding */
2732 document_redo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2734 document_set_encoding(doc
, (const gchar
*)action
->data
);
2736 ignore_callback
= TRUE
;
2737 encodings_select_radio_item((const gchar
*)action
->data
);
2738 ignore_callback
= FALSE
;
2740 g_free(action
->data
);
2746 g_free(action
); /* free the action which was taken from the stack */
2748 update_changed_state(doc
);
2749 ui_update_popup_reundo_items(doc
);
2753 gboolean
document_can_redo(GeanyDocument
*doc
)
2755 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2757 if (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0 || sci_can_redo(doc
->editor
->sci
))
2764 void document_redo(GeanyDocument
*doc
)
2766 undo_action
*action
;
2768 g_return_if_fail(doc
!= NULL
);
2770 action
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2772 if (G_UNLIKELY(action
== NULL
))
2774 /* fallback, should not be necessary */
2775 geany_debug("%s: fallback used", G_STRFUNC
);
2776 sci_redo(doc
->editor
->sci
);
2780 switch (action
->type
)
2782 case UNDO_SCINTILLA
:
2784 document_undo_add(doc
, UNDO_SCINTILLA
, NULL
);
2786 sci_redo(doc
->editor
->sci
);
2791 document_undo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2793 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2794 ui_update_statusbar(doc
, -1);
2795 ui_document_show_hide(doc
);
2800 document_undo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2802 document_set_encoding(doc
, (const gchar
*)action
->data
);
2804 ignore_callback
= TRUE
;
2805 encodings_select_radio_item((const gchar
*)action
->data
);
2806 ignore_callback
= FALSE
;
2808 g_free(action
->data
);
2814 g_free(action
); /* free the action which was taken from the stack */
2816 update_changed_state(doc
);
2817 ui_update_popup_reundo_items(doc
);
2821 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2823 undo_action
*action
;
2825 g_return_if_fail(doc
!= NULL
);
2827 action
= g_new0(undo_action
, 1);
2828 action
->type
= type
;
2829 action
->data
= data
;
2831 g_trash_stack_push(&doc
->priv
->redo_actions
, action
);
2833 document_set_text_changed(doc
, TRUE
);
2834 ui_update_popup_reundo_items(doc
);
2839 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2840 * Returned colors are red if the document has changes, green if the document is read-only
2841 * or simply @c NULL if the document is unmodified but writable.
2843 * @param doc The document to use.
2845 * @return The color for the document or @c NULL if the default color should be used. The color
2846 * object is owned by Geany and should not be modified or freed.
2850 const GdkColor
*document_get_status_color(GeanyDocument
*doc
)
2852 static GdkColor red
= {0, 0xFFFF, 0, 0};
2853 static GdkColor green
= {0, 0, 0x7FFF, 0};
2855 static GdkColor orange
= {0, 0xFFFF, 0x7FFF, 0};
2857 GdkColor
*color
= NULL
;
2859 g_return_val_if_fail(doc
!= NULL
, NULL
);
2864 else if (doc
->priv
->file_disk_status
== FILE_CHANGED
)
2867 else if (doc
->readonly
)
2870 return color
; /* return pointer to static GdkColor. */
2874 /** Accessor function for @ref GeanyData::documents_array items.
2875 * @warning Always check the returned document is valid (@c doc->is_valid).
2876 * @param idx @c documents_array index.
2877 * @return The document, or @c NULL if @a idx is out of range.
2881 GeanyDocument
*document_index(gint idx
)
2883 return (idx
>= 0 && idx
< (gint
) documents_array
->len
) ? documents
[idx
] : NULL
;
2887 /* create a new file and copy file content and properties */
2888 GeanyDocument
*document_clone(GeanyDocument
*old_doc
, const gchar
*utf8_filename
)
2894 g_return_val_if_fail(old_doc
!= NULL
, NULL
);
2896 len
= sci_get_length(old_doc
->editor
->sci
) + 1;
2897 text
= (gchar
*) g_malloc(len
);
2898 sci_get_text(old_doc
->editor
->sci
, len
, text
);
2899 /* use old file type (or maybe NULL for auto detect would be better?) */
2900 doc
= document_new_file(utf8_filename
, old_doc
->file_type
, text
);
2903 /* copy file properties */
2904 doc
->editor
->line_wrapping
= old_doc
->editor
->line_wrapping
;
2905 doc
->readonly
= old_doc
->readonly
;
2906 doc
->has_bom
= old_doc
->has_bom
;
2907 document_set_encoding(doc
, old_doc
->encoding
);
2908 sci_set_lines_wrapped(doc
->editor
->sci
, doc
->editor
->line_wrapping
);
2909 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
2911 ui_document_show_hide(doc
);
2916 /* @note If successful, this should always be followed up with a call to
2917 * document_close_all().
2918 * @return TRUE if all files were saved or had their changes discarded. */
2919 gboolean
document_account_for_unsaved(void)
2921 guint i
, p
, page_count
, len
= documents_array
->len
;
2924 page_count
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
2925 for (p
= 0; p
< page_count
; p
++)
2927 doc
= document_get_from_page(p
);
2928 if (DOC_VALID(doc
) && doc
->changed
)
2930 if (! dialogs_show_unsaved_file(doc
))
2934 /* all documents should now be accounted for, so ignore any changes */
2935 for (i
= 0; i
< len
; i
++)
2938 if (doc
->is_valid
&& doc
->changed
)
2940 doc
->changed
= FALSE
;
2947 static void force_close_all(void)
2949 guint i
, len
= documents_array
->len
;
2951 /* check all documents have been accounted for */
2952 for (i
= 0; i
< len
; i
++)
2954 if (documents
[i
]->is_valid
)
2956 g_return_if_fail(!documents
[i
]->changed
);
2959 main_status
.closing_all
= TRUE
;
2963 document_close(documents
[i
]);
2966 main_status
.closing_all
= FALSE
;
2970 gboolean
document_close_all(void)
2972 if (! document_account_for_unsaved())
2981 static void monitor_reload_file(GeanyDocument
*doc
)
2983 gchar
*base_name
= g_path_get_basename(doc
->file_name
);
2986 ret
= dialogs_show_prompt(NULL
,
2987 GTK_STOCK_CLOSE
, GTK_RESPONSE_CLOSE
,
2988 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
2989 _("_Reload"), GTK_RESPONSE_ACCEPT
,
2990 _("Do you want to reload it?"),
2991 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2995 if (ret
== GTK_RESPONSE_ACCEPT
)
2996 document_reload_file(doc
, doc
->encoding
);
2997 else if (ret
== GTK_RESPONSE_CLOSE
)
2998 document_close(doc
);
3002 static gboolean
monitor_resave_missing_file(GeanyDocument
*doc
)
3004 gboolean want_reload
= FALSE
;
3005 gboolean file_saved
= FALSE
;
3008 ret
= dialogs_show_prompt(NULL
,
3009 _("Close _without saving"), GTK_RESPONSE_CLOSE
,
3010 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
3011 GTK_STOCK_SAVE
, GTK_RESPONSE_ACCEPT
,
3012 _("Try to resave the file?"),
3013 _("File \"%s\" was not found on disk!"),
3015 if (ret
== GTK_RESPONSE_ACCEPT
)
3017 file_saved
= dialogs_show_save_as();
3020 else if (ret
== GTK_RESPONSE_CLOSE
)
3022 document_close(doc
);
3024 if (ret
!= GTK_RESPONSE_CLOSE
&& ! file_saved
)
3026 /* file is missing - set unsaved state */
3027 document_set_text_changed(doc
, TRUE
);
3028 /* don't prompt more than once */
3029 setptr(doc
->real_path
, NULL
);
3036 /* Set force to force a disk check, otherwise it is ignored if there was a check
3037 * in the last file_prefs.disk_check_timeout seconds.
3038 * @return @c TRUE if the file has changed. */
3039 gboolean
document_check_disk_status(GeanyDocument
*doc
, gboolean force
)
3041 gboolean ret
= FALSE
;
3042 gboolean use_gio_filemon
;
3043 time_t cur_time
= 0;
3045 gchar
*locale_filename
;
3046 FileDiskStatus old_status
;
3048 g_return_val_if_fail(doc
!= NULL
, FALSE
);
3050 /* ignore remote files and documents that have never been saved to disk */
3051 if (file_prefs
.disk_check_timeout
== 0 || doc
->real_path
== NULL
|| doc
->priv
->is_remote
)
3054 use_gio_filemon
= (doc
->priv
->monitor
!= NULL
);
3056 if (use_gio_filemon
)
3058 if (doc
->priv
->file_disk_status
!= FILE_CHANGED
&& ! force
)
3063 cur_time
= time(NULL
);
3064 if (! force
&& doc
->priv
->last_check
> (cur_time
- file_prefs
.disk_check_timeout
))
3067 doc
->priv
->last_check
= cur_time
;
3070 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
3071 if (g_stat(locale_filename
, &st
) != 0)
3073 monitor_resave_missing_file(doc
);
3074 /* doc may be closed now */
3077 else if (! use_gio_filemon
&& /* ignore these checks when using GIO */
3078 (G_UNLIKELY(doc
->priv
->mtime
> cur_time
) || G_UNLIKELY(st
.st_mtime
> cur_time
)))
3080 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC
);
3082 else if (doc
->priv
->mtime
< st
.st_mtime
)
3084 doc
->priv
->mtime
= st
.st_mtime
;
3085 monitor_reload_file(doc
);
3086 /* doc may be closed now */
3089 g_free(locale_filename
);
3092 { /* doc can get invalid when a document was closed */
3093 old_status
= doc
->priv
->file_disk_status
;
3094 doc
->priv
->file_disk_status
= FILE_OK
;
3095 if (old_status
!= doc
->priv
->file_disk_status
)
3096 ui_update_tab_status(doc
);