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
;
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 notebook_remove_page(page_num
);
644 sidebar_remove_document(doc
);
645 navqueue_remove_file(doc
->file_name
);
646 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc
));
647 g_free(doc
->encoding
);
648 g_free(doc
->priv
->saved_encoding
.encoding
);
649 g_free(doc
->file_name
);
650 g_free(doc
->real_path
);
651 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
653 editor_destroy(doc
->editor
);
656 document_stop_file_monitoring(doc
);
658 doc
->file_name
= NULL
;
659 doc
->real_path
= NULL
;
660 doc
->file_type
= NULL
;
661 doc
->encoding
= NULL
;
662 doc
->has_bom
= FALSE
;
664 document_undo_clear(doc
);
667 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
669 sidebar_update_tag_list(NULL
, FALSE
);
670 /*on_notebook1_switch_page(GTK_NOTEBOOK(main_widgets.notebook), NULL, 0, NULL);*/
671 ui_set_window_title(NULL
);
672 ui_save_buttons_toggle(FALSE
);
673 ui_document_buttons_update();
674 build_menu_update(NULL
);
680 /* used to keep a record of the unchanged document state encoding */
681 static void store_saved_encoding(GeanyDocument
*doc
)
683 g_free(doc
->priv
->saved_encoding
.encoding
);
684 doc
->priv
->saved_encoding
.encoding
= g_strdup(doc
->encoding
);
685 doc
->priv
->saved_encoding
.has_bom
= doc
->has_bom
;
689 /* Opens a new empty document only if there are no other documents open */
690 GeanyDocument
*document_new_file_if_non_open(void)
692 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
693 return document_new_file(NULL
, NULL
, NULL
);
700 * Creates a new document.
701 * Afterwards, the @c "document-new" signal is emitted for plugins.
703 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
704 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
705 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
707 * @return The new document.
709 GeanyDocument
*document_new_file(const gchar
*utf8_filename
, GeanyFiletype
*ft
,
714 if (utf8_filename
&& g_path_is_absolute(utf8_filename
))
717 tmp
= utils_strdupa(utf8_filename
); /* work around const */
718 utils_tidy_path(tmp
);
721 doc
= document_create(utf8_filename
);
723 g_assert(doc
!= NULL
);
725 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
727 sci_set_text(doc
->editor
->sci
, text
);
729 sci_clear_all(doc
->editor
->sci
);
731 sci_set_eol_mode(doc
->editor
->sci
, file_prefs
.default_eol_character
);
732 /* convert the eol chars in the template text in case they are different from
733 * from file_prefs.default_eol */
735 sci_convert_eols(doc
->editor
->sci
, file_prefs
.default_eol_character
);
737 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
738 sci_empty_undo_buffer(doc
->editor
->sci
);
740 doc
->encoding
= g_strdup(encodings
[file_prefs
.default_new_encoding
].charset
);
741 /* store the opened encoding for undo/redo */
742 store_saved_encoding(doc
);
744 if (ft
== NULL
&& utf8_filename
!= NULL
) /* guess the filetype from the filename if one is given */
745 ft
= filetypes_detect_from_document(doc
);
747 document_set_filetype(doc
, ft
); /* also clears taglist */
749 ui_set_window_title(doc
);
750 build_menu_update(doc
);
751 document_update_tag_list(doc
, FALSE
);
752 document_set_text_changed(doc
, FALSE
);
753 ui_document_show_hide(doc
); /* update the document menu */
755 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
756 /* bring it in front, jump to the start and grab the focus */
757 editor_goto_pos(doc
->editor
, 0, FALSE
);
758 document_try_focus(doc
, NULL
);
761 monitor_file_setup(doc
);
763 doc
->priv
->mtime
= time(NULL
);
766 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
767 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
), doc
->editor
);
769 g_signal_emit_by_name(geany_object
, "document-new", doc
);
771 msgwin_status_add(_("New file \"%s\" opened."),
779 * Opens a document specified by @a locale_filename.
780 * Afterwards, the @c "document-open" signal is emitted for plugins.
782 * @param locale_filename The filename of the document to load, in locale encoding.
783 * @param readonly Whether to open the document in read-only mode.
784 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
785 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
787 * @return The document opened or @c NULL.
789 GeanyDocument
*document_open_file(const gchar
*locale_filename
, gboolean readonly
,
790 GeanyFiletype
*ft
, const gchar
*forced_enc
)
792 return document_open_file_full(NULL
, locale_filename
, 0, readonly
, ft
, forced_enc
);
798 gchar
*data
; /* null-terminated file data */
799 gsize size
; /* actual file size on disk */
800 gsize len
; /* string length of data */
803 time_t mtime
; /* modification time, read by stat::st_mtime */
808 /* reload file with specified encoding */
810 handle_forced_encoding(FileData
*filedata
, const gchar
*forced_enc
)
812 GeanyEncodingIndex enc_idx
;
814 if (utils_str_equal(forced_enc
, "UTF-8"))
816 if (! g_utf8_validate(filedata
->data
, filedata
->len
, NULL
))
823 gchar
*converted_text
= encodings_convert_to_utf8_from_charset(
824 filedata
->data
, filedata
->size
, forced_enc
, FALSE
);
825 if (converted_text
== NULL
)
831 g_free(filedata
->data
);
832 filedata
->data
= converted_text
;
833 filedata
->len
= strlen(converted_text
);
836 enc_idx
= encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, NULL
);
837 filedata
->bom
= (enc_idx
== GEANY_ENCODING_UTF_8
);
838 filedata
->enc
= g_strdup(forced_enc
);
843 /* detect encoding and convert to UTF-8 if necessary */
845 handle_encoding(FileData
*filedata
, GeanyEncodingIndex enc_idx
)
847 g_return_val_if_fail(filedata
->enc
== NULL
, FALSE
);
848 g_return_val_if_fail(filedata
->bom
== FALSE
, FALSE
);
850 if (filedata
->size
== 0)
852 /* we have no data so assume UTF-8, filedata->len can be 0 even we have an empty
853 * e.g. UTF32 file with a BOM(so size is 4, len is 0) */
854 filedata
->enc
= g_strdup("UTF-8");
858 /* first check for a BOM */
859 if (enc_idx
!= GEANY_ENCODING_NONE
)
861 filedata
->enc
= g_strdup(encodings
[enc_idx
].charset
);
862 filedata
->bom
= TRUE
;
864 if (enc_idx
!= GEANY_ENCODING_UTF_8
) /* the BOM indicated something else than UTF-8 */
866 gchar
*converted_text
= encodings_convert_to_utf8_from_charset(
867 filedata
->data
, filedata
->size
, filedata
->enc
, FALSE
);
868 if (converted_text
!= NULL
)
870 g_free(filedata
->data
);
871 filedata
->data
= converted_text
;
872 filedata
->len
= strlen(converted_text
);
876 /* there was a problem converting data from BOM encoding type */
877 g_free(filedata
->enc
);
878 filedata
->enc
= NULL
;
879 filedata
->bom
= FALSE
;
884 if (filedata
->enc
== NULL
) /* either there was no BOM or the BOM encoding failed */
886 /* try UTF-8 first */
887 if ((filedata
->size
== filedata
->len
) &&
888 g_utf8_validate(filedata
->data
, filedata
->len
, NULL
))
890 filedata
->enc
= g_strdup("UTF-8");
894 /* detect the encoding */
895 gchar
*converted_text
= encodings_convert_to_utf8(filedata
->data
,
896 filedata
->size
, &filedata
->enc
);
898 if (converted_text
== NULL
)
902 g_free(filedata
->data
);
903 filedata
->data
= converted_text
;
904 filedata
->len
= strlen(converted_text
);
913 handle_bom(FileData
*filedata
)
917 encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, &bom_len
);
918 g_return_if_fail(bom_len
!= 0);
920 /* use filedata->len here because the contents are already converted into UTF-8 */
921 filedata
->len
-= bom_len
;
922 /* overwrite the BOM with the remainder of the file contents, plus the NULL terminator. */
923 g_memmove(filedata
->data
, filedata
->data
+ bom_len
, filedata
->len
+ 1);
924 filedata
->data
= g_realloc(filedata
->data
, filedata
->len
+ 1);
928 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
929 static gboolean
load_text_file(const gchar
*locale_filename
, const gchar
*display_filename
,
930 FileData
*filedata
, const gchar
*forced_enc
)
934 GeanyEncodingIndex tmp_enc_idx
;
936 filedata
->data
= NULL
;
938 filedata
->enc
= NULL
;
939 filedata
->bom
= FALSE
;
940 filedata
->readonly
= FALSE
;
942 if (g_stat(locale_filename
, &st
) != 0)
944 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"),
945 display_filename
, g_strerror(errno
));
949 filedata
->mtime
= st
.st_mtime
;
951 if (! g_file_get_contents(locale_filename
, &filedata
->data
, NULL
, &err
))
953 ui_set_statusbar(TRUE
, "%s", err
->message
);
958 /* use strlen to check for null chars */
959 filedata
->size
= (gsize
) st
.st_size
;
960 filedata
->len
= strlen(filedata
->data
);
962 /* temporarily retrieve the encoding idx based on the BOM to suppress the following warning
963 * if we have a BOM */
964 tmp_enc_idx
= encodings_scan_unicode_bom(filedata
->data
, filedata
->size
, NULL
);
966 /* check whether the size of the loaded data is equal to the size of the file in the
967 * filesystem file size may be 0 to allow opening files in /proc/ which have typically a
968 * file size of 0 bytes */
969 if (filedata
->len
!= filedata
->size
&& filedata
->size
!= 0 && (
970 tmp_enc_idx
== GEANY_ENCODING_UTF_8
|| /* tmp_enc_idx can be UTF-7/8/16/32, UCS and None */
971 tmp_enc_idx
== GEANY_ENCODING_UTF_7
)) /* filter UTF-7/8 where no NULL bytes are allowed */
973 const gchar
*warn_msg
= _(
974 "The file \"%s\" could not be opened properly and has been truncated. " \
975 "This can occur if the file contains a NULL byte. " \
976 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
978 if (main_status
.main_window_realized
)
979 dialogs_show_msgbox(GTK_MESSAGE_WARNING
, warn_msg
, display_filename
);
981 ui_set_statusbar(TRUE
, warn_msg
, display_filename
);
983 /* set the file to read-only mode because saving it is probably dangerous */
984 filedata
->readonly
= TRUE
;
987 /* Determine character encoding and convert to UTF-8 */
988 if (forced_enc
!= NULL
)
990 /* the encoding should be ignored(requested by user), so open the file "as it is" */
991 if (utils_str_equal(forced_enc
, encodings
[GEANY_ENCODING_NONE
].charset
))
993 filedata
->bom
= FALSE
;
994 filedata
->enc
= g_strdup(encodings
[GEANY_ENCODING_NONE
].charset
);
996 else if (! handle_forced_encoding(filedata
, forced_enc
))
998 /* For translators: the second wildcard is an encoding name, e.g.
999 * The file \"test.txt\" is not valid UTF-8. */
1000 ui_set_statusbar(TRUE
, _("The file \"%s\" is not valid %s."),
1001 display_filename
, forced_enc
);
1003 g_free(filedata
->data
);
1007 else if (! handle_encoding(filedata
, tmp_enc_idx
))
1009 ui_set_statusbar(TRUE
,
1010 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1013 g_free(filedata
->data
);
1018 handle_bom(filedata
);
1023 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1024 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1025 * if cl_options.goto_column is set.
1027 * returns the new position which may have changed */
1028 static gint
set_cursor_position(GeanyEditor
*editor
, gint pos
)
1030 if (cl_options
.goto_line
>= 0)
1031 { /* goto line which was specified on command line and then undefine the line */
1032 sci_goto_line(editor
->sci
, cl_options
.goto_line
- 1, TRUE
);
1033 editor
->scroll_percent
= 0.5F
;
1034 cl_options
.goto_line
= -1;
1038 sci_set_current_position(editor
->sci
, pos
, FALSE
);
1039 editor
->scroll_percent
= 0.5F
;
1042 if (cl_options
.goto_column
>= 0)
1043 { /* goto column which was specified on command line and then undefine the column */
1045 gint new_pos
= sci_get_current_position(editor
->sci
) + cl_options
.goto_column
;
1046 sci_set_current_position(editor
->sci
, new_pos
, FALSE
);
1047 editor
->scroll_percent
= 0.5F
;
1048 cl_options
.goto_column
= -1;
1051 return sci_get_current_position(editor
->sci
);
1055 /* Count lines that start with some hard tabs then a soft tab. */
1056 static gboolean
detect_tabs_and_spaces(GeanyEditor
*editor
)
1058 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1059 ScintillaObject
*sci
= editor
->sci
;
1061 struct Sci_TextToFind ttf
;
1062 gchar
*soft_tab
= g_strnfill(iprefs
->width
, ' ');
1063 gchar
*regex
= g_strconcat("^\t+", soft_tab
, "[^ ]", NULL
);
1068 ttf
.chrg
.cpMax
= sci_get_length(sci
);
1069 ttf
.lpstrText
= regex
;
1074 pos
= sci_find_text(sci
, SCFIND_REGEXP
, &ttf
);
1076 break; /* no more matches */
1078 ttf
.chrg
.cpMin
= ttf
.chrgText
.cpMax
+ 1; /* search after this match */
1081 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1082 return count
> sci_get_line_count(sci
) * 0.02;
1086 /* Detect the indent type based on counting the leading indent characters for each line. */
1087 static GeanyIndentType
detect_indent_type(GeanyEditor
*editor
)
1089 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1090 ScintillaObject
*sci
= editor
->sci
;
1091 guint line
, line_count
;
1092 gsize tabs
= 0, spaces
= 0;
1094 if (detect_tabs_and_spaces(editor
))
1095 return GEANY_INDENT_TYPE_BOTH
;
1097 line_count
= sci_get_line_count(sci
);
1098 for (line
= 0; line
< line_count
; line
++)
1100 gint pos
= sci_get_position_from_line(sci
, line
);
1103 /* most code will have indent total <= 24, otherwise it's more likely to be
1104 * alignment than indentation */
1105 if (sci_get_line_indentation(sci
, line
) > 24)
1108 c
= sci_get_char_at(sci
, pos
);
1114 /* check for at least 2 spaces */
1115 if (sci_get_char_at(sci
, pos
+ 1) == ' ')
1119 if (spaces
== 0 && tabs
== 0)
1120 return iprefs
->type
;
1122 /* the factors may need to be tweaked */
1123 if (spaces
> tabs
* 4)
1124 return GEANY_INDENT_TYPE_SPACES
;
1125 else if (tabs
> spaces
* 4)
1126 return GEANY_INDENT_TYPE_TABS
;
1128 return GEANY_INDENT_TYPE_BOTH
;
1132 void document_apply_indent_settings(GeanyDocument
*doc
)
1134 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
1135 GeanyIndentType type
= iprefs
->type
;
1137 switch (FILETYPE_ID(doc
->file_type
))
1139 case GEANY_FILETYPES_MAKE
:
1140 /* force using tabs for indentation for Makefiles */
1141 editor_set_indent_type(doc
->editor
, GEANY_INDENT_TYPE_TABS
);
1143 case GEANY_FILETYPES_F77
:
1144 /* force using spaces for indentation for Fortran 77 */
1145 editor_set_indent_type(doc
->editor
, GEANY_INDENT_TYPE_SPACES
);
1148 if (iprefs
->detect_type
)
1150 type
= detect_indent_type(doc
->editor
);
1152 if (type
!= iprefs
->type
)
1154 const gchar
*name
= NULL
;
1158 case GEANY_INDENT_TYPE_SPACES
:
1161 case GEANY_INDENT_TYPE_TABS
:
1164 case GEANY_INDENT_TYPE_BOTH
:
1165 name
= _("Tabs and Spaces");
1168 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1169 * and Spaces), the second one is the filename */
1170 ui_set_statusbar(TRUE
, _("Setting %s indentation mode for %s."), name
,
1174 editor_set_indent_type(doc
->editor
, type
);
1179 static gboolean
auto_update_tag_list(gpointer data
)
1181 GeanyDocument
*doc
= data
;
1183 if (! doc
|| ! doc
->is_valid
|| doc
->tm_file
== NULL
)
1186 if (gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
)) != GTK_WIDGET(doc
->editor
->sci
))
1189 if (update_tags_from_buffer(doc
))
1190 sidebar_update_tag_list(doc
, TRUE
);
1197 /* To open a new file, set doc to NULL; filename should be locale encoded.
1198 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1199 * pos is the cursor position, which can be overridden by --line and --column.
1200 * forced_enc can be NULL to detect the file encoding.
1201 * Returns: doc of the opened file or NULL if an error occurred. */
1202 GeanyDocument
*document_open_file_full(GeanyDocument
*doc
, const gchar
*filename
, gint pos
,
1203 gboolean readonly
, GeanyFiletype
*ft
, const gchar
*forced_enc
)
1206 gboolean reload
= (doc
== NULL
) ? FALSE
: TRUE
;
1207 gchar
*utf8_filename
= NULL
;
1208 gchar
*display_filename
= NULL
;
1209 gchar
*locale_filename
= NULL
;
1210 GeanyFiletype
*use_ft
;
1215 utf8_filename
= g_strdup(doc
->file_name
);
1216 locale_filename
= utils_get_locale_from_utf8(utf8_filename
);
1220 /* filename must not be NULL when opening a file */
1221 if (filename
== NULL
)
1223 ui_set_statusbar(FALSE
, _("Invalid filename"));
1228 /* if filename is a shortcut, try to resolve it */
1229 locale_filename
= win32_get_shortcut_target(filename
);
1231 locale_filename
= g_strdup(filename
);
1233 /* remove relative junk */
1234 utils_tidy_path(locale_filename
);
1236 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1237 utf8_filename
= utils_get_utf8_from_locale(locale_filename
);
1239 /* if file is already open, switch to it and go */
1240 doc
= document_find_by_filename(utf8_filename
);
1243 ui_add_recent_file(utf8_filename
); /* either add or reorder recent item */
1244 /* show the doc before reload dialog */
1245 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets
.notebook
),
1246 gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
),
1247 (GtkWidget
*) doc
->editor
->sci
));
1248 document_check_disk_status(doc
, TRUE
); /* force a file changed check */
1251 if (reload
|| doc
== NULL
)
1252 { /* doc possibly changed */
1253 display_filename
= utils_str_middle_truncate(utf8_filename
, 100);
1255 if (! load_text_file(locale_filename
, display_filename
, &filedata
, forced_enc
))
1257 g_free(display_filename
);
1258 g_free(utf8_filename
);
1259 g_free(locale_filename
);
1265 doc
= document_create(utf8_filename
);
1266 g_return_val_if_fail(doc
!= NULL
, NULL
); /* really should not happen */
1268 /* file exists on disk, set real_path */
1269 setptr(doc
->real_path
, tm_get_real_path(locale_filename
));
1271 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1272 monitor_file_setup(doc
);
1275 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
1276 sci_empty_undo_buffer(doc
->editor
->sci
);
1278 /* add the text to the ScintillaObject */
1279 sci_set_readonly(doc
->editor
->sci
, FALSE
); /* to allow replacing text */
1280 sci_set_text(doc
->editor
->sci
, filedata
.data
); /* NULL terminated data */
1281 queue_colourise(doc
); /* Ensure the document gets colourised. */
1283 /* detect & set line endings */
1284 editor_mode
= utils_get_line_endings(filedata
.data
, filedata
.len
);
1285 sci_set_eol_mode(doc
->editor
->sci
, editor_mode
);
1286 g_free(filedata
.data
);
1288 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
1290 doc
->priv
->mtime
= filedata
.mtime
; /* get the modification time from file and keep it */
1291 g_free(doc
->encoding
); /* if reloading, free old encoding */
1292 doc
->encoding
= filedata
.enc
;
1293 doc
->has_bom
= filedata
.bom
;
1294 store_saved_encoding(doc
); /* store the opened encoding for undo/redo */
1296 doc
->readonly
= readonly
|| filedata
.readonly
;
1297 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
1299 /* update line number margin width */
1300 doc
->priv
->line_count
= sci_get_line_count(doc
->editor
->sci
);
1301 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
1306 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1307 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
),
1310 use_ft
= (ft
!= NULL
) ? ft
: filetypes_detect_from_document(doc
);
1314 document_undo_clear(doc
);
1318 /* update taglist, typedef keywords and build menu if necessary */
1319 document_set_filetype(doc
, use_ft
);
1321 /* set indentation settings after setting the filetype */
1323 editor_set_indent_type(doc
->editor
, doc
->editor
->indent_type
); /* resetup sci */
1325 document_apply_indent_settings(doc
);
1327 document_set_text_changed(doc
, FALSE
); /* also updates tab state */
1328 ui_document_show_hide(doc
); /* update the document menu */
1330 /* finally add current file to recent files menu, but not the files from the last session */
1331 if (! main_status
.opening_session_files
)
1332 ui_add_recent_file(utf8_filename
);
1335 g_signal_emit_by_name(geany_object
, "document-open", doc
);
1338 ui_set_statusbar(TRUE
, _("File %s reloaded."), display_filename
);
1340 /* For translators: this is the status window message for opening a file. %d is the number
1341 * of the newly opened file, %s indicates whether the file is opened read-only
1342 * (it is replaced with the string ", read-only"). */
1343 msgwin_status_add(_("File %s opened(%d%s)."),
1344 display_filename
, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)),
1345 (readonly
) ? _(", read-only") : "");
1348 g_free(display_filename
);
1349 g_free(utf8_filename
);
1350 g_free(locale_filename
);
1352 /* TODO This could be used to automatically update the symbol list,
1353 * based on a configurable interval */
1354 /*g_timeout_add(10000, auto_update_tag_list, doc);*/
1356 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1357 pos
= set_cursor_position(doc
->editor
, pos
);
1358 /* now bring the file in front */
1359 editor_goto_pos(doc
->editor
, pos
, FALSE
);
1361 /* finally, let the editor widget grab the focus so you can start coding
1363 g_idle_add(on_idle_focus
, doc
);
1368 /* Takes a new line separated list of filename URIs and opens each file.
1369 * length is the length of the string or -1 if it should be detected */
1370 void document_open_file_list(const gchar
*data
, gssize length
)
1376 g_return_if_fail(data
!= NULL
);
1379 length
= strlen(data
);
1381 switch (utils_get_line_endings(data
, length
))
1383 case SC_EOL_CR
: list
= g_strsplit(data
, "\r", 0); break;
1384 case SC_EOL_CRLF
: list
= g_strsplit(data
, "\r\n", 0); break;
1385 case SC_EOL_LF
: list
= g_strsplit(data
, "\n", 0); break;
1386 default: list
= g_strsplit(data
, "\n", 0);
1391 if (list
[i
] == NULL
)
1393 filename
= g_filename_from_uri(list
[i
], NULL
, NULL
);
1394 if (G_UNLIKELY(filename
== NULL
))
1396 document_open_file(filename
, FALSE
, NULL
, NULL
);
1405 * Opens each file in the list @a filenames.
1406 * Internally, document_open_file() is called for every list item.
1408 * @param filenames A list of filenames to load, in locale encoding.
1409 * @param readonly Whether to open the document in read-only mode.
1410 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1411 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1413 void document_open_files(const GSList
*filenames
, gboolean readonly
, GeanyFiletype
*ft
,
1414 const gchar
*forced_enc
)
1418 for (item
= filenames
; item
!= NULL
; item
= g_slist_next(item
))
1420 document_open_file(item
->data
, readonly
, ft
, forced_enc
);
1426 * Reloads the document with the specified file encoding
1427 * @a forced_enc or @c NULL to auto-detect the file encoding.
1429 * @param doc The document to reload.
1430 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1432 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1434 gboolean
document_reload_file(GeanyDocument
*doc
, const gchar
*forced_enc
)
1437 GeanyDocument
*new_doc
;
1439 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1441 /* try to set the cursor to the position before reloading */
1442 pos
= sci_get_current_position(doc
->editor
->sci
);
1443 new_doc
= document_open_file_full(doc
, NULL
, pos
, doc
->readonly
, doc
->file_type
, forced_enc
);
1445 return (new_doc
!= NULL
);
1449 static gboolean
document_update_timestamp(GeanyDocument
*doc
, const gchar
*locale_filename
)
1451 #if ! USE_GIO_FILEMON
1454 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1456 /* stat the file to get the timestamp, otherwise on Windows the actual
1457 * timestamp can be ahead of time(NULL) */
1458 if (g_stat(locale_filename
, &st
) != 0)
1460 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"), doc
->file_name
,
1465 doc
->priv
->mtime
= st
.st_mtime
; /* get the modification time from file and keep it */
1471 /* Sets line and column to the given position byte_pos in the document.
1472 * byte_pos is the position counted in bytes, not characters */
1473 static void get_line_column_from_pos(GeanyDocument
*doc
, guint byte_pos
, gint
*line
, gint
*column
)
1478 /* for some reason we can use byte count instead of character count here */
1479 *line
= sci_get_line_from_position(doc
->editor
->sci
, byte_pos
);
1480 line_start
= sci_get_position_from_line(doc
->editor
->sci
, *line
);
1481 /* get the column in the line */
1482 *column
= byte_pos
- line_start
;
1484 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1485 * skip one byte(i++) and decrease the column number which is based on byte count */
1486 for (i
= line_start
; i
< (line_start
+ *column
); i
++)
1488 if (sci_get_char_at(doc
->editor
->sci
, i
) < 0)
1497 static void replace_header_filename(GeanyDocument
*doc
)
1501 struct Sci_TextToFind ttf
;
1503 g_return_if_fail(doc
!= NULL
);
1504 g_return_if_fail(doc
->file_type
!= NULL
);
1506 if (doc
->file_type
->extension
)
1507 filebase
= g_strconcat(GEANY_STRING_UNTITLED
, "\\.\\w+", NULL
);
1509 filebase
= g_strdup(GEANY_STRING_UNTITLED
);
1511 filename
= g_path_get_basename(doc
->file_name
);
1513 /* only search the first 3 lines */
1515 ttf
.chrg
.cpMax
= sci_get_position_from_line(doc
->editor
->sci
, 3);
1516 ttf
.lpstrText
= filebase
;
1518 if (search_find_text(doc
->editor
->sci
, SCFIND_MATCHCASE
| SCFIND_REGEXP
, &ttf
) != -1)
1520 sci_set_target_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1521 sci_set_target_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1522 sci_replace_target(doc
->editor
->sci
, filename
, FALSE
);
1530 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1531 * you still have to call @ref document_save_file_as() to change the @a doc object.
1532 * It also stops monitoring for file changes to prevent receiving too many file change events
1533 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1535 * @param doc The current document which should be renamed.
1536 * @param new_filename The new filename in UTF-8 encoding.
1540 void document_rename_file(GeanyDocument
*doc
, const gchar
*new_filename
)
1542 gchar
*old_locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1543 gchar
*new_locale_filename
= utils_get_locale_from_utf8(new_filename
);
1546 /* stop file monitoring to avoid getting events for deleting/creating files,
1547 * it's re-setup in document_save_file_as() */
1548 document_stop_file_monitoring(doc
);
1550 result
= g_rename(old_locale_filename
, new_locale_filename
);
1553 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
,
1554 _("Error renaming file."), g_strerror(errno
));
1556 g_free(old_locale_filename
);
1557 g_free(new_locale_filename
);
1561 /* Return TRUE if the document hasn't been saved before, i.e. either the filename or
1562 * the real_path is not set. */
1563 gboolean
document_need_save_as(GeanyDocument
*doc
)
1565 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1567 return (doc
->file_name
== NULL
|| doc
->real_path
== NULL
);
1572 * Saves the document, detecting the filetype.
1574 * @param doc The document for the file to save.
1575 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1576 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1578 * @see document_save_file().
1582 gboolean
document_save_file_as(GeanyDocument
*doc
, const gchar
*utf8_fname
)
1586 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1588 if (utf8_fname
!= NULL
)
1589 setptr(doc
->file_name
, g_strdup(utf8_fname
));
1591 /* reset real path, it's retrieved again in document_save() */
1592 setptr(doc
->real_path
, NULL
);
1594 /* detect filetype */
1595 if (FILETYPE_ID(doc
->file_type
) == GEANY_FILETYPES_NONE
)
1597 GeanyFiletype
*ft
= filetypes_detect_from_document(doc
);
1599 document_set_filetype(doc
, ft
);
1600 if (document_get_current() == doc
)
1602 ignore_callback
= TRUE
;
1603 filetypes_select_radio_item(doc
->file_type
);
1604 ignore_callback
= FALSE
;
1607 replace_header_filename(doc
);
1609 ret
= document_save_file(doc
, TRUE
);
1611 /* file monitoring support, add file monitoring after the file has been saved
1612 * to ignore any earlier events */
1613 monitor_file_setup(doc
);
1614 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1617 ui_add_recent_file(doc
->file_name
);
1622 static gsize
save_convert_to_encoding(GeanyDocument
*doc
, gchar
**data
, gsize
*len
)
1624 GError
*conv_error
= NULL
;
1625 gchar
* conv_file_contents
= NULL
;
1629 g_return_val_if_fail(data
!= NULL
|| *data
== NULL
, FALSE
);
1630 g_return_val_if_fail(len
!= NULL
, FALSE
);
1632 /* try to convert it from UTF-8 to original encoding */
1633 conv_file_contents
= g_convert(*data
, *len
- 1, doc
->encoding
, "UTF-8",
1634 &bytes_read
, &conv_len
, &conv_error
);
1636 if (conv_error
!= NULL
)
1638 gchar
*text
= g_strdup_printf(
1639 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1643 if (conv_error
->code
== G_CONVERT_ERROR_ILLEGAL_SEQUENCE
)
1645 gchar
*context
= NULL
;
1649 /* don't read over the doc length */
1650 gint max_len
= MIN((gint
)bytes_read
+ 6, (gint
)*len
- 1);
1651 context
= g_malloc(7); /* read 6 bytes from Sci + '\0' */
1652 sci_get_text_range(doc
->editor
->sci
, bytes_read
, max_len
, context
);
1654 /* take only one valid Unicode character from the context and discard the leftover */
1655 unic
= g_utf8_get_char_validated(context
, -1);
1656 context_len
= g_unichar_to_utf8(unic
, context
);
1657 context
[context_len
] = '\0';
1658 get_line_column_from_pos(doc
, bytes_read
, &line
, &column
);
1660 error_text
= g_strdup_printf(
1661 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1662 conv_error
->message
, context
, line
+ 1, column
);
1666 error_text
= g_strdup_printf(_("Error message: %s."), conv_error
->message
);
1668 geany_debug("encoding error: %s", conv_error
->message
);
1669 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, text
, error_text
);
1670 g_error_free(conv_error
);
1678 *data
= conv_file_contents
;
1686 static gchar
*write_data_to_disk(GeanyDocument
*doc
, const gchar
*locale_filename
,
1687 const gchar
*data
, gint len
)
1692 GError
*error
= NULL
;
1694 g_return_val_if_fail(doc
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1695 g_return_val_if_fail(data
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1697 if (! file_prefs
.use_safe_file_saving
)
1699 fp
= g_fopen(locale_filename
, "wb");
1700 if (G_UNLIKELY(fp
== NULL
))
1701 return g_strdup(g_strerror(errno
));
1703 bytes_written
= fwrite(data
, sizeof(gchar
), len
, fp
);
1705 if (G_UNLIKELY(len
!= bytes_written
))
1711 return g_strdup(g_strerror(err
));
1715 g_file_set_contents(locale_filename
, data
, len
, &error
);
1718 gchar
*msg
= g_strdup(error
->message
);
1719 g_error_free(error
);
1724 /* now the file is on disk, set real_path */
1725 if (doc
->real_path
== NULL
)
1727 doc
->real_path
= tm_get_real_path(locale_filename
);
1728 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1729 monitor_file_setup(doc
);
1737 * Saves the document. Saving includes replacing tabs by spaces,
1738 * stripping trailing spaces and adding a final new line at the end of the file (all only if
1739 * user enabled these features). Then the @c "document-before-save" signal is emitted,
1740 * allowing plugins to modify the document before it is saved, and data is
1741 * actually written to disk. The filetype is set again or auto-detected if it wasn't set yet.
1742 * Afterwards, the @c "document-save" signal is emitted for plugins.
1744 * If the file is not modified, this functions does nothing unless force is set to @c TRUE.
1746 * @param doc The document to save.
1747 * @param force Whether to save the file even if it is not modified (e.g. for Save As).
1749 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1751 gboolean
document_save_file(GeanyDocument
*doc
, gboolean force
)
1756 gchar
*locale_filename
;
1758 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1760 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1761 if (! force
&& ! ui_prefs
.allow_always_save
&& (! doc
->changed
|| doc
->readonly
))
1764 if (G_UNLIKELY(doc
->file_name
== NULL
))
1766 ui_set_statusbar(TRUE
, _("Error saving file."));
1771 /* replaces tabs by spaces but only if the current file is not a Makefile */
1772 if (file_prefs
.replace_tabs
&& FILETYPE_ID(doc
->file_type
) != GEANY_FILETYPES_MAKE
)
1773 editor_replace_tabs(doc
->editor
);
1774 /* strip trailing spaces */
1775 if (file_prefs
.strip_trailing_spaces
)
1776 editor_strip_trailing_spaces(doc
->editor
);
1777 /* ensure the file has a newline at the end */
1778 if (file_prefs
.final_new_line
)
1779 editor_ensure_final_newline(doc
->editor
);
1781 /* notify plugins which may wish to modify the document before it's saved */
1782 g_signal_emit_by_name(geany_object
, "document-before-save", doc
);
1784 len
= sci_get_length(doc
->editor
->sci
) + 1;
1785 if (doc
->has_bom
&& encodings_is_unicode_charset(doc
->encoding
))
1786 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1787 * encoding, it will be converted to doc->encoding below and this conversion
1788 * also changes the BOM */
1789 data
= (gchar
*) g_malloc(len
+ 3); /* 3 chars for BOM */
1790 data
[0] = (gchar
) 0xef;
1791 data
[1] = (gchar
) 0xbb;
1792 data
[2] = (gchar
) 0xbf;
1793 sci_get_text(doc
->editor
->sci
, len
, data
+ 3);
1798 data
= (gchar
*) g_malloc(len
);
1799 sci_get_text(doc
->editor
->sci
, len
, data
);
1802 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1803 if (doc
->encoding
!= NULL
&& ! utils_str_equal(doc
->encoding
, "UTF-8") &&
1804 ! utils_str_equal(doc
->encoding
, encodings
[GEANY_ENCODING_NONE
].charset
))
1806 if (! save_convert_to_encoding(doc
, &data
, &len
))
1817 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1819 /* ignore file changed notification when the file is written */
1820 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1822 /* actually write the content of data to the file on disk */
1823 errmsg
= write_data_to_disk(doc
, locale_filename
, data
, len
);
1828 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), errmsg
);
1829 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, _("Error saving file."), errmsg
);
1830 doc
->priv
->file_disk_status
= FILE_OK
;
1832 g_free(locale_filename
);
1837 /* store the opened encoding for undo/redo */
1838 store_saved_encoding(doc
);
1840 /* ignore the following things if we are quitting */
1841 if (! main_status
.quitting
)
1843 sci_set_savepoint(doc
->editor
->sci
);
1845 if (file_prefs
.disk_check_timeout
> 0)
1846 document_update_timestamp(doc
, locale_filename
);
1848 /* update filetype-related things */
1849 document_set_filetype(doc
, doc
->file_type
);
1851 document_update_tab_label(doc
);
1853 msgwin_status_add(_("File %s saved."), doc
->file_name
);
1854 ui_update_statusbar(doc
, -1);
1856 vte_cwd((doc
->real_path
!= NULL
) ? doc
->real_path
: doc
->file_name
, FALSE
);
1859 g_free(locale_filename
);
1861 g_signal_emit_by_name(geany_object
, "document-save", doc
);
1867 /* special search function, used from the find entry in the toolbar
1868 * return TRUE if text was found otherwise FALSE
1869 * return also TRUE if text is empty */
1870 gboolean
document_search_bar_find(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean inc
)
1872 gint start_pos
, search_pos
;
1873 struct Sci_TextToFind ttf
;
1875 g_return_val_if_fail(text
!= NULL
, FALSE
);
1876 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1880 start_pos
= (inc
) ? sci_get_selection_start(doc
->editor
->sci
) :
1881 sci_get_selection_end(doc
->editor
->sci
); /* equal if no selection */
1883 /* search cursor to end */
1884 ttf
.chrg
.cpMin
= start_pos
;
1885 ttf
.chrg
.cpMax
= sci_get_length(doc
->editor
->sci
);
1886 ttf
.lpstrText
= (gchar
*)text
;
1887 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1889 /* if no match, search start to cursor */
1890 if (search_pos
== -1)
1893 ttf
.chrg
.cpMax
= start_pos
+ strlen(text
);
1894 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1897 if (search_pos
!= -1)
1899 gint line
= sci_get_line_from_position(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1901 /* unfold maybe folded results */
1902 sci_ensure_line_is_visible(doc
->editor
->sci
, line
);
1904 sci_set_selection_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1905 sci_set_selection_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1907 if (! editor_line_in_view(doc
->editor
, line
))
1908 { /* we need to force scrolling in case the cursor is outside of the current visible area
1909 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1910 * while searching */
1911 editor_scroll_to_line(doc
->editor
, -1, 0.3F
);
1914 sci_scroll_caret(doc
->editor
->sci
); /* may need horizontal scrolling */
1921 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
1924 sci_goto_pos(doc
->editor
->sci
, start_pos
, FALSE
); /* clear selection */
1930 /* General search function, used from the find dialog.
1931 * Returns -1 on failure or the start position of the matching text.
1932 * Will skip past any selection, ignoring it. */
1933 gint
document_find_text(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean search_backwards
,
1934 gboolean scroll
, GtkWidget
*parent
)
1936 gint selection_end
, selection_start
, search_pos
;
1938 g_return_val_if_fail(doc
!= NULL
&& text
!= NULL
, -1);
1942 /* Sci doesn't support searching backwards with a regex */
1943 if (flags
& SCFIND_REGEXP
)
1944 search_backwards
= FALSE
;
1946 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
1947 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
1948 if ((selection_end
- selection_start
) > 0)
1949 { /* there's a selection so go to the end */
1950 if (search_backwards
)
1951 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
1953 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
1956 sci_set_search_anchor(doc
->editor
->sci
);
1957 if (search_backwards
)
1958 search_pos
= sci_search_prev(doc
->editor
->sci
, flags
, text
);
1960 search_pos
= search_find_next(doc
->editor
->sci
, text
, flags
);
1962 if (search_pos
!= -1)
1964 /* unfold maybe folded results */
1965 sci_ensure_line_is_visible(doc
->editor
->sci
,
1966 sci_get_line_from_position(doc
->editor
->sci
, search_pos
));
1968 doc
->editor
->scroll_percent
= 0.3F
;
1972 gint sci_len
= sci_get_length(doc
->editor
->sci
);
1974 /* if we just searched the whole text, give up searching. */
1975 if ((selection_end
== 0 && ! search_backwards
) ||
1976 (selection_end
== sci_len
&& search_backwards
))
1978 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
1983 /* we searched only part of the document, so ask whether to wraparound. */
1984 if (search_prefs
.suppress_dialogs
||
1985 dialogs_show_question_full(parent
, GTK_STOCK_FIND
, GTK_STOCK_CANCEL
,
1986 _("Wrap search and find again?"), _("\"%s\" was not found."), text
))
1990 sci_set_current_position(doc
->editor
->sci
, (search_backwards
) ? sci_len
: 0, FALSE
);
1991 ret
= document_find_text(doc
, text
, flags
, search_backwards
, scroll
, parent
);
1993 { /* return to original cursor position if not found */
1994 sci_set_current_position(doc
->editor
->sci
, selection_start
, FALSE
);
2003 /* Replaces the selection if it matches, otherwise just finds the next match.
2004 * Returns: start of replaced text, or -1 if no replacement was made */
2005 gint
document_replace_text(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2006 gint flags
, gboolean search_backwards
)
2008 gint selection_end
, selection_start
, search_pos
;
2010 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, -1);
2015 /* Sci doesn't support searching backwards with a regex */
2016 if (flags
& SCFIND_REGEXP
)
2017 search_backwards
= FALSE
;
2019 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2020 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2021 if (selection_end
== selection_start
)
2023 /* no selection so just find the next match */
2024 document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2027 /* there's a selection so go to the start before finding to search through it
2028 * this ensures there is a match */
2029 if (search_backwards
)
2030 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2032 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2034 search_pos
= document_find_text(doc
, find_text
, flags
, search_backwards
, TRUE
, NULL
);
2035 /* return if the original selected text did not match (at the start of the selection) */
2036 if (search_pos
!= selection_start
)
2039 if (search_pos
!= -1)
2042 /* search next/prev will select matching text, which we use to set the replace target */
2043 sci_target_from_selection(doc
->editor
->sci
);
2044 replace_len
= search_replace_target(doc
->editor
->sci
, replace_text
, flags
& SCFIND_REGEXP
);
2045 /* select the replacement - find text will skip past the selected text */
2046 sci_set_selection_start(doc
->editor
->sci
, search_pos
);
2047 sci_set_selection_end(doc
->editor
->sci
, search_pos
+ replace_len
);
2051 /* no match in the selection */
2058 static void show_replace_summary(GeanyDocument
*doc
, gint count
, const gchar
*find_text
,
2059 const gchar
*replace_text
, gboolean escaped_chars
)
2061 gchar
*escaped_find_text
, *escaped_replace_text
, *filename
;
2065 ui_set_statusbar(FALSE
, _("No matches found for \"%s\"."), find_text
);
2069 filename
= g_path_get_basename(DOC_FILENAME(doc
));
2072 { /* escape special characters for showing */
2073 escaped_find_text
= g_strescape(find_text
, NULL
);
2074 escaped_replace_text
= g_strescape(replace_text
, NULL
);
2075 ui_set_statusbar(TRUE
, ngettext(
2076 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2077 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2078 count
), filename
, count
, escaped_find_text
, escaped_replace_text
);
2079 g_free(escaped_find_text
);
2080 g_free(escaped_replace_text
);
2084 ui_set_statusbar(TRUE
, ngettext(
2085 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2086 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2087 count
), filename
, count
, find_text
, replace_text
);
2093 /* Replace all text matches in a certain range within document.
2094 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2095 * or -1 if no text was found.
2096 * scroll_to_match is whether to scroll the last replacement in view (which also
2097 * clears the selection).
2098 * Returns: the number of replacements made. */
2100 document_replace_range(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2101 gint flags
, gint start
, gint end
, gboolean scroll_to_match
, gint
*new_range_end
)
2104 struct Sci_TextToFind ttf
;
2105 ScintillaObject
*sci
;
2107 if (new_range_end
!= NULL
)
2108 *new_range_end
= -1;
2110 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, 0);
2112 if (! *find_text
|| doc
->readonly
)
2115 sci
= doc
->editor
->sci
;
2117 ttf
.chrg
.cpMin
= start
;
2118 ttf
.chrg
.cpMax
= end
;
2119 ttf
.lpstrText
= (gchar
*)find_text
;
2121 sci_start_undo_action(sci
);
2122 count
= search_replace_range(sci
, &ttf
, flags
, replace_text
);
2123 sci_end_undo_action(sci
);
2126 { /* scroll last match in view, will destroy the existing selection */
2127 if (scroll_to_match
)
2128 sci_goto_pos(sci
, ttf
.chrg
.cpMin
, TRUE
);
2130 if (new_range_end
!= NULL
)
2131 *new_range_end
= ttf
.chrg
.cpMax
;
2137 void document_replace_sel(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2138 gint flags
, gboolean escaped_chars
)
2140 gint selection_end
, selection_start
, selection_mode
, selected_lines
, last_line
= 0;
2141 gint max_column
= 0, count
= 0;
2142 gboolean replaced
= FALSE
;
2144 g_return_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
);
2149 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2150 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2151 /* do we have a selection? */
2152 if ((selection_end
- selection_start
) == 0)
2158 selection_mode
= sci_get_selection_mode(doc
->editor
->sci
);
2159 selected_lines
= sci_get_lines_selected(doc
->editor
->sci
);
2160 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2161 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2163 gint first_line
, line
;
2165 sci_start_undo_action(doc
->editor
->sci
);
2167 first_line
= sci_get_line_from_position(doc
->editor
->sci
, selection_start
);
2168 /* Find the last line with chars selected (not EOL char) */
2169 last_line
= sci_get_line_from_position(doc
->editor
->sci
,
2170 selection_end
- editor_get_eol_char_len(doc
->editor
));
2171 last_line
= MAX(first_line
, last_line
);
2172 for (line
= first_line
; line
< (first_line
+ selected_lines
); line
++)
2174 gint line_start
= sci_get_pos_at_line_sel_start(doc
->editor
->sci
, line
);
2175 gint line_end
= sci_get_pos_at_line_sel_end(doc
->editor
->sci
, line
);
2177 /* skip line if there is no selection */
2178 if (line_start
!= INVALID_POSITION
)
2180 /* don't let document_replace_range() scroll to match to keep our selection */
2183 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2184 line_start
, line_end
, FALSE
, &new_sel_end
);
2185 if (new_sel_end
!= -1)
2188 /* this gets the greatest column within the selection after replacing */
2189 max_column
= MAX(max_column
,
2190 new_sel_end
- sci_get_position_from_line(doc
->editor
->sci
, line
));
2194 sci_end_undo_action(doc
->editor
->sci
);
2196 else /* handle normal line selection */
2198 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2199 selection_start
, selection_end
, TRUE
, &selection_end
);
2200 if (selection_end
!= -1)
2205 { /* update the selection for the new endpoint */
2207 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2209 /* now we can scroll to the selection and destroy it because we rebuild it later */
2210 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2212 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2213 * the highest column on the last line. The wrapped selection is completely different
2214 * from the original one, so skip the selection at all */
2215 /* TODO is there a better way to handle the wrapped selection? */
2216 if ((sci_get_line_length(doc
->editor
->sci
, last_line
) - 1) >= max_column
)
2217 { /* for keeping and adjusting the selection in multi line rectangle selection we
2218 * need the last line of the original selection and the greatest column number after
2219 * replacing and set the selection end to the last line at the greatest column */
2220 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2221 sci_set_selection_end(doc
->editor
->sci
,
2222 sci_get_position_from_line(doc
->editor
->sci
, last_line
) + max_column
);
2223 sci_set_selection_mode(doc
->editor
->sci
, selection_mode
);
2228 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2229 sci_set_selection_end(doc
->editor
->sci
, selection_end
);
2232 else /* no replacements */
2235 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2239 /* returns number of replacements made. */
2240 gint
document_replace_all(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2241 gint flags
, gboolean escaped_chars
)
2244 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, FALSE
);
2249 len
= sci_get_length(doc
->editor
->sci
);
2250 count
= document_replace_range(
2251 doc
, find_text
, replace_text
, flags
, 0, len
, TRUE
, NULL
);
2253 show_replace_summary(doc
, count
, find_text
, replace_text
, escaped_chars
);
2258 static gboolean
update_tags_from_buffer(GeanyDocument
*doc
)
2263 result
= tm_source_file_update(doc
->tm_file
, TRUE
, FALSE
, TRUE
);
2265 gsize len
= sci_get_length(doc
->editor
->sci
) + 1;
2266 gchar
*text
= g_malloc(len
);
2268 /* we copy the whole text into memory instead using a direct char pointer from
2269 * Scintilla because tm_source_file_buffer_update() does modify the string slightly */
2270 sci_get_text(doc
->editor
->sci
, len
, text
);
2271 result
= tm_source_file_buffer_update(doc
->tm_file
, (guchar
*) text
, len
, TRUE
);
2278 void document_update_tag_list(GeanyDocument
*doc
, gboolean update
)
2280 /* We must call sidebar_update_tag_list() before returning,
2281 * to ensure that the symbol list is always updated properly (e.g.
2282 * when creating a new document with a partial filename set. */
2283 gboolean success
= FALSE
;
2285 /* if the filetype doesn't have a tag parser or it is a new file */
2286 if (doc
== NULL
|| doc
->file_type
== NULL
|| app
->tm_workspace
== NULL
||
2287 ! filetype_has_tags(doc
->file_type
) || ! doc
->file_name
)
2289 /* set the default (empty) tag list */
2290 sidebar_update_tag_list(doc
, FALSE
);
2294 if (doc
->tm_file
== NULL
)
2296 gchar
*locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2299 /* lookup the name rather than using filetype name to support custom filetypes */
2300 name
= tm_source_file_get_lang_name(doc
->file_type
->lang
);
2301 doc
->tm_file
= tm_source_file_new(locale_filename
, FALSE
, name
);
2302 g_free(locale_filename
);
2306 if (!tm_workspace_add_object(doc
->tm_file
))
2308 tm_work_object_free(doc
->tm_file
);
2309 doc
->tm_file
= NULL
;
2314 update_tags_from_buffer(doc
);
2321 success
= update_tags_from_buffer(doc
);
2322 if (G_UNLIKELY(! success
))
2323 geany_debug("tag list updating failed");
2325 sidebar_update_tag_list(doc
, success
);
2329 /* Caches the list of project typenames, as a space separated GString.
2330 * Returns: TRUE if typenames have changed.
2331 * (*types) is set to the list of typenames, or NULL if there are none. */
2332 static gboolean
get_project_typenames(const GString
**types
, gint lang
)
2334 static GString
*last_typenames
= NULL
;
2337 if (app
->tm_workspace
)
2339 GPtrArray
*tags_array
= app
->tm_workspace
->work_object
.tags_array
;
2343 s
= symbols_find_tags_as_string(tags_array
, TM_GLOBAL_TYPE_MASK
, lang
);
2347 if (s
&& last_typenames
&& g_string_equal(s
, last_typenames
))
2349 g_string_free(s
, TRUE
);
2350 *types
= last_typenames
;
2351 return FALSE
; /* project typenames haven't changed */
2353 /* cache typename list for next time */
2355 g_string_free(last_typenames
, TRUE
);
2365 /* If sci is NULL, update project typenames for all documents that support typenames,
2366 * if typenames have changed.
2367 * If sci is not NULL, then if sci supports typenames, project typenames are updated
2368 * if necessary, and typename keywords are set for sci.
2369 * Returns: TRUE if any scintilla type keywords were updated. */
2370 static gboolean
update_type_keywords(GeanyDocument
*doc
, gint lang
)
2372 gboolean ret
= FALSE
;
2375 ScintillaObject
*sci
;
2377 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2378 sci
= doc
->editor
->sci
;
2380 switch (FILETYPE_ID(doc
->file_type
))
2381 { /* continue working with the following languages, skip on all others */
2382 case GEANY_FILETYPES_C
:
2383 case GEANY_FILETYPES_CPP
:
2384 case GEANY_FILETYPES_CS
:
2385 case GEANY_FILETYPES_D
:
2386 case GEANY_FILETYPES_JAVA
:
2387 case GEANY_FILETYPES_VALA
:
2393 sci
= doc
->editor
->sci
;
2394 if (sci
!= NULL
&& editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
)) == -1)
2397 if (! get_project_typenames(&s
, lang
))
2398 { /* typenames have not changed */
2399 if (s
!= NULL
&& sci
!= NULL
)
2401 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(sci
));
2403 sci_set_keywords(sci
, keyword_idx
, s
->str
);
2404 queue_colourise(doc
);
2408 g_return_val_if_fail(s
!= NULL
, FALSE
);
2410 for (n
= 0; n
< documents_array
->len
; n
++)
2412 if (documents
[n
]->is_valid
)
2414 ScintillaObject
*wid
= documents
[n
]->editor
->sci
;
2415 gint keyword_idx
= editor_lexer_get_type_keyword_idx(sci_get_lexer(wid
));
2417 if (keyword_idx
> 0)
2419 sci_set_keywords(wid
, keyword_idx
, s
->str
);
2420 queue_colourise(documents
[n
]);
2429 static void document_load_config(GeanyDocument
*doc
, GeanyFiletype
*type
,
2430 gboolean filetype_changed
)
2432 g_return_if_fail(doc
);
2434 type
= filetypes
[GEANY_FILETYPES_NONE
];
2436 if (filetype_changed
)
2438 doc
->file_type
= type
;
2440 /* delete tm file object to force creation of a new one */
2441 if (doc
->tm_file
!= NULL
)
2443 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
2444 doc
->tm_file
= NULL
;
2446 /* load tags files before highlighting (some lexers highlight global typenames) */
2447 if (type
->id
!= GEANY_FILETYPES_NONE
)
2448 symbols_global_tags_loaded(type
->id
);
2450 highlighting_set_styles(doc
->editor
->sci
, type
);
2451 editor_set_indentation_guides(doc
->editor
);
2452 build_menu_update(doc
);
2453 queue_colourise(doc
);
2456 document_update_tag_list(doc
, TRUE
);
2458 /* Update session typename keywords. */
2459 update_type_keywords(doc
, type
->lang
);
2463 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2464 * @param doc The document to use.
2465 * @param type The filetype. */
2466 void document_set_filetype(GeanyDocument
*doc
, GeanyFiletype
*type
)
2468 gboolean ft_changed
;
2469 GeanyFiletype
*old_ft
;
2471 g_return_if_fail(doc
);
2473 type
= filetypes
[GEANY_FILETYPES_NONE
];
2475 old_ft
= doc
->file_type
;
2476 geany_debug("%s : %s (%s)",
2477 (doc
->file_name
!= NULL
) ? doc
->file_name
: "unknown",
2478 (type
->name
!= NULL
) ? type
->name
: "unknown",
2479 (doc
->encoding
!= NULL
) ? doc
->encoding
: "unknown");
2481 ft_changed
= (doc
->file_type
!= type
); /* filetype has changed */
2482 document_load_config(doc
, type
, ft_changed
);
2485 g_signal_emit_by_name(geany_object
, "document-filetype-set", doc
, old_ft
);
2489 void document_reload_config(GeanyDocument
*doc
)
2491 document_load_config(doc
, doc
->file_type
, TRUE
);
2496 * Sets the encoding of a document.
2497 * This function only set the encoding of the %document, it does not any conversions. The new
2498 * encoding is used when e.g. saving the file.
2500 * @param doc The document to use.
2501 * @param new_encoding The encoding to be set for the document.
2503 void document_set_encoding(GeanyDocument
*doc
, const gchar
*new_encoding
)
2505 if (doc
== NULL
|| new_encoding
== NULL
||
2506 utils_str_equal(new_encoding
, doc
->encoding
))
2509 g_free(doc
->encoding
);
2510 doc
->encoding
= g_strdup(new_encoding
);
2512 ui_update_statusbar(doc
, -1);
2513 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets
.window
, "menu_write_unicode_bom1"),
2514 encodings_is_unicode_charset(doc
->encoding
));
2518 /* own Undo / Redo implementation to be able to undo / redo changes
2519 * to the encoding or the Unicode BOM (which are Scintilla independet).
2520 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2522 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2523 void document_undo_clear(GeanyDocument
*doc
)
2527 while (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0)
2529 a
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2530 if (G_LIKELY(a
!= NULL
))
2534 case UNDO_ENCODING
: g_free(a
->data
); break;
2540 doc
->priv
->undo_actions
= NULL
;
2542 while (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0)
2544 a
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2545 if (G_LIKELY(a
!= NULL
))
2549 case UNDO_ENCODING
: g_free(a
->data
); break;
2555 doc
->priv
->redo_actions
= NULL
;
2557 if (! main_status
.quitting
&& doc
->editor
!= NULL
)
2558 document_set_text_changed(doc
, FALSE
);
2562 void document_undo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2564 undo_action
*action
;
2566 g_return_if_fail(doc
!= NULL
);
2568 action
= g_new0(undo_action
, 1);
2569 action
->type
= type
;
2570 action
->data
= data
;
2572 g_trash_stack_push(&doc
->priv
->undo_actions
, action
);
2574 document_set_text_changed(doc
, TRUE
);
2575 ui_update_popup_reundo_items(doc
);
2579 gboolean
document_can_undo(GeanyDocument
*doc
)
2581 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2583 if (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0 || sci_can_undo(doc
->editor
->sci
))
2590 static void update_changed_state(GeanyDocument
*doc
)
2593 (sci_is_modified(doc
->editor
->sci
) ||
2594 doc
->has_bom
!= doc
->priv
->saved_encoding
.has_bom
||
2595 ! utils_str_equal(doc
->encoding
, doc
->priv
->saved_encoding
.encoding
));
2596 document_set_text_changed(doc
, doc
->changed
);
2600 void document_undo(GeanyDocument
*doc
)
2602 undo_action
*action
;
2604 g_return_if_fail(doc
!= NULL
);
2606 action
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2608 if (G_UNLIKELY(action
== NULL
))
2610 /* fallback, should not be necessary */
2611 geany_debug("%s: fallback used", G_STRFUNC
);
2612 sci_undo(doc
->editor
->sci
);
2616 switch (action
->type
)
2618 case UNDO_SCINTILLA
:
2620 document_redo_add(doc
, UNDO_SCINTILLA
, NULL
);
2622 sci_undo(doc
->editor
->sci
);
2627 document_redo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2629 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2630 ui_update_statusbar(doc
, -1);
2631 ui_document_show_hide(doc
);
2636 /* use the "old" encoding */
2637 document_redo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2639 document_set_encoding(doc
, (const gchar
*)action
->data
);
2641 ignore_callback
= TRUE
;
2642 encodings_select_radio_item((const gchar
*)action
->data
);
2643 ignore_callback
= FALSE
;
2645 g_free(action
->data
);
2651 g_free(action
); /* free the action which was taken from the stack */
2653 update_changed_state(doc
);
2654 ui_update_popup_reundo_items(doc
);
2658 gboolean
document_can_redo(GeanyDocument
*doc
)
2660 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2662 if (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0 || sci_can_redo(doc
->editor
->sci
))
2669 void document_redo(GeanyDocument
*doc
)
2671 undo_action
*action
;
2673 g_return_if_fail(doc
!= NULL
);
2675 action
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2677 if (G_UNLIKELY(action
== NULL
))
2679 /* fallback, should not be necessary */
2680 geany_debug("%s: fallback used", G_STRFUNC
);
2681 sci_redo(doc
->editor
->sci
);
2685 switch (action
->type
)
2687 case UNDO_SCINTILLA
:
2689 document_undo_add(doc
, UNDO_SCINTILLA
, NULL
);
2691 sci_redo(doc
->editor
->sci
);
2696 document_undo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2698 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2699 ui_update_statusbar(doc
, -1);
2700 ui_document_show_hide(doc
);
2705 document_undo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2707 document_set_encoding(doc
, (const gchar
*)action
->data
);
2709 ignore_callback
= TRUE
;
2710 encodings_select_radio_item((const gchar
*)action
->data
);
2711 ignore_callback
= FALSE
;
2713 g_free(action
->data
);
2719 g_free(action
); /* free the action which was taken from the stack */
2721 update_changed_state(doc
);
2722 ui_update_popup_reundo_items(doc
);
2726 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2728 undo_action
*action
;
2730 g_return_if_fail(doc
!= NULL
);
2732 action
= g_new0(undo_action
, 1);
2733 action
->type
= type
;
2734 action
->data
= data
;
2736 g_trash_stack_push(&doc
->priv
->redo_actions
, action
);
2738 document_set_text_changed(doc
, TRUE
);
2739 ui_update_popup_reundo_items(doc
);
2744 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2745 * Returned colors are red if the document has changes, green if the document is read-only
2746 * or simply @c NULL if the document is unmodified but writable.
2748 * @param doc The document to use.
2750 * @return The color for the document or @c NULL if the default color should be used. The color
2751 * object is owned by Geany and should not be modified or freed.
2755 const GdkColor
*document_get_status_color(GeanyDocument
*doc
)
2757 static GdkColor red
= {0, 0xFFFF, 0, 0};
2758 static GdkColor green
= {0, 0, 0x7FFF, 0};
2760 static GdkColor orange
= {0, 0xFFFF, 0x7FFF, 0};
2762 GdkColor
*color
= NULL
;
2764 g_return_val_if_fail(doc
!= NULL
, NULL
);
2769 else if (doc
->priv
->file_disk_status
== FILE_CHANGED
)
2772 else if (doc
->readonly
)
2775 return color
; /* return pointer to static GdkColor. */
2779 /** Accessor function for @ref GeanyData::documents_array items.
2780 * @warning Always check the returned document is valid (@c doc->is_valid).
2781 * @param idx @c documents_array index.
2782 * @return The document, or @c NULL if @a idx is out of range.
2786 GeanyDocument
*document_index(gint idx
)
2788 return (idx
>= 0 && idx
< (gint
) documents_array
->len
) ? documents
[idx
] : NULL
;
2792 /* create a new file and copy file content and properties */
2793 GeanyDocument
*document_clone(GeanyDocument
*old_doc
, const gchar
*utf8_filename
)
2799 g_return_val_if_fail(old_doc
!= NULL
, NULL
);
2801 len
= sci_get_length(old_doc
->editor
->sci
) + 1;
2802 text
= (gchar
*) g_malloc(len
);
2803 sci_get_text(old_doc
->editor
->sci
, len
, text
);
2804 /* use old file type (or maybe NULL for auto detect would be better?) */
2805 doc
= document_new_file(utf8_filename
, old_doc
->file_type
, text
);
2808 /* copy file properties */
2809 doc
->editor
->line_wrapping
= old_doc
->editor
->line_wrapping
;
2810 doc
->readonly
= old_doc
->readonly
;
2811 doc
->has_bom
= old_doc
->has_bom
;
2812 document_set_encoding(doc
, old_doc
->encoding
);
2813 sci_set_lines_wrapped(doc
->editor
->sci
, doc
->editor
->line_wrapping
);
2814 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
2816 ui_document_show_hide(doc
);
2821 /* @note If successful, this should always be followed up with a call to
2822 * document_close_all().
2823 * @return TRUE if all files were saved or had their changes discarded. */
2824 gboolean
document_account_for_unsaved(void)
2826 guint i
, p
, page_count
, len
= documents_array
->len
;
2829 page_count
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
2830 for (p
= 0; p
< page_count
; p
++)
2832 doc
= document_get_from_page(p
);
2835 if (! dialogs_show_unsaved_file(doc
))
2839 /* all documents should now be accounted for, so ignore any changes */
2840 for (i
= 0; i
< len
; i
++)
2843 if (doc
->is_valid
&& doc
->changed
)
2845 doc
->changed
= FALSE
;
2852 static void force_close_all(void)
2854 guint i
, len
= documents_array
->len
;
2856 /* check all documents have been accounted for */
2857 for (i
= 0; i
< len
; i
++)
2859 if (documents
[i
]->is_valid
)
2861 g_return_if_fail(!documents
[i
]->changed
);
2864 main_status
.closing_all
= TRUE
;
2866 while (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) > 0)
2868 document_remove_page(0);
2871 main_status
.closing_all
= FALSE
;
2875 gboolean
document_close_all(void)
2877 if (! document_account_for_unsaved())
2886 static gboolean
monitor_reload_file(GeanyDocument
*doc
)
2888 gchar
*base_name
= g_path_get_basename(doc
->file_name
);
2889 gboolean want_reload
;
2891 want_reload
= dialogs_show_question_full(NULL
, _("_Reload"), GTK_STOCK_CANCEL
,
2892 _("Do you want to reload it?"),
2893 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2897 document_reload_file(doc
, doc
->encoding
);
2904 static gboolean
monitor_resave_missing_file(GeanyDocument
*doc
)
2906 gboolean want_reload
= FALSE
;
2907 gboolean file_saved
= FALSE
;
2910 ret
= dialogs_show_prompt(NULL
,
2911 _("Close _without saving"), GTK_RESPONSE_CLOSE
,
2912 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
2913 GTK_STOCK_SAVE
, GTK_RESPONSE_ACCEPT
,
2915 _("File \"%s\" was not found on disk! Try to resave the file?"),
2917 if (ret
== GTK_RESPONSE_ACCEPT
)
2919 file_saved
= dialogs_show_save_as();
2922 else if (ret
== GTK_RESPONSE_CLOSE
)
2924 document_close(doc
);
2926 if (ret
!= GTK_RESPONSE_CLOSE
&& ! file_saved
)
2928 /* file is missing - set unsaved state */
2929 document_set_text_changed(doc
, TRUE
);
2930 /* don't prompt more than once */
2931 setptr(doc
->real_path
, NULL
);
2938 /* Set force to force a disk check, otherwise it is ignored if there was a check
2939 * in the last file_prefs.disk_check_timeout seconds.
2940 * @return @c TRUE if the file has changed. */
2941 gboolean
document_check_disk_status(GeanyDocument
*doc
, gboolean force
)
2943 gboolean ret
= FALSE
;
2944 gboolean use_gio_filemon
;
2945 time_t cur_time
= 0;
2947 gchar
*locale_filename
;
2948 FileDiskStatus old_status
;
2950 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2952 /* ignore remote files and documents that have never been saved to disk */
2953 if (file_prefs
.disk_check_timeout
== 0 || doc
->real_path
== NULL
|| doc
->priv
->is_remote
)
2956 use_gio_filemon
= (doc
->priv
->monitor
!= NULL
);
2958 if (use_gio_filemon
)
2960 if (doc
->priv
->file_disk_status
!= FILE_CHANGED
&& ! force
)
2965 cur_time
= time(NULL
);
2966 if (! force
&& doc
->priv
->last_check
> (cur_time
- file_prefs
.disk_check_timeout
))
2969 doc
->priv
->last_check
= cur_time
;
2972 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2973 if (g_stat(locale_filename
, &st
) != 0)
2975 monitor_resave_missing_file(doc
);
2978 else if (! use_gio_filemon
&& /* ignore these checks when using GIO */
2979 (G_UNLIKELY(doc
->priv
->mtime
> cur_time
) || G_UNLIKELY(st
.st_mtime
> cur_time
)))
2981 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC
);
2983 else if (doc
->priv
->mtime
< st
.st_mtime
)
2985 monitor_reload_file(doc
);
2986 doc
->priv
->mtime
= st
.st_mtime
;
2989 g_free(locale_filename
);
2992 { /* doc can get invalid when a document was closed by monitor_resave_missing_file() */
2993 old_status
= doc
->priv
->file_disk_status
;
2994 doc
->priv
->file_disk_status
= FILE_OK
;
2995 if (old_status
!= doc
->priv
->file_disk_status
)
2996 ui_update_tab_status(doc
);