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"
83 GeanyFilePrefs file_prefs
;
85 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
86 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
87 * to a document over time, but it might no longer represent a notebook tab. To check this,
88 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
91 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
92 * although usually you would just use the foreach_document() macro.
94 * Never assume that the order of document pointers is the same as the order of notebook tabs.
95 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
96 GPtrArray
*documents_array
= NULL
;
99 /* an undo action, also used for redo actions */
102 GTrashStack
*next
; /* pointer to the next stack element(required for the GTrashStack) */
103 guint type
; /* to identify the action */
104 gpointer
*data
; /* the old value (before the change), in case of a redo action
105 * it contains the new value */
109 static void document_undo_clear(GeanyDocument
*doc
);
110 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
);
111 static gboolean
update_tags_from_buffer(GeanyDocument
*doc
);
114 /* ignore the case of filenames and paths under WIN32, causes errors if not */
116 #define filenamecmp(a, b) utils_str_casecmp((a), (b))
118 #define filenamecmp(a, b) strcmp((a), (b))
122 * Finds a document whose @c real_path field matches the given filename.
124 * @param realname The filename to search, which should be identical to the
125 * string returned by @c tm_get_real_path().
127 * @return The matching document, or @c NULL.
128 * @note This is only really useful when passing a @c TMWorkObject::file_name.
129 * @see GeanyDocument::real_path.
130 * @see document_find_by_filename().
134 GeanyDocument
* document_find_by_real_path(const gchar
*realname
)
139 return NULL
; /* file doesn't exist on disk */
141 for (i
= 0; i
< documents_array
->len
; i
++)
143 GeanyDocument
*doc
= documents
[i
];
145 if (! doc
->is_valid
|| G_UNLIKELY(! doc
->real_path
))
148 if (filenamecmp(realname
, doc
->real_path
) == 0)
157 /* dereference symlinks, /../ junk in path and return locale encoding */
158 static gchar
*get_real_path_from_utf8(const gchar
*utf8_filename
)
160 gchar
*locale_name
= utils_get_locale_from_utf8(utf8_filename
);
161 gchar
*realname
= tm_get_real_path(locale_name
);
169 * Finds a document with the given filename.
170 * This matches either an exact GeanyDocument::file_name string, or variant
171 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
174 * @param utf8_filename The filename to search (in UTF-8 encoding).
176 * @return The matching document, or @c NULL.
177 * @see document_find_by_real_path().
179 GeanyDocument
*document_find_by_filename(const gchar
*utf8_filename
)
185 g_return_val_if_fail(utf8_filename
!= NULL
, NULL
);
187 /* First search GeanyDocument::file_name, so we can find documents with a
188 * filename set but not saved on disk, like vcdiff produces */
189 for (i
= 0; i
< documents_array
->len
; i
++)
193 if (! doc
->is_valid
|| G_UNLIKELY(doc
->file_name
== NULL
))
196 if (filenamecmp(utf8_filename
, doc
->file_name
) == 0)
201 /* Now try matching based on the realpath(), which is unique per file on disk */
202 realname
= get_real_path_from_utf8(utf8_filename
);
203 doc
= document_find_by_real_path(realname
);
209 /* returns the document which has sci, or NULL. */
210 GeanyDocument
*document_find_by_sci(ScintillaObject
*sci
)
214 g_return_val_if_fail(sci
!= NULL
, NULL
);
216 for (i
= 0; i
< documents_array
->len
; i
++)
218 if (documents
[i
]->is_valid
&& documents
[i
]->editor
->sci
== sci
)
225 /** Gets the notebook page index for a document.
226 * @param doc The document.
229 gint
document_get_notebook_page(GeanyDocument
*doc
)
231 g_return_val_if_fail(doc
!= NULL
, -1);
233 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
),
234 GTK_WIDGET(doc
->editor
->sci
));
239 * Finds the document for the given notebook page @a page_num.
241 * @param page_num The notebook page number to search.
243 * @return The corresponding document for the given notebook page, or @c NULL.
245 GeanyDocument
*document_get_from_page(guint page_num
)
247 ScintillaObject
*sci
;
249 if (page_num
>= documents_array
->len
)
252 sci
= (ScintillaObject
*)gtk_notebook_get_nth_page(
253 GTK_NOTEBOOK(main_widgets
.notebook
), page_num
);
255 return document_find_by_sci(sci
);
260 * Finds the current document.
262 * @return A pointer to the current document or @c NULL if there are no opened documents.
264 GeanyDocument
*document_get_current(void)
266 gint cur_page
= gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets
.notebook
));
272 ScintillaObject
*sci
= (ScintillaObject
*)
273 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets
.notebook
), cur_page
);
275 return document_find_by_sci(sci
);
280 void document_init_doclist()
282 documents_array
= g_ptr_array_new();
286 void document_finalize()
288 g_ptr_array_free(documents_array
, TRUE
);
293 * Returns the last part of the filename of the given GeanyDocument. The result is also
294 * truncated to a maximum of @a length characters in case the filename is very long.
296 * @param doc The document to use.
297 * @param length The length of the resulting string or -1 to use a default value.
299 * @return The ellipsized last part of the filename of @a doc, should be freed when no
304 /* TODO make more use of this */
305 gchar
*document_get_basename_for_display(GeanyDocument
*doc
, gint length
)
307 gchar
*base_name
, *short_name
;
309 g_return_val_if_fail(doc
!= NULL
, NULL
);
314 base_name
= g_path_get_basename(DOC_FILENAME(doc
));
315 short_name
= utils_str_middle_truncate(base_name
, length
);
323 void document_update_tab_label(GeanyDocument
*doc
)
328 g_return_if_fail(doc
!= NULL
);
330 short_name
= document_get_basename_for_display(doc
, -1);
332 /* we need to use the event box for the tooltip, labels don't get the necessary events */
333 parent
= gtk_widget_get_parent(doc
->priv
->tab_label
);
334 parent
= gtk_widget_get_parent(parent
);
336 gtk_label_set_text(GTK_LABEL(doc
->priv
->tab_label
), short_name
);
338 ui_widget_set_tooltip_text(parent
, DOC_FILENAME(doc
));
345 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
346 * according to the document's save state.
347 * This is called by Geany mostly when opening or saving files.
349 * @param doc The document to use.
350 * @param changed Whether the document state should indicate changes have been made.
352 void document_set_text_changed(GeanyDocument
*doc
, gboolean changed
)
354 g_return_if_fail(doc
!= NULL
);
356 doc
->changed
= changed
;
358 if (! main_status
.quitting
)
360 ui_update_tab_status(doc
);
361 ui_save_buttons_toggle(changed
);
362 ui_set_window_title(doc
);
363 ui_update_statusbar(doc
, -1);
368 /* Sets is_valid to FALSE and initializes some members to NULL, to mark it uninitialized.
369 * The flag is_valid is set to TRUE in document_create(). */
370 static void init_doc_struct(GeanyDocument
*new_doc
)
372 GeanyDocumentPrivate
*priv
;
374 memset(new_doc
, 0, sizeof(GeanyDocument
));
376 new_doc
->is_valid
= FALSE
;
377 new_doc
->has_tags
= FALSE
;
378 new_doc
->readonly
= FALSE
;
379 new_doc
->file_name
= NULL
;
380 new_doc
->file_type
= NULL
;
381 new_doc
->tm_file
= NULL
;
382 new_doc
->encoding
= NULL
;
383 new_doc
->has_bom
= FALSE
;
384 new_doc
->editor
= NULL
;
385 new_doc
->changed
= FALSE
;
386 new_doc
->real_path
= NULL
;
388 new_doc
->priv
= g_new0(GeanyDocumentPrivate
, 1);
389 priv
= new_doc
->priv
;
390 priv
->tag_store
= NULL
;
391 priv
->tag_tree
= NULL
;
392 priv
->saved_encoding
.encoding
= NULL
;
393 priv
->saved_encoding
.has_bom
= FALSE
;
394 priv
->undo_actions
= NULL
;
395 priv
->redo_actions
= NULL
;
396 priv
->line_count
= 0;
397 #if ! defined(USE_GIO_FILEMON)
398 priv
->last_check
= time(NULL
);
403 /* returns the next free place in the document list,
404 * or -1 if the documents_array is full */
405 static gint
document_get_new_idx(void)
409 for (i
= 0; i
< documents_array
->len
; i
++)
411 if (documents
[i
]->editor
== NULL
)
420 static void queue_colourise(GeanyDocument
*doc
)
422 /* Colourise the editor before it is next drawn */
423 doc
->priv
->colourise_needed
= TRUE
;
425 /* If the editor doesn't need drawing (e.g. after saving the current
426 * document), we need to force a redraw, so the expose event is triggered.
427 * This ensures we don't start colourising before all documents are opened/saved,
428 * only once the editor is drawn. */
429 gtk_widget_queue_draw(GTK_WIDGET(doc
->editor
->sci
));
434 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor
*monitor
, G_GNUC_UNUSED GFile
*file
,
435 G_GNUC_UNUSED GFile
*other_file
, GFileMonitorEvent event
,
438 g_return_if_fail(doc
!= NULL
);
440 if (file_prefs
.disk_check_timeout
== 0)
443 geany_debug("%s: event: %d previous file status: %d",
444 G_STRFUNC
, event
, doc
->priv
->file_disk_status
);
447 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT
:
449 if (doc
->priv
->file_disk_status
== FILE_IGNORE
)
450 doc
->priv
->file_disk_status
= FILE_OK
;
452 doc
->priv
->file_disk_status
= FILE_CHANGED
;
453 g_message("%s: FILE_CHANGED", G_STRFUNC
);
456 case G_FILE_MONITOR_EVENT_DELETED
:
458 doc
->priv
->file_disk_status
= FILE_CHANGED
;
459 g_message("%s: FILE_MISSING", G_STRFUNC
);
465 if (doc
->priv
->file_disk_status
!= FILE_OK
)
467 ui_update_tab_status(doc
);
473 static void document_stop_file_monitoring(GeanyDocument
*doc
)
475 g_return_if_fail(doc
!= NULL
);
477 if (doc
->priv
->monitor
!= NULL
)
479 g_object_unref(doc
->priv
->monitor
);
480 doc
->priv
->monitor
= NULL
;
485 static void monitor_file_setup(GeanyDocument
*doc
)
487 g_return_if_fail(doc
!= NULL
);
488 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
489 * doesn't work at all for remote files and legacy polling is too slow. */
490 if (! doc
->priv
->is_remote
)
493 gchar
*locale_filename
;
495 /* stop any previous monitoring */
496 document_stop_file_monitoring(doc
);
498 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
499 if (locale_filename
!= NULL
&& g_file_test(locale_filename
, G_FILE_TEST_EXISTS
))
501 /* get a file monitor and connect to the 'changed' signal */
502 GFile
*file
= g_file_new_for_path(locale_filename
);
503 doc
->priv
->monitor
= g_file_monitor_file(file
, G_FILE_MONITOR_NONE
, NULL
, NULL
);
504 g_signal_connect(doc
->priv
->monitor
, "changed",
505 G_CALLBACK(monitor_file_changed_cb
), doc
);
507 /* we set the rate limit according to the GUI pref but it's most probably not used */
508 g_file_monitor_set_rate_limit(doc
->priv
->monitor
, file_prefs
.disk_check_timeout
* 1000);
510 g_object_unref(file
);
512 g_free(locale_filename
);
515 doc
->priv
->file_disk_status
= FILE_OK
;
519 void document_try_focus(GeanyDocument
*doc
, GtkWidget
*source_widget
)
521 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
524 GtkWidget
*sci
= GTK_WIDGET(doc
->editor
->sci
);
525 GtkWidget
*focusw
= gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
));
527 if (source_widget
== NULL
)
528 source_widget
= doc
->priv
->tag_tree
;
530 if (focusw
== source_widget
)
531 gtk_widget_grab_focus(sci
);
536 static gboolean
on_idle_focus(gpointer doc
)
538 document_try_focus(doc
, NULL
);
543 /* Creates a new document and editor, adding a tab in the notebook.
544 * @return The created document */
545 static GeanyDocument
*document_create(const gchar
*utf8_filename
)
549 gint cur_pages
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
553 GeanyDocument
*cur
= document_get_current();
554 /* remove the empty document and open a new one */
555 if (cur
!= NULL
&& cur
->file_name
== NULL
&& ! cur
->changed
)
556 document_remove_page(0);
559 new_idx
= document_get_new_idx();
560 if (new_idx
== -1) /* expand the array, no free places */
562 GeanyDocument
*new_doc
= g_new0(GeanyDocument
, 1);
564 new_idx
= documents_array
->len
;
565 g_ptr_array_add(documents_array
, new_doc
);
567 doc
= documents
[new_idx
];
568 init_doc_struct(doc
); /* initialize default document settings */
569 doc
->index
= new_idx
;
571 doc
->file_name
= g_strdup(utf8_filename
);
573 doc
->editor
= editor_create(doc
);
575 sidebar_openfiles_add(doc
); /* sets doc->iter */
577 notebook_new_tab(doc
);
579 /* select document in sidebar */
581 GtkTreeSelection
*sel
;
583 sel
= gtk_tree_view_get_selection(GTK_TREE_VIEW(tv
.tree_openfiles
));
584 gtk_tree_selection_select_iter(sel
, &doc
->priv
->iter
);
587 ui_document_buttons_update();
589 doc
->is_valid
= TRUE
; /* do this last to prevent UI updating with NULL items. */
595 * Closes the given document.
597 * @param doc The document to remove.
599 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
603 gboolean
document_close(GeanyDocument
*doc
)
605 g_return_val_if_fail(doc
, FALSE
);
607 return document_remove_page(document_get_notebook_page(doc
));
612 * Removes the given notebook tab at @a page_num and clears all related information
613 * in the document list.
615 * @param page_num The notebook page number to remove.
617 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
619 gboolean
document_remove_page(guint page_num
)
621 GeanyDocument
*doc
= document_get_from_page(page_num
);
623 if (G_UNLIKELY(doc
== NULL
))
625 g_warning("%s: page_num: %d", G_STRFUNC
, page_num
);
629 if (doc
->changed
&& ! dialogs_show_unsaved_file(doc
))
634 /* tell any plugins that the document is about to be closed */
635 g_signal_emit_by_name(geany_object
, "document-close", doc
);
637 /* Checking real_path makes it likely the file exists on disk */
638 if (! main_status
.closing_all
&& doc
->real_path
!= NULL
)
639 ui_add_recent_file(doc
->file_name
);
641 doc
->is_valid
= FALSE
;
643 if (! main_status
.quitting
)
645 notebook_remove_page(page_num
);
646 sidebar_remove_document(doc
);
647 navqueue_remove_file(doc
->file_name
);
648 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc
));
650 g_free(doc
->encoding
);
651 g_free(doc
->priv
->saved_encoding
.encoding
);
652 g_free(doc
->file_name
);
653 g_free(doc
->real_path
);
654 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
656 editor_destroy(doc
->editor
);
659 document_stop_file_monitoring(doc
);
661 doc
->file_name
= NULL
;
662 doc
->real_path
= NULL
;
663 doc
->file_type
= NULL
;
664 doc
->encoding
= NULL
;
665 doc
->has_bom
= FALSE
;
667 document_undo_clear(doc
);
670 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
672 sidebar_update_tag_list(NULL
, FALSE
);
673 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
674 ui_set_window_title(NULL
);
675 ui_save_buttons_toggle(FALSE
);
676 ui_update_popup_reundo_items(NULL
);
677 ui_document_buttons_update();
678 build_menu_update(NULL
);
684 /* used to keep a record of the unchanged document state encoding */
685 static void store_saved_encoding(GeanyDocument
*doc
)
687 g_free(doc
->priv
->saved_encoding
.encoding
);
688 doc
->priv
->saved_encoding
.encoding
= g_strdup(doc
->encoding
);
689 doc
->priv
->saved_encoding
.has_bom
= doc
->has_bom
;
693 /* Opens a new empty document only if there are no other documents open */
694 GeanyDocument
*document_new_file_if_non_open(void)
696 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
697 return document_new_file(NULL
, NULL
, NULL
);
704 * Creates a new document.
705 * Afterwards, the @c "document-new" signal is emitted for plugins.
707 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
708 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
709 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
711 * @return The new document.
713 GeanyDocument
*document_new_file(const gchar
*utf8_filename
, GeanyFiletype
*ft
,
718 if (utf8_filename
&& g_path_is_absolute(utf8_filename
))
721 tmp
= utils_strdupa(utf8_filename
); /* work around const */
722 utils_tidy_path(tmp
);
725 doc
= document_create(utf8_filename
);
727 g_assert(doc
!= NULL
);
729 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
731 sci_set_text(doc
->editor
->sci
, text
);
733 sci_clear_all(doc
->editor
->sci
);
735 sci_set_eol_mode(doc
->editor
->sci
, file_prefs
.default_eol_character
);
736 /* convert the eol chars in the template text in case they are different from
737 * from file_prefs.default_eol */
739 sci_convert_eols(doc
->editor
->sci
, file_prefs
.default_eol_character
);
741 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
742 sci_empty_undo_buffer(doc
->editor
->sci
);
744 doc
->encoding
= g_strdup(encodings
[file_prefs
.default_new_encoding
].charset
);
745 /* store the opened encoding for undo/redo */
746 store_saved_encoding(doc
);
748 if (ft
== NULL
&& utf8_filename
!= NULL
) /* guess the filetype from the filename if one is given */
749 ft
= filetypes_detect_from_document(doc
);
751 document_set_filetype(doc
, ft
); /* also clears taglist */
753 ui_set_window_title(doc
);
754 build_menu_update(doc
);
755 document_update_tag_list(doc
, FALSE
);
756 document_set_text_changed(doc
, FALSE
);
757 ui_document_show_hide(doc
); /* update the document menu */
759 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
760 /* bring it in front, jump to the start and grab the focus */
761 editor_goto_pos(doc
->editor
, 0, FALSE
);
762 document_try_focus(doc
, NULL
);
765 monitor_file_setup(doc
);
767 doc
->priv
->mtime
= time(NULL
);
770 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
771 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
), doc
->editor
);
773 g_signal_emit_by_name(geany_object
, "document-new", doc
);
775 msgwin_status_add(_("New file \"%s\" opened."),
783 * Opens a document specified by @a locale_filename.
784 * Afterwards, the @c "document-open" signal is emitted for plugins.
786 * @param locale_filename The filename of the document to load, in locale encoding.
787 * @param readonly Whether to open the document in read-only mode.
788 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
789 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
791 * @return The document opened or @c NULL.
793 GeanyDocument
*document_open_file(const gchar
*locale_filename
, gboolean readonly
,
794 GeanyFiletype
*ft
, const gchar
*forced_enc
)
796 return document_open_file_full(NULL
, locale_filename
, 0, readonly
, ft
, forced_enc
);
802 gchar
*data
; /* null-terminated file data */
803 gsize size
; /* actual file size on disk */
804 gsize len
; /* string length of data */
807 time_t mtime
; /* modification time, read by stat::st_mtime */
812 /* reload file with specified encoding */
814 handle_forced_encoding(FileData
*filedata
, const gchar
*forced_enc
)
816 GeanyEncodingIndex enc_idx
;
818 if (utils_str_equal(forced_enc
, "UTF-8"))
820 if (! g_utf8_validate(filedata
->data
, filedata
->len
, NULL
))
827 gchar
*converted_text
= encodings_convert_to_utf8_from_charset(
828 filedata
->data
, filedata
->size
, forced_enc
, FALSE
);
829 if (converted_text
== NULL
)
835 g_free(filedata
->data
);
836 filedata
->data
= converted_text
;
837 filedata
->len
= strlen(converted_text
);
840 enc_idx
= encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, NULL
);
841 filedata
->bom
= (enc_idx
== GEANY_ENCODING_UTF_8
);
842 filedata
->enc
= g_strdup(forced_enc
);
847 /* detect encoding and convert to UTF-8 if necessary */
849 handle_encoding(FileData
*filedata
, GeanyEncodingIndex enc_idx
)
851 g_return_val_if_fail(filedata
->enc
== NULL
, FALSE
);
852 g_return_val_if_fail(filedata
->bom
== FALSE
, FALSE
);
854 if (filedata
->size
== 0)
856 /* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
857 * e.g. UTF32 file with a BOM(so size is 4, len is 0) */
858 filedata
->enc
= g_strdup("UTF-8");
862 /* first check for a BOM */
863 if (enc_idx
!= GEANY_ENCODING_NONE
)
865 filedata
->enc
= g_strdup(encodings
[enc_idx
].charset
);
866 filedata
->bom
= TRUE
;
868 if (enc_idx
!= GEANY_ENCODING_UTF_8
) /* the BOM indicated something else than UTF-8 */
870 gchar
*converted_text
= encodings_convert_to_utf8_from_charset(
871 filedata
->data
, filedata
->size
, filedata
->enc
, FALSE
);
872 if (converted_text
!= NULL
)
874 g_free(filedata
->data
);
875 filedata
->data
= converted_text
;
876 filedata
->len
= strlen(converted_text
);
880 /* there was a problem converting data from BOM encoding type */
881 g_free(filedata
->enc
);
882 filedata
->enc
= NULL
;
883 filedata
->bom
= FALSE
;
888 if (filedata
->enc
== NULL
) /* either there was no BOM or the BOM encoding failed */
890 /* try UTF-8 first */
891 if ((filedata
->size
== filedata
->len
) &&
892 g_utf8_validate(filedata
->data
, filedata
->len
, NULL
))
894 filedata
->enc
= g_strdup("UTF-8");
898 /* detect the encoding */
899 gchar
*converted_text
= encodings_convert_to_utf8(filedata
->data
,
900 filedata
->size
, &filedata
->enc
);
902 if (converted_text
== NULL
)
906 g_free(filedata
->data
);
907 filedata
->data
= converted_text
;
908 filedata
->len
= strlen(converted_text
);
917 handle_bom(FileData
*filedata
)
921 encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, &bom_len
);
922 g_return_if_fail(bom_len
!= 0);
924 /* use filedata->len here because the contents are already converted into UTF-8 */
925 filedata
->len
-= bom_len
;
926 /* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
927 g_memmove(filedata
->data
, filedata
->data
+ bom_len
, filedata
->len
+ 1);
928 filedata
->data
= g_realloc(filedata
->data
, filedata
->len
+ 1);
932 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
933 static gboolean
load_text_file(const gchar
*locale_filename
, const gchar
*display_filename
,
934 FileData
*filedata
, const gchar
*forced_enc
)
938 GeanyEncodingIndex tmp_enc_idx
;
940 filedata
->data
= NULL
;
942 filedata
->enc
= NULL
;
943 filedata
->bom
= FALSE
;
944 filedata
->readonly
= FALSE
;
946 if (g_stat(locale_filename
, &st
) != 0)
948 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"),
949 display_filename
, g_strerror(errno
));
953 filedata
->mtime
= st
.st_mtime
;
955 if (! g_file_get_contents(locale_filename
, &filedata
->data
, NULL
, &err
))
957 ui_set_statusbar(TRUE
, "%s", err
->message
);
962 /* use strlen to check for null chars */
963 filedata
->size
= (gsize
) st
.st_size
;
964 filedata
->len
= strlen(filedata
->data
);
966 /* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
967 * if we have a BOM */
968 tmp_enc_idx
= encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, NULL
);
970 /* check whether the size of the loaded data is equal to the size of the file in the
971 * filesystem file size may be 0 to allow opening files in /proc/ which have typically a
972 * file size of 0 bytes */
973 if (filedata
->len
!= filedata
->size
&& filedata
->size
!= 0 && (
974 tmp_enc_idx
== GEANY_ENCODING_UTF_8
|| /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
975 tmp_enc_idx
== GEANY_ENCODING_UTF_7
)) /* filter UTF-7/8 where no NULL bytes are allowed */
977 const gchar
*warn_msg
= _(
978 "The file \"%s\" could not be opened properly and has been truncated. " \
979 "This can occur if the file contains a NULL byte. " \
980 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
982 if (main_status
.main_window_realized
)
983 dialogs_show_msgbox(GTK_MESSAGE_WARNING
, warn_msg
, display_filename
);
985 ui_set_statusbar(TRUE
, warn_msg
, display_filename
);
987 /* set the file to read-only mode because saving it is probably dangerous */
988 filedata
->readonly
= TRUE
;
991 /* Determine character encoding and convert to UTF-8 */
992 if (forced_enc
!= NULL
)
994 /* the encoding should be ignored(requested by user), so open the file "as it is" */
995 if (utils_str_equal(forced_enc
, encodings
[GEANY_ENCODING_NONE
].charset
))
997 filedata
->bom
= FALSE
;
998 filedata
->enc
= g_strdup(encodings
[GEANY_ENCODING_NONE
].charset
);
1000 else if (! handle_forced_encoding(filedata
, forced_enc
))
1002 /* For translators: the second wildcard is an encoding name, e.g.
1003 * The file \"test.txt\" is not valid UTF-8. */
1004 ui_set_statusbar(TRUE
, _("The file \"%s\" is not valid %s."),
1005 display_filename
, forced_enc
);
1007 g_free(filedata
->data
);
1011 else if (! handle_encoding(filedata
, tmp_enc_idx
))
1013 ui_set_statusbar(TRUE
,
1014 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1017 g_free(filedata
->data
);
1022 handle_bom(filedata
);
1027 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1028 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1029 * if cl_options.goto_column is set.
1031 * returns the new position which may have changed */
1032 static gint
set_cursor_position(GeanyEditor
*editor
, gint pos
)
1034 if (cl_options
.goto_line
>= 0)
1035 { /* goto line which was specified on command line and then undefine the line */
1036 sci_goto_line(editor
->sci
, cl_options
.goto_line
- 1, TRUE
);
1037 editor
->scroll_percent
= 0.5F
;
1038 cl_options
.goto_line
= -1;
1042 sci_set_current_position(editor
->sci
, pos
, FALSE
);
1043 editor
->scroll_percent
= 0.5F
;
1046 if (cl_options
.goto_column
>= 0)
1047 { /* goto column which was specified on command line and then undefine the column */
1049 gint new_pos
= sci_get_current_position(editor
->sci
) + cl_options
.goto_column
;
1050 sci_set_current_position(editor
->sci
, new_pos
, FALSE
);
1051 editor
->scroll_percent
= 0.5F
;
1052 cl_options
.goto_column
= -1;
1055 return sci_get_current_position(editor
->sci
);
1059 /* Count lines that start with some hard tabs then a soft tab. */
1060 static gboolean
detect_tabs_and_spaces(GeanyEditor
*editor
)
1062 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1063 ScintillaObject
*sci
= editor
->sci
;
1065 struct Sci_TextToFind ttf
;
1066 gchar
*soft_tab
= g_strnfill(iprefs
->width
, ' ');
1067 gchar
*regex
= g_strconcat("^\t+", soft_tab
, "[^ ]", NULL
);
1072 ttf
.chrg
.cpMax
= sci_get_length(sci
);
1073 ttf
.lpstrText
= regex
;
1078 pos
= sci_find_text(sci
, SCFIND_REGEXP
, &ttf
);
1080 break; /* no more matches */
1082 ttf
.chrg
.cpMin
= ttf
.chrgText
.cpMax
+ 1; /* search after this match */
1085 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1086 return count
> sci_get_line_count(sci
) * 0.02;
1090 /* Detect the indent type based on counting the leading indent characters for each line. */
1091 static GeanyIndentType
detect_indent_type(GeanyEditor
*editor
)
1093 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1094 ScintillaObject
*sci
= editor
->sci
;
1095 guint line
, line_count
;
1096 gsize tabs
= 0, spaces
= 0;
1098 if (detect_tabs_and_spaces(editor
))
1099 return GEANY_INDENT_TYPE_BOTH
;
1101 line_count
= sci_get_line_count(sci
);
1102 for (line
= 0; line
< line_count
; line
++)
1104 gint pos
= sci_get_position_from_line(sci
, line
);
1107 /* most code will have indent total <= 24, otherwise it's more likely to be
1108 * alignment than indentation */
1109 if (sci_get_line_indentation(sci
, line
) > 24)
1112 c
= sci_get_char_at(sci
, pos
);
1118 /* check for at least 2 spaces */
1119 if (sci_get_char_at(sci
, pos
+ 1) == ' ')
1123 if (spaces
== 0 && tabs
== 0)
1124 return iprefs
->type
;
1126 /* the factors may need to be tweaked */
1127 if (spaces
> tabs
* 4)
1128 return GEANY_INDENT_TYPE_SPACES
;
1129 else if (tabs
> spaces
* 4)
1130 return GEANY_INDENT_TYPE_TABS
;
1132 return GEANY_INDENT_TYPE_BOTH
;
1136 void document_apply_indent_settings(GeanyDocument
*doc
)
1138 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
1139 GeanyIndentType type
= iprefs
->type
;
1141 switch (FILETYPE_ID(doc
->file_type
))
1143 case GEANY_FILETYPES_MAKE
:
1144 /* force using tabs for indentation for Makefiles */
1145 editor_set_indent_type(doc
->editor
, GEANY_INDENT_TYPE_TABS
);
1147 case GEANY_FILETYPES_F77
:
1148 /* force using spaces for indentation for Fortran 77 */
1149 editor_set_indent_type(doc
->editor
, GEANY_INDENT_TYPE_SPACES
);
1152 if (iprefs
->detect_type
)
1154 type
= detect_indent_type(doc
->editor
);
1156 if (type
!= iprefs
->type
)
1158 const gchar
*name
= NULL
;
1162 case GEANY_INDENT_TYPE_SPACES
:
1165 case GEANY_INDENT_TYPE_TABS
:
1168 case GEANY_INDENT_TYPE_BOTH
:
1169 name
= _("Tabs and Spaces");
1172 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1173 * and Spaces), the second one is the filename */
1174 ui_set_statusbar(TRUE
, _("Setting %s indentation mode for %s."), name
,
1178 editor_set_indent_type(doc
->editor
, type
);
1183 static gboolean
auto_update_tag_list(gpointer data
)
1185 GeanyDocument
*doc
= data
;
1187 if (! doc
|| ! doc
->is_valid
|| doc
->tm_file
== NULL
)
1190 if (gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
)) != GTK_WIDGET(doc
->editor
->sci
))
1193 if (update_tags_from_buffer(doc
))
1194 sidebar_update_tag_list(doc
, TRUE
);
1201 /* To open a new file, set doc to NULL; filename should be locale encoded.
1202 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1203 * pos is the cursor position, which can be overridden by --line and --column.
1204 * forced_enc can be NULL to detect the file encoding.
1205 * Returns: doc of the opened file or NULL if an error occurred. */
1206 GeanyDocument
*document_open_file_full(GeanyDocument
*doc
, const gchar
*filename
, gint pos
,
1207 gboolean readonly
, GeanyFiletype
*ft
, const gchar
*forced_enc
)
1210 gboolean reload
= (doc
== NULL
) ? FALSE
: TRUE
;
1211 gchar
*utf8_filename
= NULL
;
1212 gchar
*display_filename
= NULL
;
1213 gchar
*locale_filename
= NULL
;
1214 GeanyFiletype
*use_ft
;
1219 utf8_filename
= g_strdup(doc
->file_name
);
1220 locale_filename
= utils_get_locale_from_utf8(utf8_filename
);
1224 /* filename must not be NULL when opening a file */
1225 if (filename
== NULL
)
1227 ui_set_statusbar(FALSE
, _("Invalid filename"));
1232 /* if filename is a shortcut, try to resolve it */
1233 locale_filename
= win32_get_shortcut_target(filename
);
1235 locale_filename
= g_strdup(filename
);
1237 /* remove relative junk */
1238 utils_tidy_path(locale_filename
);
1240 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1241 utf8_filename
= utils_get_utf8_from_locale(locale_filename
);
1243 /* if file is already open, switch to it and go */
1244 doc
= document_find_by_filename(utf8_filename
);
1247 ui_add_recent_file(utf8_filename
); /* either add or reorder recent item */
1248 /* show the doc before reload dialog */
1249 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets
.notebook
),
1250 gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
),
1251 (GtkWidget
*) doc
->editor
->sci
));
1252 document_check_disk_status(doc
, TRUE
); /* force a file changed check */
1255 if (reload
|| doc
== NULL
)
1256 { /* doc possibly changed */
1257 display_filename
= utils_str_middle_truncate(utf8_filename
, 100);
1259 if (! load_text_file(locale_filename
, display_filename
, &filedata
, forced_enc
))
1261 g_free(display_filename
);
1262 g_free(utf8_filename
);
1263 g_free(locale_filename
);
1269 doc
= document_create(utf8_filename
);
1270 g_return_val_if_fail(doc
!= NULL
, NULL
); /* really should not happen */
1272 /* file exists on disk, set real_path */
1273 setptr(doc
->real_path
, tm_get_real_path(locale_filename
));
1275 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1276 monitor_file_setup(doc
);
1279 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
1280 sci_empty_undo_buffer(doc
->editor
->sci
);
1282 /* add the text to the ScintillaObject */
1283 sci_set_readonly(doc
->editor
->sci
, FALSE
); /* to allow replacing text */
1284 sci_set_text(doc
->editor
->sci
, filedata
.data
); /* NULL terminated data */
1285 queue_colourise(doc
); /* Ensure the document gets colourised. */
1287 /* detect & set line endings */
1288 editor_mode
= utils_get_line_endings(filedata
.data
, filedata
.len
);
1289 sci_set_eol_mode(doc
->editor
->sci
, editor_mode
);
1290 g_free(filedata
.data
);
1292 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
1294 doc
->priv
->mtime
= filedata
.mtime
; /* get the modification time from file and keep it */
1295 g_free(doc
->encoding
); /* if reloading, free old encoding */
1296 doc
->encoding
= filedata
.enc
;
1297 doc
->has_bom
= filedata
.bom
;
1298 store_saved_encoding(doc
); /* store the opened encoding for undo/redo */
1300 doc
->readonly
= readonly
|| filedata
.readonly
;
1301 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
1303 /* update line number margin width */
1304 doc
->priv
->line_count
= sci_get_line_count(doc
->editor
->sci
);
1305 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
1310 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1311 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
),
1314 use_ft
= (ft
!= NULL
) ? ft
: filetypes_detect_from_document(doc
);
1318 document_undo_clear(doc
);
1322 /* update taglist, typedef keywords and build menu if necessary */
1323 document_set_filetype(doc
, use_ft
);
1325 /* set indentation settings after setting the filetype */
1327 editor_set_indent_type(doc
->editor
, doc
->editor
->indent_type
); /* resetup sci */
1329 document_apply_indent_settings(doc
);
1331 document_set_text_changed(doc
, FALSE
); /* also updates tab state */
1332 ui_document_show_hide(doc
); /* update the document menu */
1334 /* finally add current file to recent files menu, but not the files from the last session */
1335 if (! main_status
.opening_session_files
)
1336 ui_add_recent_file(utf8_filename
);
1339 g_signal_emit_by_name(geany_object
, "document-open", doc
);
1342 ui_set_statusbar(TRUE
, _("File %s reloaded."), display_filename
);
1344 /* For translators: this is the status window message for opening a file. %d is the number
1345 * of the newly opened file, %s indicates whether the file is opened read-only
1346 * (it is replaced with the string ", read-only"). */
1347 msgwin_status_add(_("File %s opened(%d%s)."),
1348 display_filename
, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)),
1349 (readonly
) ? _(", read-only") : "");
1352 g_free(display_filename
);
1353 g_free(utf8_filename
);
1354 g_free(locale_filename
);
1356 /* TODO This could be used to automatically update the symbol list,
1357 * based on a configurable interval */
1358 /*g_timeout_add(10000, auto_update_tag_list, doc);*/
1360 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1361 pos
= set_cursor_position(doc
->editor
, pos
);
1362 /* now bring the file in front */
1363 editor_goto_pos(doc
->editor
, pos
, FALSE
);
1365 /* finally, let the editor widget grab the focus so you can start coding
1367 g_idle_add(on_idle_focus
, doc
);
1372 /* Takes a new line separated list of filename URIs and opens each file.
1373 * length is the length of the string or -1 if it should be detected */
1374 void document_open_file_list(const gchar
*data
, gssize length
)
1380 g_return_if_fail(data
!= NULL
);
1383 length
= strlen(data
);
1385 switch (utils_get_line_endings(data
, length
))
1387 case SC_EOL_CR
: list
= g_strsplit(data
, "\r", 0); break;
1388 case SC_EOL_CRLF
: list
= g_strsplit(data
, "\r\n", 0); break;
1389 case SC_EOL_LF
: list
= g_strsplit(data
, "\n", 0); break;
1390 default: list
= g_strsplit(data
, "\n", 0);
1395 if (list
[i
] == NULL
)
1397 filename
= g_filename_from_uri(list
[i
], NULL
, NULL
);
1398 if (G_UNLIKELY(filename
== NULL
))
1400 document_open_file(filename
, FALSE
, NULL
, NULL
);
1409 * Opens each file in the list @a filenames.
1410 * Internally, document_open_file() is called for every list item.
1412 * @param filenames A list of filenames to load, in locale encoding.
1413 * @param readonly Whether to open the document in read-only mode.
1414 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1415 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1417 void document_open_files(const GSList
*filenames
, gboolean readonly
, GeanyFiletype
*ft
,
1418 const gchar
*forced_enc
)
1422 for (item
= filenames
; item
!= NULL
; item
= g_slist_next(item
))
1424 document_open_file(item
->data
, readonly
, ft
, forced_enc
);
1430 * Reloads the document with the specified file encoding
1431 * @a forced_enc or @c NULL to auto-detect the file encoding.
1433 * @param doc The document to reload.
1434 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1436 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1438 gboolean
document_reload_file(GeanyDocument
*doc
, const gchar
*forced_enc
)
1441 GeanyDocument
*new_doc
;
1443 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1445 /* try to set the cursor to the position before reloading */
1446 pos
= sci_get_current_position(doc
->editor
->sci
);
1447 new_doc
= document_open_file_full(doc
, NULL
, pos
, doc
->readonly
, doc
->file_type
, forced_enc
);
1449 return (new_doc
!= NULL
);
1453 static gboolean
document_update_timestamp(GeanyDocument
*doc
, const gchar
*locale_filename
)
1455 #if ! USE_GIO_FILEMON
1458 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1460 /* stat the file to get the timestamp, otherwise on Windows the actual
1461 * timestamp can be ahead of time(NULL) */
1462 if (g_stat(locale_filename
, &st
) != 0)
1464 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"), doc
->file_name
,
1469 doc
->priv
->mtime
= st
.st_mtime
; /* get the modification time from file and keep it */
1475 /* Sets line and column to the given position byte_pos in the document.
1476 * byte_pos is the position counted in bytes, not characters */
1477 static void get_line_column_from_pos(GeanyDocument
*doc
, guint byte_pos
, gint
*line
, gint
*column
)
1482 /* for some reason we can use byte count instead of character count here */
1483 *line
= sci_get_line_from_position(doc
->editor
->sci
, byte_pos
);
1484 line_start
= sci_get_position_from_line(doc
->editor
->sci
, *line
);
1485 /* get the column in the line */
1486 *column
= byte_pos
- line_start
;
1488 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1489 * skip one byte(i++) and decrease the column number which is based on byte count */
1490 for (i
= line_start
; i
< (line_start
+ *column
); i
++)
1492 if (sci_get_char_at(doc
->editor
->sci
, i
) < 0)
1501 static void replace_header_filename(GeanyDocument
*doc
)
1505 struct Sci_TextToFind ttf
;
1507 g_return_if_fail(doc
!= NULL
);
1508 g_return_if_fail(doc
->file_type
!= NULL
);
1510 if (doc
->file_type
->extension
)
1511 filebase
= g_strconcat("\\<", GEANY_STRING_UNTITLED
, "\\.\\w+", NULL
);
1513 filebase
= g_strdup(GEANY_STRING_UNTITLED
);
1515 filename
= g_path_get_basename(doc
->file_name
);
1517 /* only search the first 3 lines */
1519 ttf
.chrg
.cpMax
= sci_get_position_from_line(doc
->editor
->sci
, 3);
1520 ttf
.lpstrText
= filebase
;
1522 if (search_find_text(doc
->editor
->sci
, SCFIND_MATCHCASE
| SCFIND_REGEXP
, &ttf
) != -1)
1524 sci_set_target_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1525 sci_set_target_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1526 sci_replace_target(doc
->editor
->sci
, filename
, FALSE
);
1534 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1535 * you still have to call @ref document_save_file_as() to change the @a doc object.
1536 * It also stops monitoring for file changes to prevent receiving too many file change events
1537 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1539 * @param doc The current document which should be renamed.
1540 * @param new_filename The new filename in UTF-8 encoding.
1544 void document_rename_file(GeanyDocument
*doc
, const gchar
*new_filename
)
1546 gchar
*old_locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1547 gchar
*new_locale_filename
= utils_get_locale_from_utf8(new_filename
);
1550 /* stop file monitoring to avoid getting events for deleting/creating files,
1551 * it's re-setup in document_save_file_as() */
1552 document_stop_file_monitoring(doc
);
1554 result
= g_rename(old_locale_filename
, new_locale_filename
);
1557 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
,
1558 _("Error renaming file."), g_strerror(errno
));
1560 g_free(old_locale_filename
);
1561 g_free(new_locale_filename
);
1565 /* Return TRUE if the document hasn't been saved before, i.e. either the filename or
1566 * the real_path is not set. */
1567 gboolean
document_need_save_as(GeanyDocument
*doc
)
1569 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1571 return (doc
->file_name
== NULL
|| doc
->real_path
== NULL
);
1576 * Saves the document, detecting the filetype.
1578 * @param doc The document for the file to save.
1579 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1580 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1582 * @see document_save_file().
1586 gboolean
document_save_file_as(GeanyDocument
*doc
, const gchar
*utf8_fname
)
1590 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1592 if (utf8_fname
!= NULL
)
1593 setptr(doc
->file_name
, g_strdup(utf8_fname
));
1595 /* reset real path, it's retrieved again in document_save() */
1596 setptr(doc
->real_path
, NULL
);
1598 /* detect filetype */
1599 if (FILETYPE_ID(doc
->file_type
) == GEANY_FILETYPES_NONE
)
1601 GeanyFiletype
*ft
= filetypes_detect_from_document(doc
);
1603 document_set_filetype(doc
, ft
);
1604 if (document_get_current() == doc
)
1606 ignore_callback
= TRUE
;
1607 filetypes_select_radio_item(doc
->file_type
);
1608 ignore_callback
= FALSE
;
1611 replace_header_filename(doc
);
1613 ret
= document_save_file(doc
, TRUE
);
1615 /* file monitoring support, add file monitoring after the file has been saved
1616 * to ignore any earlier events */
1617 monitor_file_setup(doc
);
1618 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1621 ui_add_recent_file(doc
->file_name
);
1626 static gsize
save_convert_to_encoding(GeanyDocument
*doc
, gchar
**data
, gsize
*len
)
1628 GError
*conv_error
= NULL
;
1629 gchar
* conv_file_contents
= NULL
;
1633 g_return_val_if_fail(data
!= NULL
|| *data
== NULL
, FALSE
);
1634 g_return_val_if_fail(len
!= NULL
, FALSE
);
1636 /* try to convert it from UTF-8 to original encoding */
1637 conv_file_contents
= g_convert(*data
, *len
- 1, doc
->encoding
, "UTF-8",
1638 &bytes_read
, &conv_len
, &conv_error
);
1640 if (conv_error
!= NULL
)
1642 gchar
*text
= g_strdup_printf(
1643 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1647 if (conv_error
->code
== G_CONVERT_ERROR_ILLEGAL_SEQUENCE
)
1649 gchar
*context
= NULL
;
1653 /* don't read over the doc length */
1654 gint max_len
= MIN((gint
)bytes_read
+ 6, (gint
)*len
- 1);
1655 context
= g_malloc(7); /* read 6 bytes from Sci + '\0' */
1656 sci_get_text_range(doc
->editor
->sci
, bytes_read
, max_len
, context
);
1658 /* take only one valid Unicode character from the context and discard the leftover */
1659 unic
= g_utf8_get_char_validated(context
, -1);
1660 context_len
= g_unichar_to_utf8(unic
, context
);
1661 context
[context_len
] = '\0';
1662 get_line_column_from_pos(doc
, bytes_read
, &line
, &column
);
1664 error_text
= g_strdup_printf(
1665 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1666 conv_error
->message
, context
, line
+ 1, column
);
1670 error_text
= g_strdup_printf(_("Error message: %s."), conv_error
->message
);
1672 geany_debug("encoding error: %s", conv_error
->message
);
1673 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, text
, error_text
);
1674 g_error_free(conv_error
);
1682 *data
= conv_file_contents
;
1690 static gchar
*write_data_to_disk(GeanyDocument
*doc
, const gchar
*locale_filename
,
1691 const gchar
*data
, gint len
)
1693 GError
*error
= NULL
;
1695 g_return_val_if_fail(doc
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1696 g_return_val_if_fail(data
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1698 if (! file_prefs
.use_safe_file_saving
)
1702 gboolean fail
= FALSE
;
1704 /* Use POSIX API to preserve file metadata */
1706 fp
= g_fopen(locale_filename
, "wb");
1712 bytes_written
= fwrite(data
, sizeof(gchar
), len
, fp
);
1714 if (len
!= bytes_written
)
1717 if (fclose(fp
) != 0)
1722 return g_strdup(g_strerror(errno
));
1727 g_file_set_contents(locale_filename
, data
, len
, &error
);
1730 gchar
*msg
= g_strdup(error
->message
);
1731 g_error_free(error
);
1736 /* now the file is on disk, set real_path */
1737 if (doc
->real_path
== NULL
)
1739 doc
->real_path
= tm_get_real_path(locale_filename
);
1740 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1741 monitor_file_setup(doc
);
1749 * Saves the document. Saving includes replacing tabs by spaces,
1750 * stripping trailing spaces and adding a final new line at the end of the file (all only if
1751 * user enabled these features). Then the @c "document-before-save" signal is emitted,
1752 * allowing plugins to modify the document before it is saved, and data is
1753 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1754 * Afterwards, the @c "document-save" signal is emitted for plugins.
1756 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1758 * @param doc The document to save.
1759 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1761 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1763 gboolean
document_save_file(GeanyDocument
*doc
, gboolean force
)
1768 gchar
*locale_filename
;
1770 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1772 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1773 if (! force
&& ! ui_prefs
.allow_always_save
&& (! doc
->changed
|| doc
->readonly
))
1776 if (G_UNLIKELY(doc
->file_name
== NULL
))
1778 ui_set_statusbar(TRUE
, _("Error saving file."));
1783 /* replaces tabs by spaces but only if the current file is not a Makefile */
1784 if (file_prefs
.replace_tabs
&& FILETYPE_ID(doc
->file_type
) != GEANY_FILETYPES_MAKE
)
1785 editor_replace_tabs(doc
->editor
);
1786 /* strip trailing spaces */
1787 if (file_prefs
.strip_trailing_spaces
)
1788 editor_strip_trailing_spaces(doc
->editor
);
1789 /* ensure the file has a newline at the end */
1790 if (file_prefs
.final_new_line
)
1791 editor_ensure_final_newline(doc
->editor
);
1793 /* notify plugins which may wish to modify the document before it's saved */
1794 g_signal_emit_by_name(geany_object
, "document-before-save", doc
);
1796 len
= sci_get_length(doc
->editor
->sci
) + 1;
1797 if (doc
->has_bom
&& encodings_is_unicode_charset(doc
->encoding
))
1798 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1799 * encoding, it will be converted to doc->encoding below and this conversion
1800 * also changes the BOM */
1801 data
= (gchar
*) g_malloc(len
+ 3); /* 3 chars for BOM */
1802 data
[0] = (gchar
) 0xef;
1803 data
[1] = (gchar
) 0xbb;
1804 data
[2] = (gchar
) 0xbf;
1805 sci_get_text(doc
->editor
->sci
, len
, data
+ 3);
1810 data
= (gchar
*) g_malloc(len
);
1811 sci_get_text(doc
->editor
->sci
, len
, data
);
1814 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1815 if (doc
->encoding
!= NULL
&& ! utils_str_equal(doc
->encoding
, "UTF-8") &&
1816 ! utils_str_equal(doc
->encoding
, encodings
[GEANY_ENCODING_NONE
].charset
))
1818 if (! save_convert_to_encoding(doc
, &data
, &len
))
1829 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1831 /* ignore file changed notification when the file is written */
1832 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1834 /* actually write the content of data to the file on disk */
1835 errmsg
= write_data_to_disk(doc
, locale_filename
, data
, len
);
1840 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), errmsg
);
1841 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, _("Error saving file."), errmsg
);
1842 doc
->priv
->file_disk_status
= FILE_OK
;
1844 g_free(locale_filename
);
1849 /* store the opened encoding for undo/redo */
1850 store_saved_encoding(doc
);
1852 /* ignore the following things if we are quitting */
1853 if (! main_status
.quitting
)
1855 sci_set_savepoint(doc
->editor
->sci
);
1857 if (file_prefs
.disk_check_timeout
> 0)
1858 document_update_timestamp(doc
, locale_filename
);
1860 /* update filetype-related things */
1861 document_set_filetype(doc
, doc
->file_type
);
1863 document_update_tab_label(doc
);
1865 msgwin_status_add(_("File %s saved."), doc
->file_name
);
1866 ui_update_statusbar(doc
, -1);
1868 vte_cwd((doc
->real_path
!= NULL
) ? doc
->real_path
: doc
->file_name
, FALSE
);
1871 g_free(locale_filename
);
1873 g_signal_emit_by_name(geany_object
, "document-save", doc
);
1879 /* special search function, used from the find entry in the toolbar
1880 * return TRUE if text was found otherwise FALSE
1881 * return also TRUE if text is empty */
1882 gboolean
document_search_bar_find(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean inc
)
1884 gint start_pos
, search_pos
;
1885 struct Sci_TextToFind ttf
;
1887 g_return_val_if_fail(text
!= NULL
, FALSE
);
1888 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1892 start_pos
= (inc
) ? sci_get_selection_start(doc
->editor
->sci
) :
1893 sci_get_selection_end(doc
->editor
->sci
); /* equal if no selection */
1895 /* search cursor to end */
1896 ttf
.chrg
.cpMin
= start_pos
;
1897 ttf
.chrg
.cpMax
= sci_get_length(doc
->editor
->sci
);
1898 ttf
.lpstrText
= (gchar
*)text
;
1899 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1901 /* if no match, search start to cursor */
1902 if (search_pos
== -1)
1905 ttf
.chrg
.cpMax
= start_pos
+ strlen(text
);
1906 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1909 if (search_pos
!= -1)
1911 gint line
= sci_get_line_from_position(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1913 /* unfold maybe folded results */
1914 sci_ensure_line_is_visible(doc
->editor
->sci
, line
);
1916 sci_set_selection_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1917 sci_set_selection_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1919 if (! editor_line_in_view(doc
->editor
, line
))
1920 { /* we need to force scrolling in case the cursor is outside of the current visible area
1921 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1922 * while searching */
1923 editor_scroll_to_line(doc
->editor
, -1, 0.3F
);
1926 sci_scroll_caret(doc
->editor
->sci
); /* may need horizontal scrolling */
1933 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
1936 sci_goto_pos(doc
->editor
->sci
, start_pos
, FALSE
); /* clear selection */
1942 /* General search function, used from the find dialog.
1943 * Returns -1 on failure or the start position of the matching text.
1944 * Will skip past any selection, ignoring it. */
1945 gint
document_find_text(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean search_backwards
,
1946 gboolean scroll
, GtkWidget
*parent
)
1948 gint selection_end
, selection_start
, search_pos
;
1950 g_return_val_if_fail(doc
!= NULL
&& text
!= NULL
, -1);
1954 /* Sci doesn't support searching backwards with a regex */
1955 if (flags
& SCFIND_REGEXP
)
1956 search_backwards
= FALSE
;
1958 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
1959 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
1960 if ((selection_end
- selection_start
) > 0)
1961 { /* there's a selection so go to the end */
1962 if (search_backwards
)
1963 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
1965 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
1968 sci_set_search_anchor(doc
->editor
->sci
);
1969 if (search_backwards
)
1970 search_pos
= sci_search_prev(doc
->editor
->sci
, flags
, text
);
1972 search_pos
= search_find_next(doc
->editor
->sci
, text
, flags
);
1974 if (search_pos
!= -1)
1976 /* unfold maybe folded results */
1977 sci_ensure_line_is_visible(doc
->editor
->sci
,
1978 sci_get_line_from_position(doc
->editor
->sci
, search_pos
));
1980 doc
->editor
->scroll_percent
= 0.3F
;
1984 gint sci_len
= sci_get_length(doc
->editor
->sci
);
1986 /* if we just searched the whole text, give up searching. */
1987 if ((selection_end
== 0 && ! search_backwards
) ||
1988 (selection_end
== sci_len
&& search_backwards
))
1990 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
1995 /* we searched only part of the document, so ask whether to wraparound. */
1996 if (search_prefs
.suppress_dialogs
||
1997 dialogs_show_question_full(parent
, GTK_STOCK_FIND
, GTK_STOCK_CANCEL
,
1998 _("Wrap search and find again?"), _("\"%s\" was not found."), text
))
2002 sci_set_current_position(doc
->editor
->sci
, (search_backwards
) ? sci_len
: 0, FALSE
);
2003 ret
= document_find_text(doc
, text
, flags
, search_backwards
, scroll
, parent
);
2005 { /* return to original cursor position if not found */
2006 sci_set_current_position(doc
->editor
->sci
, selection_start
, FALSE
);
2015 /* Replaces the selection if it matches, otherwise just finds the next match.
2016 * Returns: start of replaced text, or -1 if no replacement was made */
2017 gint
document_replace_text(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2018 gint flags
, gboolean search_backwards
)
2020 gint selection_end
, selection_start
, search_pos
;
2022 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, -1);
2027 /* Sci doesn't support searching backwards with a regex */
2028 if (flags
& SCFIND_REGEXP
)
2029 search_backwards
= FALSE
;
2031 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2032 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2033 if (selection_end
== selection_start
)
2035 /* no selection so just find the next match */
2036 document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2039 /* there's a selection so go to the start before finding to search through it
2040 * this ensures there is a match */
2041 if (search_backwards
)
2042 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2044 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2046 search_pos
= document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2047 /* return if the original selected text did not match (at the start of the selection) */
2048 if (search_pos
!= selection_start
)
2051 if (search_pos
!= -1)
2054 /* search next/prev will select matching text, which we use to set the replace target */
2055 sci_target_from_selection(doc
->editor
->sci
);
2056 replace_len
= search_replace_target(doc
->editor
->sci
, replace_text
, flags
& SCFIND_REGEXP
);
2057 /* select the replacement - find text will skip past the selected text */
2058 sci_set_selection_start(doc
->editor
->sci
, search_pos
);
2059 sci_set_selection_end(doc
->editor
->sci
, search_pos
+ replace_len
);
2063 /* no match in the selection */
2070 static void show_replace_summary(GeanyDocument
*doc
, gint count
, const gchar
*find_text
,
2071 const gchar
*replace_text
, gboolean escaped_chars
)
2073 gchar
*escaped_find_text
, *escaped_replace_text
, *filename
;
2077 ui_set_statusbar(FALSE
, _("No matches found for \"%s\"."), find_text
);
2081 filename
= g_path_get_basename(DOC_FILENAME(doc
));
2084 { /* escape special characters for showing */
2085 escaped_find_text
= g_strescape(find_text
, NULL
);
2086 escaped_replace_text
= g_strescape(replace_text
, NULL
);
2087 ui_set_statusbar(TRUE
, ngettext(
2088 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2089 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2090 count
), filename
, count
, escaped_find_text
, escaped_replace_text
);
2091 g_free(escaped_find_text
);
2092 g_free(escaped_replace_text
);
2096 ui_set_statusbar(TRUE
, ngettext(
2097 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2098 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2099 count
), filename
, count
, find_text
, replace_text
);
2105 /* Replace all text matches in a certain range within document.
2106 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2107 * or -1 if no text was found.
2108 * scroll_to_match is whether to scroll the last replacement in view (which also
2109 * clears the selection).
2110 * Returns: the number of replacements made. */
2112 document_replace_range(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2113 gint flags
, gint start
, gint end
, gboolean scroll_to_match
, gint
*new_range_end
)
2116 struct Sci_TextToFind ttf
;
2117 ScintillaObject
*sci
;
2119 if (new_range_end
!= NULL
)
2120 *new_range_end
= -1;
2122 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, 0);
2124 if (! *find_text
|| doc
->readonly
)
2127 sci
= doc
->editor
->sci
;
2129 ttf
.chrg
.cpMin
= start
;
2130 ttf
.chrg
.cpMax
= end
;
2131 ttf
.lpstrText
= (gchar
*)find_text
;
2133 sci_start_undo_action(sci
);
2134 count
= search_replace_range(sci
, &ttf
, flags
, replace_text
);
2135 sci_end_undo_action(sci
);
2138 { /* scroll last match in view, will destroy the existing selection */
2139 if (scroll_to_match
)
2140 sci_goto_pos(sci
, ttf
.chrg
.cpMin
, TRUE
);
2142 if (new_range_end
!= NULL
)
2143 *new_range_end
= ttf
.chrg
.cpMax
;
2149 void document_replace_sel(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2150 gint flags
, gboolean escaped_chars
)
2152 gint selection_end
, selection_start
, selection_mode
, selected_lines
, last_line
= 0;
2153 gint max_column
= 0, count
= 0;
2154 gboolean replaced
= FALSE
;
2156 g_return_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
);
2161 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2162 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2163 /* do we have a selection? */
2164 if ((selection_end
- selection_start
) == 0)
2170 selection_mode
= sci_get_selection_mode(doc
->editor
->sci
);
2171 selected_lines
= sci_get_lines_selected(doc
->editor
->sci
);
2172 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2173 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2175 gint first_line
, line
;
2177 sci_start_undo_action(doc
->editor
->sci
);
2179 first_line
= sci_get_line_from_position(doc
->editor
->sci
, selection_start
);
2180 /* Find the last line with chars selected (not EOL char) */
2181 last_line
= sci_get_line_from_position(doc
->editor
->sci
,
2182 selection_end
- editor_get_eol_char_len(doc
->editor
));
2183 last_line
= MAX(first_line
, last_line
);
2184 for (line
= first_line
; line
< (first_line
+ selected_lines
); line
++)
2186 gint line_start
= sci_get_pos_at_line_sel_start(doc
->editor
->sci
, line
);
2187 gint line_end
= sci_get_pos_at_line_sel_end(doc
->editor
->sci
, line
);
2189 /* skip line if there is no selection */
2190 if (line_start
!= INVALID_POSITION
)
2192 /* don't let document_replace_range() scroll to match to keep our selection */
2195 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2196 line_start
, line_end
, FALSE
, &new_sel_end
);
2197 if (new_sel_end
!= -1)
2200 /* this gets the greatest column within the selection after replacing */
2201 max_column
= MAX(max_column
,
2202 new_sel_end
- sci_get_position_from_line(doc
->editor
->sci
, line
));
2206 sci_end_undo_action(doc
->editor
->sci
);
2208 else /* handle normal line selection */
2210 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2211 selection_start
, selection_end
, TRUE
, &selection_end
);
2212 if (selection_end
!= -1)
2217 { /* update the selection for the new endpoint */
2219 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2221 /* now we can scroll to the selection and destroy it because we rebuild it later */
2222 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2224 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2225 * the highest column on the last line. The wrapped selection is completely different
2226 * from the original one, so skip the selection at all */
2227 /* TODO is there a better way to handle the wrapped selection? */
2228 if ((sci_get_line_length(doc
->editor
->sci
, last_line
) - 1) >= max_column
)
2229 { /* for keeping and adjusting the selection in multi line rectangle selection we
2230 * need the last line of the original selection and the greatest column number after
2231 * replacing and set the selection end to the last line at the greatest column */
2232 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2233 sci_set_selection_end(doc
->editor
->sci
,
2234 sci_get_position_from_line(doc
->editor
->sci
, last_line
) + max_column
);
2235 sci_set_selection_mode(doc
->editor
->sci
, selection_mode
);
2240 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2241 sci_set_selection_end(doc
->editor
->sci
, selection_end
);
2244 else /* no replacements */
2247 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2251 /* returns number of replacements made. */
2252 gint
document_replace_all(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2253 gint flags
, gboolean escaped_chars
)
2256 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, FALSE
);
2261 len
= sci_get_length(doc
->editor
->sci
);
2262 count
= document_replace_range(
2263 doc
, find_text
, replace_text
, flags
, 0, len
, TRUE
, NULL
);
2265 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2270 static gboolean
update_tags_from_buffer(GeanyDocument
*doc
)
2275 result
= tm_source_file_update(doc
->tm_file
, TRUE
, FALSE
, TRUE
);
2277 gsize len
= sci_get_length(doc
->editor
->sci
) + 1;
2278 gchar
*text
= g_malloc(len
);
2280 /* we copy the whole text into memory instead using a direct char pointer from
2281 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2282 sci_get_text(doc
->editor
->sci
, len
, text
);
2283 result
= tm_source_file_buffer_update(doc
->tm_file
, (guchar
*) text
, len
, TRUE
);
2290 void document_update_tag_list(GeanyDocument
*doc
, gboolean update
)
2292 /* We must call sidebar_update_tag_list() before returning,
2293 * to ensure that the symbol list is always updated properly (e.g.
2294 * when creating a new document with a partial filename set. */
2295 gboolean success
= FALSE
;
2297 /* if the filetype doesn't have a tag parser or it is a new file */
2298 if (doc
== NULL
|| doc
->file_type
== NULL
|| app
->tm_workspace
== NULL
||
2299 ! filetype_has_tags(doc
->file_type
) || ! doc
->file_name
)
2301 /* set the default (empty) tag list */
2302 sidebar_update_tag_list(doc
, FALSE
);
2306 if (doc
->tm_file
== NULL
)
2308 gchar
*locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2311 /* lookup the name rather than using filetype name to support custom filetypes */
2312 name
= tm_source_file_get_lang_name(doc
->file_type
->lang
);
2313 doc
->tm_file
= tm_source_file_new(locale_filename
, FALSE
, name
);
2314 g_free(locale_filename
);
2318 if (!tm_workspace_add_object(doc
->tm_file
))
2320 tm_work_object_free(doc
->tm_file
);
2321 doc
->tm_file
= NULL
;
2326 update_tags_from_buffer(doc
);
2333 success
= update_tags_from_buffer(doc
);
2334 if (G_UNLIKELY(! success
))
2335 geany_debug("tag list updating failed");
2337 sidebar_update_tag_list(doc
, success
);
2341 /* Caches the list of project typenames, as a space separated GString.
2342 * Returns: TRUE if typenames have changed.
2343 * (*types) is set to the list of typenames, or NULL if there are none. */
2344 static gboolean
get_project_typenames(const GString
**types
, gint lang
)
2346 static GString
*last_typenames
= NULL
;
2349 if (app
->tm_workspace
)
2351 GPtrArray
*tags_array
= app
->tm_workspace
->work_object
.tags_array
;
2355 s
= symbols_find_tags_as_string(tags_array
, TM_GLOBAL_TYPE_MASK
, lang
);
2359 if (s
&& last_typenames
&& g_string_equal(s
, last_typenames
))
2361 g_string_free(s
, TRUE
);
2362 *types
= last_typenames
;
2363 return FALSE
; /* project typenames haven't changed */
2365 /* cache typename list for next time */
2367 g_string_free(last_typenames
, TRUE
);
2377 /* If sci is NULL, update project typenames for all documents that support typenames,
2378 * if typenames have changed.
2379 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2380 * if necessary, and typename keywords are set for sci.
2381 * Returns: TRUE if any scintilla type keywords were updated. */
2382 static gboolean
update_type_keywords(GeanyDocument
*doc
, gint lang
)
2384 gboolean ret
= FALSE
;
2387 ScintillaObject
*sci
;
2389 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2390 sci
= doc
->editor
->sci
;
2392 switch (FILETYPE_ID(doc
->file_type
))
2393 { /* continue working with the following languages, skip on all others */
2394 case GEANY_FILETYPES_C
:
2395 case GEANY_FILETYPES_CPP
:
2396 case GEANY_FILETYPES_CS
:
2397 case GEANY_FILETYPES_D
:
2398 case GEANY_FILETYPES_JAVA
:
2399 case GEANY_FILETYPES_VALA
:
2405 sci
= doc
->editor
->sci
;
2406 if (sci
!= NULL
&& editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
)) == -1)
2409 if (! get_project_typenames(&s
, lang
))
2410 { /* typenames have not changed */
2411 if (s
!= NULL
&& sci
!= NULL
)
2413 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
));
2415 sci_set_keywords(sci
, keyword_idx
, s
->str
);
2416 queue_colourise(doc
);
2420 g_return_val_if_fail(s
!= NULL
, FALSE
);
2422 for (n
= 0; n
< documents_array
->len
; n
++)
2424 if (documents
[n
]->is_valid
)
2426 ScintillaObject
*wid
= documents
[n
]->editor
->sci
;
2427 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(wid
));
2429 if (keyword_idx
> 0)
2431 sci_set_keywords(wid
, keyword_idx
, s
->str
);
2432 queue_colourise(documents
[n
]);
2441 static void document_load_config(GeanyDocument
*doc
, GeanyFiletype
*type
,
2442 gboolean filetype_changed
)
2444 g_return_if_fail(doc
);
2446 type
= filetypes
[GEANY_FILETYPES_NONE
];
2448 if (filetype_changed
)
2450 doc
->file_type
= type
;
2452 /* delete tm file object to force creation of a new one */
2453 if (doc
->tm_file
!= NULL
)
2455 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
2456 doc
->tm_file
= NULL
;
2458 /* load tags files before highlighting (some lexers highlight global typenames) */
2459 if (type
->id
!= GEANY_FILETYPES_NONE
)
2460 symbols_global_tags_loaded(type
->id
);
2462 highlighting_set_styles(doc
->editor
->sci
, type
);
2463 editor_set_indentation_guides(doc
->editor
);
2464 build_menu_update(doc
);
2465 queue_colourise(doc
);
2468 document_update_tag_list(doc
, TRUE
);
2470 /* Update session typename keywords. */
2471 update_type_keywords(doc
, type
->lang
);
2475 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2476 * @param doc The document to use.
2477 * @param type The filetype. */
2478 void document_set_filetype(GeanyDocument
*doc
, GeanyFiletype
*type
)
2480 gboolean ft_changed
;
2481 GeanyFiletype
*old_ft
;
2483 g_return_if_fail(doc
);
2485 type
= filetypes
[GEANY_FILETYPES_NONE
];
2487 old_ft
= doc
->file_type
;
2488 geany_debug("%s : %s (%s)",
2489 (doc
->file_name
!= NULL
) ? doc
->file_name
: "unknown",
2490 (type
->name
!= NULL
) ? type
->name
: "unknown",
2491 (doc
->encoding
!= NULL
) ? doc
->encoding
: "unknown");
2493 ft_changed
= (doc
->file_type
!= type
); /* filetype has changed */
2494 document_load_config(doc
, type
, ft_changed
);
2497 g_signal_emit_by_name(geany_object
, "document-filetype-set", doc
, old_ft
);
2501 void document_reload_config(GeanyDocument
*doc
)
2503 document_load_config(doc
, doc
->file_type
, TRUE
);
2508 * Sets the encoding of a document.
2509 * This function only set the encoding of the %document, it does not any conversions. The new
2510 * encoding is used when e.g. saving the file.
2512 * @param doc The document to use.
2513 * @param new_encoding The encoding to be set for the document.
2515 void document_set_encoding(GeanyDocument
*doc
, const gchar
*new_encoding
)
2517 if (doc
== NULL
|| new_encoding
== NULL
||
2518 utils_str_equal(new_encoding
, doc
->encoding
))
2521 g_free(doc
->encoding
);
2522 doc
->encoding
= g_strdup(new_encoding
);
2524 ui_update_statusbar(doc
, -1);
2525 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets
.window
, "menu_write_unicode_bom1"),
2526 encodings_is_unicode_charset(doc
->encoding
));
2530 /* own Undo / Redo implementation to be able to undo / redo changes
2531 * to the encoding or the Unicode BOM (which are Scintilla independet).
2532 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2534 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2535 void document_undo_clear(GeanyDocument
*doc
)
2539 while (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0)
2541 a
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2542 if (G_LIKELY(a
!= NULL
))
2546 case UNDO_ENCODING
: g_free(a
->data
); break;
2552 doc
->priv
->undo_actions
= NULL
;
2554 while (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0)
2556 a
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2557 if (G_LIKELY(a
!= NULL
))
2561 case UNDO_ENCODING
: g_free(a
->data
); break;
2567 doc
->priv
->redo_actions
= NULL
;
2569 if (! main_status
.quitting
&& doc
->editor
!= NULL
)
2570 document_set_text_changed(doc
, FALSE
);
2574 void document_undo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2576 undo_action
*action
;
2578 g_return_if_fail(doc
!= NULL
);
2580 action
= g_new0(undo_action
, 1);
2581 action
->type
= type
;
2582 action
->data
= data
;
2584 g_trash_stack_push(&doc
->priv
->undo_actions
, action
);
2586 document_set_text_changed(doc
, TRUE
);
2587 ui_update_popup_reundo_items(doc
);
2591 gboolean
document_can_undo(GeanyDocument
*doc
)
2593 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2595 if (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0 || sci_can_undo(doc
->editor
->sci
))
2602 static void update_changed_state(GeanyDocument
*doc
)
2605 (sci_is_modified(doc
->editor
->sci
) ||
2606 doc
->has_bom
!= doc
->priv
->saved_encoding
.has_bom
||
2607 ! utils_str_equal(doc
->encoding
, doc
->priv
->saved_encoding
.encoding
));
2608 document_set_text_changed(doc
, doc
->changed
);
2612 void document_undo(GeanyDocument
*doc
)
2614 undo_action
*action
;
2616 g_return_if_fail(doc
!= NULL
);
2618 action
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2620 if (G_UNLIKELY(action
== NULL
))
2622 /* fallback, should not be necessary */
2623 geany_debug("%s: fallback used", G_STRFUNC
);
2624 sci_undo(doc
->editor
->sci
);
2628 switch (action
->type
)
2630 case UNDO_SCINTILLA
:
2632 document_redo_add(doc
, UNDO_SCINTILLA
, NULL
);
2634 sci_undo(doc
->editor
->sci
);
2639 document_redo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2641 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2642 ui_update_statusbar(doc
, -1);
2643 ui_document_show_hide(doc
);
2648 /* use the "old" encoding */
2649 document_redo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2651 document_set_encoding(doc
, (const gchar
*)action
->data
);
2653 ignore_callback
= TRUE
;
2654 encodings_select_radio_item((const gchar
*)action
->data
);
2655 ignore_callback
= FALSE
;
2657 g_free(action
->data
);
2663 g_free(action
); /* free the action which was taken from the stack */
2665 update_changed_state(doc
);
2666 ui_update_popup_reundo_items(doc
);
2670 gboolean
document_can_redo(GeanyDocument
*doc
)
2672 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2674 if (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0 || sci_can_redo(doc
->editor
->sci
))
2681 void document_redo(GeanyDocument
*doc
)
2683 undo_action
*action
;
2685 g_return_if_fail(doc
!= NULL
);
2687 action
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2689 if (G_UNLIKELY(action
== NULL
))
2691 /* fallback, should not be necessary */
2692 geany_debug("%s: fallback used", G_STRFUNC
);
2693 sci_redo(doc
->editor
->sci
);
2697 switch (action
->type
)
2699 case UNDO_SCINTILLA
:
2701 document_undo_add(doc
, UNDO_SCINTILLA
, NULL
);
2703 sci_redo(doc
->editor
->sci
);
2708 document_undo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2710 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2711 ui_update_statusbar(doc
, -1);
2712 ui_document_show_hide(doc
);
2717 document_undo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2719 document_set_encoding(doc
, (const gchar
*)action
->data
);
2721 ignore_callback
= TRUE
;
2722 encodings_select_radio_item((const gchar
*)action
->data
);
2723 ignore_callback
= FALSE
;
2725 g_free(action
->data
);
2731 g_free(action
); /* free the action which was taken from the stack */
2733 update_changed_state(doc
);
2734 ui_update_popup_reundo_items(doc
);
2738 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2740 undo_action
*action
;
2742 g_return_if_fail(doc
!= NULL
);
2744 action
= g_new0(undo_action
, 1);
2745 action
->type
= type
;
2746 action
->data
= data
;
2748 g_trash_stack_push(&doc
->priv
->redo_actions
, action
);
2750 document_set_text_changed(doc
, TRUE
);
2751 ui_update_popup_reundo_items(doc
);
2756 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2757 * Returned colors are red if the document has changes, green if the document is read-only
2758 * or simply @c NULL if the document is unmodified but writable.
2760 * @param doc The document to use.
2762 * @return The color for the document or @c NULL if the default color should be used. The color
2763 * object is owned by Geany and should not be modified or freed.
2767 const GdkColor
*document_get_status_color(GeanyDocument
*doc
)
2769 static GdkColor red
= {0, 0xFFFF, 0, 0};
2770 static GdkColor green
= {0, 0, 0x7FFF, 0};
2772 static GdkColor orange
= {0, 0xFFFF, 0x7FFF, 0};
2774 GdkColor
*color
= NULL
;
2776 g_return_val_if_fail(doc
!= NULL
, NULL
);
2781 else if (doc
->priv
->file_disk_status
== FILE_CHANGED
)
2784 else if (doc
->readonly
)
2787 return color
; /* return pointer to static GdkColor. */
2791 /** Accessor function for @ref GeanyData::documents_array items.
2792 * @warning Always check the returned document is valid (@c doc->is_valid).
2793 * @param idx @c documents_array index.
2794 * @return The document, or @c NULL if @a idx is out of range.
2798 GeanyDocument
*document_index(gint idx
)
2800 return (idx
>= 0 && idx
< (gint
) documents_array
->len
) ? documents
[idx
] : NULL
;
2804 /* create a new file and copy file content and properties */
2805 GeanyDocument
*document_clone(GeanyDocument
*old_doc
, const gchar
*utf8_filename
)
2811 g_return_val_if_fail(old_doc
!= NULL
, NULL
);
2813 len
= sci_get_length(old_doc
->editor
->sci
) + 1;
2814 text
= (gchar
*) g_malloc(len
);
2815 sci_get_text(old_doc
->editor
->sci
, len
, text
);
2816 /* use old file type (or maybe NULL for auto detect would be better?) */
2817 doc
= document_new_file(utf8_filename
, old_doc
->file_type
, text
);
2820 /* copy file properties */
2821 doc
->editor
->line_wrapping
= old_doc
->editor
->line_wrapping
;
2822 doc
->readonly
= old_doc
->readonly
;
2823 doc
->has_bom
= old_doc
->has_bom
;
2824 document_set_encoding(doc
, old_doc
->encoding
);
2825 sci_set_lines_wrapped(doc
->editor
->sci
, doc
->editor
->line_wrapping
);
2826 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
2828 ui_document_show_hide(doc
);
2833 /* @note If successful, this should always be followed up with a call to
2834 * document_close_all().
2835 * @return TRUE if all files were saved or had their changes discarded. */
2836 gboolean
document_account_for_unsaved(void)
2838 guint i
, p
, page_count
, len
= documents_array
->len
;
2841 page_count
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
2842 for (p
= 0; p
< page_count
; p
++)
2844 doc
= document_get_from_page(p
);
2845 if (DOC_VALID(doc
) && doc
->changed
)
2847 if (! dialogs_show_unsaved_file(doc
))
2851 /* all documents should now be accounted for, so ignore any changes */
2852 for (i
= 0; i
< len
; i
++)
2855 if (doc
->is_valid
&& doc
->changed
)
2857 doc
->changed
= FALSE
;
2864 static void force_close_all(void)
2866 guint i
, len
= documents_array
->len
;
2868 /* check all documents have been accounted for */
2869 for (i
= 0; i
< len
; i
++)
2871 if (documents
[i
]->is_valid
)
2873 g_return_if_fail(!documents
[i
]->changed
);
2876 main_status
.closing_all
= TRUE
;
2880 document_close(documents
[i
]);
2883 main_status
.closing_all
= FALSE
;
2887 gboolean
document_close_all(void)
2889 if (! document_account_for_unsaved())
2898 static gboolean
monitor_reload_file(GeanyDocument
*doc
)
2900 gchar
*base_name
= g_path_get_basename(doc
->file_name
);
2901 gboolean want_reload
;
2903 want_reload
= dialogs_show_question_full(NULL
, _("_Reload"), GTK_STOCK_CANCEL
,
2904 _("Do you want to reload it?"),
2905 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2909 document_reload_file(doc
, doc
->encoding
);
2916 static gboolean
monitor_resave_missing_file(GeanyDocument
*doc
)
2918 gboolean want_reload
= FALSE
;
2919 gboolean file_saved
= FALSE
;
2922 ret
= dialogs_show_prompt(NULL
,
2923 _("Close _without saving"), GTK_RESPONSE_CLOSE
,
2924 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
2925 GTK_STOCK_SAVE
, GTK_RESPONSE_ACCEPT
,
2927 _("File \"%s\" was not found on disk! Try to resave the file?"),
2929 if (ret
== GTK_RESPONSE_ACCEPT
)
2931 file_saved
= dialogs_show_save_as();
2934 else if (ret
== GTK_RESPONSE_CLOSE
)
2936 document_close(doc
);
2938 if (ret
!= GTK_RESPONSE_CLOSE
&& ! file_saved
)
2940 /* file is missing - set unsaved state */
2941 document_set_text_changed(doc
, TRUE
);
2942 /* don't prompt more than once */
2943 setptr(doc
->real_path
, NULL
);
2950 /* Set force to force a disk check, otherwise it is ignored if there was a check
2951 * in the last file_prefs.disk_check_timeout seconds.
2952 * @return @c TRUE if the file has changed. */
2953 gboolean
document_check_disk_status(GeanyDocument
*doc
, gboolean force
)
2955 gboolean ret
= FALSE
;
2956 gboolean use_gio_filemon
;
2957 time_t cur_time
= 0;
2959 gchar
*locale_filename
;
2960 FileDiskStatus old_status
;
2962 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2964 /* ignore remote files and documents that have never been saved to disk */
2965 if (file_prefs
.disk_check_timeout
== 0 || doc
->real_path
== NULL
|| doc
->priv
->is_remote
)
2968 use_gio_filemon
= (doc
->priv
->monitor
!= NULL
);
2970 if (use_gio_filemon
)
2972 if (doc
->priv
->file_disk_status
!= FILE_CHANGED
&& ! force
)
2977 cur_time
= time(NULL
);
2978 if (! force
&& doc
->priv
->last_check
> (cur_time
- file_prefs
.disk_check_timeout
))
2981 doc
->priv
->last_check
= cur_time
;
2984 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2985 if (g_stat(locale_filename
, &st
) != 0)
2987 monitor_resave_missing_file(doc
);
2990 else if (! use_gio_filemon
&& /* ignore these checks when using GIO */
2991 (G_UNLIKELY(doc
->priv
->mtime
> cur_time
) || G_UNLIKELY(st
.st_mtime
> cur_time
)))
2993 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC
);
2995 else if (doc
->priv
->mtime
< st
.st_mtime
)
2997 monitor_reload_file(doc
);
2998 doc
->priv
->mtime
= st
.st_mtime
;
3001 g_free(locale_filename
);
3004 { /* doc can get invalid when a document was closed by monitor_resave_missing_file() */
3005 old_status
= doc
->priv
->file_disk_status
;
3006 doc
->priv
->file_disk_status
= FILE_OK
;
3007 if (old_status
!= doc
->priv
->file_disk_status
)
3008 ui_update_tab_status(doc
);