2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005 The Geany contributors
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 2 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along
17 * with this program; if not, write to the Free Software Foundation, Inc.,
18 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 * Document related actions: new, save, open, etc.
23 * Also Scintilla search actions.
33 #include "callbacks.h" /* for ignore_callback */
35 #include "documentprivate.h"
36 #include "encodings.h"
37 #include "encodingsprivate.h"
38 #include "filetypesprivate.h"
39 #include "geany.h" /* FIXME: why is this needed for DOC_FILENAME()? should come from documentprivate.h/document.h */
40 #include "geanyobject.h"
41 #include "geanywraplabel.h"
42 #include "highlighting.h"
44 #include "msgwindow.h"
48 #include "sciwrappers.h"
57 #ifdef HAVE_SYS_TIME_H
58 # include <sys/time.h>
66 #ifdef HAVE_SYS_TYPES_H
67 # include <sys/types.h>
72 /* gstdio.h also includes sys/stat.h */
73 #include <glib/gstdio.h>
75 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
76 /*#define USE_GIO_FILEMON 1*/
80 #include <gdk/gdkkeysyms.h>
83 #define USE_GIO_FILE_OPERATIONS (!file_prefs.use_safe_file_saving && file_prefs.use_gio_unsafe_file_saving)
86 GeanyFilePrefs file_prefs
;
87 GPtrArray
*documents_array
= NULL
;
90 /* an undo action, also used for redo actions */
93 GTrashStack
*next
; /* pointer to the next stack element(required for the GTrashStack) */
94 guint type
; /* to identify the action */
95 gpointer
*data
; /* the old value (before the change), in case of a redo action
96 * it contains the new value */
99 /* Custom document info bar response IDs */
102 RESPONSE_DOCUMENT_RELOAD
= 1,
103 RESPONSE_DOCUMENT_SAVE
,
107 static guint show_tab_idle
= 0;
108 static guint doc_id_counter
= 0;
111 static void document_undo_clear_stack(GTrashStack
**stack
);
112 static void document_undo_clear(GeanyDocument
*doc
);
113 static void document_undo_add_internal(GeanyDocument
*doc
, guint type
, gpointer data
);
114 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
);
115 static gboolean
remove_page(guint page_num
);
116 static GtkWidget
* document_show_message(GeanyDocument
*doc
, GtkMessageType msgtype
,
117 void (*response_cb
)(GtkWidget
*info_bar
, gint response_id
, GeanyDocument
*doc
),
118 const gchar
*btn_1
, GtkResponseType response_1
,
119 const gchar
*btn_2
, GtkResponseType response_2
,
120 const gchar
*btn_3
, GtkResponseType response_3
,
121 const gchar
*extra_text
, const gchar
*format
, ...) G_GNUC_PRINTF(11, 12);
125 * Finds a document whose @c real_path field matches the given filename.
127 * @param realname The filename to search, which should be identical to the
128 * string returned by @c utils_get_real_path().
130 * @return @transfer{none} @nullable The matching document, or @c NULL.
131 * @note This is only really useful when passing a @c TMSourceFile::file_name.
132 * @see GeanyDocument::real_path.
133 * @see document_find_by_filename().
138 GeanyDocument
* document_find_by_real_path(const gchar
*realname
)
143 return NULL
; /* file doesn't exist on disk */
145 for (i
= 0; i
< documents_array
->len
; i
++)
147 GeanyDocument
*doc
= documents
[i
];
149 if (! doc
->is_valid
|| ! doc
->real_path
)
152 if (utils_filenamecmp(realname
, doc
->real_path
) == 0)
161 /* dereference symlinks, /../ junk in path and return locale encoding */
162 static gchar
*get_real_path_from_utf8(const gchar
*utf8_filename
)
164 gchar
*locale_name
= utils_get_locale_from_utf8(utf8_filename
);
165 gchar
*realname
= utils_get_real_path(locale_name
);
173 * Finds a document with the given filename.
174 * This matches either an exact GeanyDocument::file_name string, or variant
175 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
178 * @param utf8_filename The filename to search (in UTF-8 encoding).
180 * @return @transfer{none} @nullable The matching document, or @c NULL.
181 * @see document_find_by_real_path().
184 GeanyDocument
*document_find_by_filename(const gchar
*utf8_filename
)
190 g_return_val_if_fail(utf8_filename
!= NULL
, NULL
);
192 /* First search GeanyDocument::file_name, so we can find documents with a
193 * filename set but not saved on disk, like vcdiff produces */
194 for (i
= 0; i
< documents_array
->len
; i
++)
198 if (! doc
->is_valid
|| doc
->file_name
== NULL
)
201 if (utils_filenamecmp(utf8_filename
, doc
->file_name
) == 0)
206 /* Now try matching based on the realpath(), which is unique per file on disk */
207 realname
= get_real_path_from_utf8(utf8_filename
);
208 doc
= document_find_by_real_path(realname
);
214 /* returns the document which has sci, or NULL. */
215 GeanyDocument
*document_find_by_sci(ScintillaObject
*sci
)
219 g_return_val_if_fail(sci
!= NULL
, NULL
);
221 for (i
= 0; i
< documents_array
->len
; i
++)
223 if (documents
[i
]->is_valid
&& documents
[i
]->editor
->sci
== sci
)
230 /** Lookup an old document by its ID.
231 * Useful when the corresponding document may have been closed since the
233 * @param id The ID of the document to find
234 * @return @transfer{none} @c NULL if the document is no longer open.
239 * GeanyDocument *doc = ...;
240 * id = doc->id; // store ID
242 * // time passes - the document may have been closed by now
243 * GeanyDocument *doc = document_find_by_id(id);
244 * gboolean still_open = (doc != NULL);
248 GeanyDocument
*document_find_by_id(guint id
)
257 if (documents
[i
]->id
== id
)
264 /* gets the widget the main_widgets.notebook consider is its child for this document */
265 static GtkWidget
*document_get_notebook_child(GeanyDocument
*doc
)
270 g_return_val_if_fail(doc
!= NULL
, NULL
);
272 child
= GTK_WIDGET(doc
->editor
->sci
);
273 parent
= gtk_widget_get_parent(child
);
274 /* search for the direct notebook child, mirroring document_get_from_page() */
275 while (parent
&& ! GTK_IS_NOTEBOOK(parent
))
278 parent
= gtk_widget_get_parent(child
);
285 /** Gets the notebook page index for a document.
286 * @param doc The document.
290 gint
document_get_notebook_page(GeanyDocument
*doc
)
292 GtkWidget
*child
= document_get_notebook_child(doc
);
294 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
), child
);
299 * Recursively searches a containers children until it finds a
300 * Scintilla widget, or NULL if one was not found.
302 static ScintillaObject
*locate_sci_in_container(GtkWidget
*container
)
304 ScintillaObject
*sci
= NULL
;
305 GList
*children
, *iter
;
307 g_return_val_if_fail(GTK_IS_CONTAINER(container
), NULL
);
309 children
= gtk_container_get_children(GTK_CONTAINER(container
));
310 for (iter
= children
; iter
!= NULL
; iter
= g_list_next(iter
))
312 if (IS_SCINTILLA(iter
->data
))
314 sci
= SCINTILLA(iter
->data
);
317 else if (GTK_IS_CONTAINER(iter
->data
))
319 sci
= locate_sci_in_container(iter
->data
);
320 if (IS_SCINTILLA(sci
))
325 g_list_free(children
);
331 /* Finds the document for the given notebook page widget */
332 GeanyDocument
*document_get_from_notebook_child(GtkWidget
*page
)
334 ScintillaObject
*sci
;
336 g_return_val_if_fail(GTK_IS_BOX(page
), NULL
);
338 sci
= locate_sci_in_container(page
);
339 g_return_val_if_fail(IS_SCINTILLA(sci
), NULL
);
341 return document_find_by_sci(sci
);
346 * Finds the document for the given notebook page @a page_num.
348 * @param page_num The notebook page number to search.
350 * @return @transfer{none} @nullable The corresponding document for the given notebook page, or @c NULL.
353 GeanyDocument
*document_get_from_page(guint page_num
)
357 if (page_num
>= documents_array
->len
)
360 parent
= gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets
.notebook
), page_num
);
362 return document_get_from_notebook_child(parent
);
367 * Finds the current document.
369 * @return @transfer{none} @nullable A pointer to the current document or @c NULL if there are no opened documents.
372 GeanyDocument
*document_get_current(void)
374 gint cur_page
= gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets
.notebook
));
379 return document_get_from_page((guint
) cur_page
);
383 void document_init_doclist(void)
385 documents_array
= g_ptr_array_new();
389 void document_finalize(void)
393 for (i
= 0; i
< documents_array
->len
; i
++)
394 g_free(documents
[i
]);
395 g_ptr_array_free(documents_array
, TRUE
);
400 * Returns the last part of the filename of the given GeanyDocument. The result is also
401 * truncated to a maximum of @a length characters in case the filename is very long.
403 * @param doc The document to use.
404 * @param length The length of the resulting string or -1 to use a default value.
406 * @return The ellipsized last part of the filename of @a doc, should be freed when no
411 /* TODO make more use of this */
413 gchar
*document_get_basename_for_display(GeanyDocument
*doc
, gint length
)
415 gchar
*base_name
, *short_name
;
417 g_return_val_if_fail(doc
!= NULL
, NULL
);
422 base_name
= g_path_get_basename(DOC_FILENAME(doc
));
423 short_name
= utils_str_middle_truncate(base_name
, (guint
)length
);
431 void document_update_tab_label(GeanyDocument
*doc
)
436 g_return_if_fail(doc
!= NULL
);
438 short_name
= document_get_basename_for_display(doc
, interface_prefs
.tab_label_len
);
440 /* we need to use the event box for the tooltip, labels don't get the necessary events */
441 parent
= gtk_widget_get_parent(doc
->priv
->tab_label
);
442 parent
= gtk_widget_get_parent(parent
);
444 gtk_label_set_text(GTK_LABEL(doc
->priv
->tab_label
), short_name
);
446 gtk_widget_set_tooltip_text(parent
, DOC_FILENAME(doc
));
453 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
454 * according to the document's save state.
455 * This is called by Geany mostly when opening or saving files.
457 * @param doc The document to use.
458 * @param changed Whether the document state should indicate changes have been made.
461 void document_set_text_changed(GeanyDocument
*doc
, gboolean changed
)
463 g_return_if_fail(doc
!= NULL
);
465 doc
->changed
= changed
;
467 if (! main_status
.quitting
)
469 ui_update_tab_status(doc
);
470 ui_save_buttons_toggle(changed
);
471 ui_set_window_title(doc
);
472 ui_update_statusbar(doc
, -1);
477 /* returns the next free place in the document list,
478 * or -1 if the documents_array is full */
479 static gint
document_get_new_idx(void)
483 for (i
= 0; i
< documents_array
->len
; i
++)
485 if (documents
[i
]->editor
== NULL
)
494 static void queue_colourise(GeanyDocument
*doc
)
496 if (doc
->priv
->colourise_needed
)
499 /* Colourise the editor before it is next drawn */
500 doc
->priv
->colourise_needed
= TRUE
;
502 /* If the editor doesn't need drawing (e.g. after saving the current
503 * document), we need to force a redraw, so the expose event is triggered.
504 * This ensures we don't start colourising before all documents are opened/saved,
505 * only once the editor is drawn. */
506 gtk_widget_queue_draw(GTK_WIDGET(doc
->editor
->sci
));
510 #ifdef USE_GIO_FILEMON
511 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor
*monitor
, G_GNUC_UNUSED GFile
*file
,
512 G_GNUC_UNUSED GFile
*other_file
, GFileMonitorEvent event
,
515 g_return_if_fail(doc
!= NULL
);
517 if (file_prefs
.disk_check_timeout
== 0)
520 geany_debug("%s: event: %d previous file status: %d",
521 G_STRFUNC
, event
, doc
->priv
->file_disk_status
);
524 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT
:
526 if (doc
->priv
->file_disk_status
== FILE_IGNORE
)
527 doc
->priv
->file_disk_status
= FILE_OK
;
529 doc
->priv
->file_disk_status
= FILE_CHANGED
;
530 g_message("%s: FILE_CHANGED", G_STRFUNC
);
533 case G_FILE_MONITOR_EVENT_DELETED
:
535 doc
->priv
->file_disk_status
= FILE_CHANGED
;
536 g_message("%s: FILE_MISSING", G_STRFUNC
);
542 if (doc
->priv
->file_disk_status
!= FILE_OK
)
544 ui_update_tab_status(doc
);
550 static void document_stop_file_monitoring(GeanyDocument
*doc
)
552 g_return_if_fail(doc
!= NULL
);
554 if (doc
->priv
->monitor
!= NULL
)
556 g_object_unref(doc
->priv
->monitor
);
557 doc
->priv
->monitor
= NULL
;
562 static void monitor_file_setup(GeanyDocument
*doc
)
564 g_return_if_fail(doc
!= NULL
);
565 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
566 * doesn't work at all for remote files and legacy polling is too slow. */
567 if (! doc
->priv
->is_remote
)
569 #ifdef USE_GIO_FILEMON
570 gchar
*locale_filename
;
572 /* stop any previous monitoring */
573 document_stop_file_monitoring(doc
);
575 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
576 if (locale_filename
!= NULL
&& g_file_test(locale_filename
, G_FILE_TEST_EXISTS
))
578 /* get a file monitor and connect to the 'changed' signal */
579 GFile
*file
= g_file_new_for_path(locale_filename
);
580 doc
->priv
->monitor
= g_file_monitor_file(file
, G_FILE_MONITOR_NONE
, NULL
, NULL
);
581 g_signal_connect(doc
->priv
->monitor
, "changed",
582 G_CALLBACK(monitor_file_changed_cb
), doc
);
584 /* we set the rate limit according to the GUI pref but it's most probably not used */
585 g_file_monitor_set_rate_limit(doc
->priv
->monitor
, file_prefs
.disk_check_timeout
* 1000);
587 g_object_unref(file
);
589 g_free(locale_filename
);
592 doc
->priv
->file_disk_status
= FILE_OK
;
596 void document_try_focus(GeanyDocument
*doc
, GtkWidget
*source_widget
)
598 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
601 GtkWidget
*sci
= GTK_WIDGET(doc
->editor
->sci
);
602 GtkWidget
*focusw
= gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
));
604 if (source_widget
== NULL
)
605 source_widget
= doc
->priv
->tag_tree
;
607 if (focusw
== source_widget
)
608 gtk_widget_grab_focus(sci
);
613 /* Creates a new document and editor, adding a tab in the notebook.
614 * @return The created document */
615 static GeanyDocument
*document_create(const gchar
*utf8_filename
)
619 gint cur_pages
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
623 doc
= document_get_current();
624 /* remove the empty document first */
625 if (doc
!= NULL
&& doc
->file_name
== NULL
&& ! doc
->changed
)
626 /* prevent immediately opening another new doc with
627 * new_document_after_close pref */
631 new_idx
= document_get_new_idx();
632 if (new_idx
== -1) /* expand the array, no free places */
634 doc
= g_new0(GeanyDocument
, 1);
636 new_idx
= documents_array
->len
;
637 g_ptr_array_add(documents_array
, doc
);
640 doc
= documents
[new_idx
];
642 /* initialize default document settings */
643 doc
->priv
= g_new0(GeanyDocumentPrivate
, 1);
644 doc
->priv
->tag_filter
= g_strdup("");
645 doc
->priv
->symbols_group_by_type
= TRUE
;
646 doc
->id
= ++doc_id_counter
;
647 doc
->index
= new_idx
;
648 doc
->file_name
= g_strdup(utf8_filename
);
649 doc
->editor
= editor_create(doc
);
650 #ifndef USE_GIO_FILEMON
651 doc
->priv
->last_check
= time(NULL
);
654 g_datalist_init(&doc
->priv
->data
);
656 sidebar_openfiles_add(doc
); /* sets doc->iter */
658 notebook_new_tab(doc
);
660 /* select document in sidebar */
662 GtkTreeSelection
*sel
;
664 sel
= gtk_tree_view_get_selection(GTK_TREE_VIEW(tv
.tree_openfiles
));
665 gtk_tree_selection_select_iter(sel
, &doc
->priv
->iter
);
668 ui_document_buttons_update();
670 doc
->is_valid
= TRUE
; /* do this last to prevent UI updating with NULL items. */
676 * Closes the given document.
678 * @param doc The document to remove.
680 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
685 gboolean
document_close(GeanyDocument
*doc
)
687 g_return_val_if_fail(doc
, FALSE
);
689 return document_remove_page(document_get_notebook_page(doc
));
693 /* Call document_remove_page() instead, this is only needed for document_create()
694 * to prevent re-opening a new document when the last document is closed (if enabled). */
695 static gboolean
remove_page(guint page_num
)
697 GeanyDocument
*doc
= document_get_from_page(page_num
);
699 g_return_val_if_fail(doc
!= NULL
, FALSE
);
701 /* if we're closing all, document_account_for_unsaved() has been called already, no need to ask again. */
702 if (! main_status
.closing_all
&& doc
->changed
&& ! dialogs_show_unsaved_file(doc
))
705 /* tell any plugins that the document is about to be closed */
706 g_signal_emit_by_name(geany_object
, "document-close", doc
);
708 /* Checking real_path makes it likely the file exists on disk */
709 if (! main_status
.closing_all
&& doc
->real_path
!= NULL
)
710 ui_add_recent_document(doc
);
712 g_datalist_clear(&doc
->priv
->data
);
714 doc
->is_valid
= FALSE
;
717 if (main_status
.quitting
)
719 /* we need to destroy the ScintillaWidget so our handlers on it are
720 * disconnected before we free any data they may use (like the editor).
721 * when not quitting, this is handled by removing the notebook page. */
722 gtk_notebook_remove_page(GTK_NOTEBOOK(main_widgets
.notebook
), page_num
);
726 notebook_remove_page(page_num
);
727 sidebar_remove_document(doc
);
728 navqueue_remove_file(doc
->file_name
);
729 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc
));
731 g_free(doc
->encoding
);
732 g_free(doc
->priv
->saved_encoding
.encoding
);
733 g_free(doc
->priv
->tag_filter
);
734 g_free(doc
->file_name
);
735 g_free(doc
->real_path
);
738 tm_workspace_remove_source_file(doc
->tm_file
);
739 tm_source_file_free(doc
->tm_file
);
742 if (doc
->priv
->tag_tree
)
743 gtk_widget_destroy(doc
->priv
->tag_tree
);
745 editor_destroy(doc
->editor
);
746 doc
->editor
= NULL
; /* needs to be NULL for document_undo_clear() call below */
748 document_stop_file_monitoring(doc
);
750 document_undo_clear(doc
);
754 /* reset document settings to defaults for re-use */
755 memset(doc
, 0, sizeof(GeanyDocument
));
757 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
759 sidebar_update_tag_list(NULL
, FALSE
);
760 ui_set_window_title(NULL
);
761 ui_save_buttons_toggle(FALSE
);
762 ui_update_popup_reundo_items(NULL
);
763 ui_document_buttons_update();
764 build_menu_update(NULL
);
771 * Removes the given notebook tab at @a page_num and clears all related information
772 * in the document list.
774 * @param page_num The notebook page number to remove.
776 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
779 gboolean
document_remove_page(guint page_num
)
781 gboolean done
= remove_page(page_num
);
783 if (done
&& ui_prefs
.new_document_after_close
)
784 document_new_file_if_non_open();
790 /* used to keep a record of the unchanged document state encoding */
791 static void store_saved_encoding(GeanyDocument
*doc
)
793 g_free(doc
->priv
->saved_encoding
.encoding
);
794 doc
->priv
->saved_encoding
.encoding
= g_strdup(doc
->encoding
);
795 doc
->priv
->saved_encoding
.has_bom
= doc
->has_bom
;
799 /* Opens a new empty document only if there are no other documents open */
800 GeanyDocument
*document_new_file_if_non_open(void)
802 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
803 return document_new_file(NULL
, NULL
, NULL
);
810 * Creates a new document.
811 * Line endings in @a text will be converted to the default setting.
812 * Afterwards, the @c "document-new" signal is emitted for plugins.
814 * @param utf8_filename @nullable The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
815 * @param ft @nullable The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
816 * @param text @nullable The initial content of the file (in UTF-8 encoding), or @c NULL.
818 * @return @transfer{none} The new document.
821 GeanyDocument
*document_new_file(const gchar
*utf8_filename
, GeanyFiletype
*ft
, const gchar
*text
)
825 if (utf8_filename
&& g_path_is_absolute(utf8_filename
))
828 tmp
= utils_strdupa(utf8_filename
); /* work around const */
829 utils_tidy_path(tmp
);
832 doc
= document_create(utf8_filename
);
834 g_assert(doc
!= NULL
);
836 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
839 GString
*template = g_string_new(text
);
840 utils_ensure_same_eol_characters(template, file_prefs
.default_eol_character
);
842 sci_set_text(doc
->editor
->sci
, template->str
);
843 g_string_free(template, TRUE
);
846 sci_clear_all(doc
->editor
->sci
);
848 sci_set_eol_mode(doc
->editor
->sci
, file_prefs
.default_eol_character
);
850 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
851 sci_empty_undo_buffer(doc
->editor
->sci
);
853 doc
->encoding
= g_strdup(encodings
[file_prefs
.default_new_encoding
].charset
);
854 /* store the opened encoding for undo/redo */
855 store_saved_encoding(doc
);
857 if (ft
== NULL
&& utf8_filename
!= NULL
) /* guess the filetype from the filename if one is given */
858 ft
= filetypes_detect_from_document(doc
);
860 document_set_filetype(doc
, ft
); /* also re-parses tags */
862 ui_set_window_title(doc
);
863 build_menu_update(doc
);
864 document_set_text_changed(doc
, FALSE
);
865 ui_document_show_hide(doc
); /* update the document menu */
867 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
);
868 /* bring it in front, jump to the start and grab the focus */
869 editor_goto_pos(doc
->editor
, 0, FALSE
);
871 #ifdef USE_GIO_FILEMON
872 monitor_file_setup(doc
);
874 doc
->priv
->mtime
= 0;
877 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
878 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
), doc
->editor
);
880 g_signal_emit_by_name(geany_object
, "document-new", doc
);
882 msgwin_status_add(_("New file \"%s\" opened."),
890 * Opens a document specified by @a locale_filename.
891 * Afterwards, the @c "document-open" signal is emitted for plugins.
893 * @param locale_filename The filename of the document to load, in locale encoding.
894 * @param readonly Whether to open the document in read-only mode.
895 * @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
896 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
898 * @return @transfer{none} @nullable The document opened or @c NULL.
901 GeanyDocument
*document_open_file(const gchar
*locale_filename
, gboolean readonly
,
902 GeanyFiletype
*ft
, const gchar
*forced_enc
)
904 return document_open_file_full(NULL
, locale_filename
, 0, readonly
, ft
, forced_enc
);
910 gchar
*data
; /* null-terminated file data */
911 gsize len
; /* string length of data */
914 time_t mtime
; /* modification time, read by stat::st_mtime */
919 static gboolean
get_mtime(const gchar
*locale_filename
, time_t *time
)
921 GError
*error
= NULL
;
922 const gchar
*err_msg
= NULL
;
924 if (USE_GIO_FILE_OPERATIONS
)
926 GFile
*file
= g_file_new_for_path(locale_filename
);
927 GFileInfo
*info
= g_file_query_info(file
, G_FILE_ATTRIBUTE_TIME_MODIFIED
, G_FILE_QUERY_INFO_NONE
, NULL
, &error
);
933 g_file_info_get_modification_time(info
, &timeval
);
934 g_object_unref(info
);
935 *time
= timeval
.tv_sec
;
938 err_msg
= error
->message
;
940 g_object_unref(file
);
946 if (g_stat(locale_filename
, &st
) == 0)
949 err_msg
= g_strerror(errno
);
954 gchar
*utf8_filename
= utils_get_utf8_from_locale(locale_filename
);
956 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"),
957 utf8_filename
, err_msg
);
958 g_free(utf8_filename
);
964 return err_msg
== NULL
;
968 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
969 static gboolean
load_text_file(const gchar
*locale_filename
, const gchar
*display_filename
,
970 FileData
*filedata
, const gchar
*forced_enc
)
974 filedata
->data
= NULL
;
976 filedata
->enc
= NULL
;
977 filedata
->bom
= FALSE
;
978 filedata
->readonly
= FALSE
;
980 if (!get_mtime(locale_filename
, &filedata
->mtime
))
983 if (USE_GIO_FILE_OPERATIONS
)
985 GFile
*file
= g_file_new_for_path(locale_filename
);
987 g_file_load_contents(file
, NULL
, &filedata
->data
, &filedata
->len
, NULL
, &err
);
988 g_object_unref(file
);
991 g_file_get_contents(locale_filename
, &filedata
->data
, &filedata
->len
, &err
);
995 ui_set_statusbar(TRUE
, "%s", err
->message
);
1000 if (! encodings_convert_to_utf8_auto(&filedata
->data
, &filedata
->len
, forced_enc
,
1001 &filedata
->enc
, &filedata
->bom
, &filedata
->readonly
))
1005 ui_set_statusbar(TRUE
, _("The file \"%s\" is not valid %s."),
1006 display_filename
, forced_enc
);
1010 ui_set_statusbar(TRUE
,
1011 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
1014 g_free(filedata
->data
);
1018 if (filedata
->readonly
)
1020 const gchar
*warn_msg
= _(
1021 "The file \"%s\" could not be opened properly and has been truncated. " \
1022 "This can occur if the file contains a NULL byte. " \
1023 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
1025 if (main_status
.main_window_realized
)
1026 dialogs_show_msgbox(GTK_MESSAGE_WARNING
, warn_msg
, display_filename
);
1028 ui_set_statusbar(TRUE
, warn_msg
, display_filename
);
1035 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
1036 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
1037 * if cl_options.goto_column is set.
1039 * returns the new position which may have changed */
1040 static gint
set_cursor_position(GeanyEditor
*editor
, gint pos
)
1042 if (cl_options
.goto_line
>= 0)
1043 { /* goto line which was specified on command line and then undefine the line */
1044 sci_goto_line(editor
->sci
, cl_options
.goto_line
- 1, TRUE
);
1045 editor
->scroll_percent
= 0.5F
;
1046 cl_options
.goto_line
= -1;
1050 sci_set_current_position(editor
->sci
, pos
, FALSE
);
1051 editor
->scroll_percent
= 0.5F
;
1054 if (cl_options
.goto_column
>= 0)
1055 { /* goto column which was specified on command line and then undefine the column */
1057 gint new_pos
= sci_get_current_position(editor
->sci
) + cl_options
.goto_column
;
1058 sci_set_current_position(editor
->sci
, new_pos
, FALSE
);
1059 editor
->scroll_percent
= 0.5F
;
1060 cl_options
.goto_column
= -1;
1063 return sci_get_current_position(editor
->sci
);
1067 /* Count lines that start with some hard tabs then a soft tab. */
1068 static gboolean
detect_tabs_and_spaces(GeanyEditor
*editor
)
1070 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1071 ScintillaObject
*sci
= editor
->sci
;
1073 struct Sci_TextToFind ttf
;
1074 gchar
*soft_tab
= g_strnfill((gsize
)iprefs
->width
, ' ');
1075 gchar
*regex
= g_strconcat("^\t+", soft_tab
, "[^ ]", NULL
);
1080 ttf
.chrg
.cpMax
= sci_get_length(sci
);
1081 ttf
.lpstrText
= regex
;
1086 pos
= sci_find_text(sci
, SCFIND_REGEXP
, &ttf
);
1088 break; /* no more matches */
1090 ttf
.chrg
.cpMin
= ttf
.chrgText
.cpMax
+ 1; /* search after this match */
1093 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
1094 return count
> sci_get_line_count(sci
) * 0.02;
1098 /* Detect the indent type based on counting the leading indent characters for each line.
1099 * Returns whether detection succeeded, and the detected type in *type_ upon success */
1100 gboolean
document_detect_indent_type(GeanyDocument
*doc
, GeanyIndentType
*type_
)
1102 GeanyEditor
*editor
= doc
->editor
;
1103 ScintillaObject
*sci
= editor
->sci
;
1104 gint line
, line_count
;
1105 gsize tabs
= 0, spaces
= 0;
1107 if (detect_tabs_and_spaces(editor
))
1109 *type_
= GEANY_INDENT_TYPE_BOTH
;
1113 line_count
= sci_get_line_count(sci
);
1114 for (line
= 0; line
< line_count
; line
++)
1116 gint pos
= sci_get_position_from_line(sci
, line
);
1119 /* most code will have indent total <= 24, otherwise it's more likely to be
1120 * alignment than indentation */
1121 if (sci_get_line_indentation(sci
, line
) > 24)
1124 c
= sci_get_char_at(sci
, pos
);
1127 /* check for at least 2 spaces */
1128 else if (c
== ' ' && sci_get_char_at(sci
, pos
+ 1) == ' ')
1131 if (spaces
== 0 && tabs
== 0)
1134 /* the factors may need to be tweaked */
1135 if (spaces
> tabs
* 4)
1136 *type_
= GEANY_INDENT_TYPE_SPACES
;
1137 else if (tabs
> spaces
* 4)
1138 *type_
= GEANY_INDENT_TYPE_TABS
;
1140 *type_
= GEANY_INDENT_TYPE_BOTH
;
1146 /* Detect the indent width based on counting the leading indent characters for each line.
1147 * Returns whether detection succeeded, and the detected width in *width_ upon success */
1148 static gboolean
detect_indent_width(GeanyEditor
*editor
, GeanyIndentType type
, gint
*width_
)
1150 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
1151 ScintillaObject
*sci
= editor
->sci
;
1152 gint line
, line_count
;
1153 gint widths
[7] = { 0 }; /* width can be from 2 to 8 */
1154 gint count
, width
, i
;
1156 /* can't easily detect the supposed width of a tab, guess the default is OK */
1157 if (type
== GEANY_INDENT_TYPE_TABS
)
1160 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
1161 sci_set_tab_width(sci
, 8);
1163 line_count
= sci_get_line_count(sci
);
1164 for (line
= 0; line
< line_count
; line
++)
1166 gint pos
= sci_get_line_indent_position(sci
, line
);
1168 /* We probably don't have style info yet, because we're generally called just after
1169 * the document got created, so we can't use highlighting_is_code_style().
1170 * That's not good, but the assumption below that concerning lines start with an
1171 * asterisk (common continuation character for C/C++/Java/...) should do the trick
1172 * without removing too much legitimate lines. */
1173 if (sci_get_char_at(sci
, pos
) == '*')
1176 width
= sci_get_line_indentation(sci
, line
);
1177 /* most code will have indent total <= 24, otherwise it's more likely to be
1178 * alignment than indentation */
1181 /* < 2 is no indentation */
1185 for (i
= G_N_ELEMENTS(widths
) - 1; i
>= 0; i
--)
1187 if ((width
% (i
+ 2)) == 0)
1192 width
= iprefs
->width
;
1193 for (i
= G_N_ELEMENTS(widths
) - 1; i
>= 0; i
--)
1195 /* give large indents higher weight not to be fooled by spurious indents */
1196 if (widths
[i
] >= count
* 1.5)
1211 /* same as detect_indent_width() but uses editor's indent type */
1212 gboolean
document_detect_indent_width(GeanyDocument
*doc
, gint
*width_
)
1214 return detect_indent_width(doc
->editor
, doc
->editor
->indent_type
, width_
);
1218 void document_apply_indent_settings(GeanyDocument
*doc
)
1220 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
1221 GeanyIndentType type
= iprefs
->type
;
1222 gint width
= iprefs
->width
;
1224 if (iprefs
->detect_type
&& document_detect_indent_type(doc
, &type
))
1226 if (type
!= iprefs
->type
)
1228 const gchar
*name
= NULL
;
1232 case GEANY_INDENT_TYPE_SPACES
:
1235 case GEANY_INDENT_TYPE_TABS
:
1238 case GEANY_INDENT_TYPE_BOTH
:
1239 name
= _("Tabs and Spaces");
1242 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1243 * and Spaces), the second one is the filename */
1244 ui_set_statusbar(TRUE
, _("Setting %s indentation mode for %s."), name
,
1248 else if (doc
->file_type
->indent_type
> -1)
1249 type
= doc
->file_type
->indent_type
;
1251 if (iprefs
->detect_width
&& detect_indent_width(doc
->editor
, type
, &width
))
1253 if (width
!= iprefs
->width
)
1255 ui_set_statusbar(TRUE
, _("Setting indentation width to %d for %s."), width
,
1259 else if (doc
->file_type
->indent_width
> -1)
1260 width
= doc
->file_type
->indent_width
;
1262 editor_set_indent(doc
->editor
, type
, width
);
1266 void document_show_tab(GeanyDocument
*doc
)
1270 g_source_remove(show_tab_idle
);
1274 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets
.notebook
),
1275 document_get_notebook_page(doc
));
1277 /* finally, let the editor widget grab the focus so you can start coding
1279 document_try_focus(doc
, NULL
);
1283 static gboolean
show_tab_cb(gpointer data
)
1285 GeanyDocument
*doc
= (GeanyDocument
*) data
;
1288 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
1290 document_show_tab(doc
);
1292 return G_SOURCE_REMOVE
;
1296 void document_show_tab_idle(GeanyDocument
*doc
)
1299 g_source_remove(show_tab_idle
);
1301 show_tab_idle
= g_idle_add(show_tab_cb
, doc
);
1305 /* To open a new file, set doc to NULL; filename should be locale encoded.
1306 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1307 * pos is the cursor position, which can be overridden by --line and --column.
1308 * forced_enc can be NULL to detect the file encoding.
1309 * Returns: doc of the opened file or NULL if an error occurred. */
1310 GeanyDocument
*document_open_file_full(GeanyDocument
*doc
, const gchar
*filename
, gint pos
,
1311 gboolean readonly
, GeanyFiletype
*ft
, const gchar
*forced_enc
)
1314 gboolean reload
= (doc
== NULL
) ? FALSE
: TRUE
;
1315 gchar
*utf8_filename
= NULL
;
1316 gchar
*display_filename
= NULL
;
1317 gchar
*locale_filename
= NULL
;
1318 GeanyFiletype
*use_ft
;
1320 UndoReloadData
*undo_reload_data
;
1321 gboolean add_undo_reload_action
;
1323 g_return_val_if_fail(doc
== NULL
|| doc
->is_valid
, NULL
);
1327 utf8_filename
= g_strdup(doc
->file_name
);
1328 locale_filename
= utils_get_locale_from_utf8(utf8_filename
);
1332 /* filename must not be NULL when opening a file */
1333 g_return_val_if_fail(filename
, NULL
);
1336 /* if filename is a shortcut, try to resolve it */
1337 locale_filename
= win32_get_shortcut_target(filename
);
1339 locale_filename
= g_strdup(filename
);
1341 /* remove relative junk */
1342 utils_tidy_path(locale_filename
);
1344 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1345 utf8_filename
= utils_get_utf8_from_locale(locale_filename
);
1347 /* if file is already open, switch to it and go */
1348 doc
= document_find_by_filename(utf8_filename
);
1351 ui_add_recent_document(doc
); /* either add or reorder recent item */
1352 document_check_disk_status(doc
, TRUE
); /* force a file changed check */
1355 if (reload
|| doc
== NULL
)
1356 { /* doc possibly changed */
1357 display_filename
= utils_str_middle_truncate(utf8_filename
, 100);
1359 if (! load_text_file(locale_filename
, display_filename
, &filedata
, forced_enc
))
1361 g_free(display_filename
);
1362 g_free(utf8_filename
);
1363 g_free(locale_filename
);
1369 doc
= document_create(utf8_filename
);
1370 g_return_val_if_fail(doc
!= NULL
, NULL
); /* really should not happen */
1372 /* file exists on disk, set real_path */
1373 SETPTR(doc
->real_path
, utils_get_real_path(locale_filename
));
1375 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1376 monitor_file_setup(doc
);
1379 if (! reload
|| ! file_prefs
.keep_edit_history_on_reload
)
1381 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
1382 sci_empty_undo_buffer(doc
->editor
->sci
);
1383 undo_reload_data
= NULL
;
1387 undo_reload_data
= (UndoReloadData
*) g_malloc(sizeof(UndoReloadData
));
1389 /* We will be adding a UNDO_RELOAD action to the undo stack that undoes
1390 * this reload. To do that, we keep collecting undo actions during
1391 * reloading, and at the end add an UNDO_RELOAD action that performs
1392 * all these actions in bulk. To keep track of how many undo actions
1393 * were added during this time, we compare the current undo-stack height
1394 * with its height at the end of the process. Note that g_trash_stack_height()
1395 * is O(N), which is a little ugly, but this seems like the most maintainable
1397 undo_reload_data
->actions_count
= g_trash_stack_height(&doc
->priv
->undo_actions
);
1399 /* We use add_undo_reload_action to track any changes to the document that
1400 * require adding an undo action to revert the reload, but that do not
1401 * generate an undo action themselves. */
1402 add_undo_reload_action
= FALSE
;
1405 /* add the text to the ScintillaObject */
1406 sci_set_readonly(doc
->editor
->sci
, FALSE
); /* to allow replacing text */
1407 sci_set_text(doc
->editor
->sci
, filedata
.data
); /* NULL terminated data */
1408 queue_colourise(doc
); /* Ensure the document gets colourised. */
1410 /* detect & set line endings */
1411 editor_mode
= utils_get_line_endings(filedata
.data
, filedata
.len
);
1412 if (undo_reload_data
)
1414 undo_reload_data
->eol_mode
= editor_get_eol_char_mode(doc
->editor
);
1415 /* Force adding an undo-reload action if the EOL mode changed. */
1416 if (editor_mode
!= undo_reload_data
->eol_mode
)
1417 add_undo_reload_action
= TRUE
;
1419 sci_set_eol_mode(doc
->editor
->sci
, editor_mode
);
1420 g_free(filedata
.data
);
1422 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
1424 /* If reloading and the current and new encodings or BOM states differ,
1425 * add appropriate undo actions. */
1426 if (undo_reload_data
)
1428 if (! utils_str_equal(doc
->encoding
, filedata
.enc
))
1429 document_undo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
1430 if (doc
->has_bom
!= filedata
.bom
)
1431 document_undo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
1434 doc
->priv
->mtime
= filedata
.mtime
; /* get the modification time from file and keep it */
1435 g_free(doc
->encoding
); /* if reloading, free old encoding */
1436 doc
->encoding
= filedata
.enc
;
1437 doc
->has_bom
= filedata
.bom
;
1438 store_saved_encoding(doc
); /* store the opened encoding for undo/redo */
1440 doc
->readonly
= readonly
|| filedata
.readonly
;
1441 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
1442 doc
->priv
->protected = 0;
1444 /* update line number margin width */
1445 doc
->priv
->line_count
= sci_get_line_count(doc
->editor
->sci
);
1446 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
);
1451 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1452 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
),
1455 use_ft
= (ft
!= NULL
) ? ft
: filetypes_detect_from_document(doc
);
1459 if (undo_reload_data
)
1461 /* Calculate the number of undo actions that are part of the reloading
1462 * process, and add the UNDO_RELOAD action. */
1463 undo_reload_data
->actions_count
=
1464 g_trash_stack_height(&doc
->priv
->undo_actions
) - undo_reload_data
->actions_count
;
1466 /* We only add an undo-reload action if the document has actually changed.
1467 * At the time of writing, this condition is moot because sci_set_text
1468 * generates an undo action even when the text hasn't really changed, so
1469 * actions_count is always greater than zero. In the future this might change.
1470 * It's arguable whether we should add an undo-reload action unconditionally,
1471 * especially since it's possible (if unlikely) that there had only
1472 * been "invisible" changes to the document, such as changes in encoding and
1473 * EOL mode, but for the time being that's how we roll. */
1474 if (undo_reload_data
->actions_count
> 0 || add_undo_reload_action
)
1475 document_undo_add(doc
, UNDO_RELOAD
, undo_reload_data
);
1477 g_free(undo_reload_data
);
1479 /* We didn't save the document per-se, but its contents are now
1480 * synchronized with the file on disk, hence set a save point here.
1481 * We need to do this in this case only, because we don't clear
1482 * Scintilla's undo stack. */
1483 sci_set_savepoint(doc
->editor
->sci
);
1486 document_undo_clear(doc
);
1490 /* update taglist, typedef keywords and build menu if necessary */
1491 document_set_filetype(doc
, use_ft
);
1493 /* set indentation settings after setting the filetype */
1495 editor_set_indent(doc
->editor
, doc
->editor
->indent_type
, doc
->editor
->indent_width
); /* resetup sci */
1497 document_apply_indent_settings(doc
);
1499 document_set_text_changed(doc
, FALSE
); /* also updates tab state */
1500 ui_document_show_hide(doc
); /* update the document menu */
1502 /* finally add current file to recent files menu, but not the files from the last session */
1503 if (! main_status
.opening_session_files
)
1504 ui_add_recent_document(doc
);
1508 g_signal_emit_by_name(geany_object
, "document-reload", doc
);
1509 ui_set_statusbar(TRUE
, _("File %s reloaded."), display_filename
);
1513 g_signal_emit_by_name(geany_object
, "document-open", doc
);
1514 /* For translators: this is the status window message for opening a file. %d is the number
1515 * of the newly opened file, %s indicates whether the file is opened read-only
1516 * (it is replaced with the string ", read-only"). */
1517 msgwin_status_add(_("File %s opened (%d%s)."),
1518 display_filename
, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)),
1519 (readonly
) ? _(", read-only") : "");
1523 g_free(display_filename
);
1524 g_free(utf8_filename
);
1525 g_free(locale_filename
);
1527 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1528 pos
= set_cursor_position(doc
->editor
, pos
);
1529 /* now bring the file in front */
1530 editor_goto_pos(doc
->editor
, pos
, FALSE
);
1536 /* Takes a new line separated list of filename URIs and opens each file.
1537 * length is the length of the string */
1538 void document_open_file_list(const gchar
*data
, gsize length
)
1543 g_return_if_fail(data
!= NULL
);
1545 list
= g_strsplit(data
, utils_get_eol_char(utils_get_line_endings(data
, length
)), 0);
1547 /* stop at the end or first empty item, because last item is empty but not null */
1548 for (i
= 0; list
[i
] != NULL
&& list
[i
][0] != '\0'; i
++)
1550 gchar
*filename
= utils_get_path_from_uri(list
[i
]);
1552 if (filename
== NULL
)
1554 document_open_file(filename
, FALSE
, NULL
, NULL
);
1563 * Opens each file in the list @a filenames.
1564 * Internally, document_open_file() is called for every list item.
1566 * @param filenames @elementtype{filename} A list of filenames to load, in locale encoding.
1567 * @param readonly Whether to open the document in read-only mode.
1568 * @param ft @nullable The filetype for the document or @c NULL to auto-detect the filetype.
1569 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1572 void document_open_files(const GSList
*filenames
, gboolean readonly
, GeanyFiletype
*ft
,
1573 const gchar
*forced_enc
)
1577 for (item
= filenames
; item
!= NULL
; item
= g_slist_next(item
))
1579 document_open_file(item
->data
, readonly
, ft
, forced_enc
);
1584 static void on_keep_edit_history_on_reload_response(GtkWidget
*bar
, gint response_id
, GeanyDocument
*doc
)
1586 if (response_id
== GTK_RESPONSE_NO
)
1588 file_prefs
.keep_edit_history_on_reload
= FALSE
;
1589 document_reload_force(doc
, doc
->encoding
);
1591 else if (response_id
== GTK_RESPONSE_CANCEL
)
1593 /* this condition cannot be reached via info bar buttons, but by our code
1594 * to replace this bar with a higher priority one */
1595 file_prefs
.show_keep_edit_history_on_reload_msg
= TRUE
;
1597 doc
->priv
->info_bars
[MSG_TYPE_POST_RELOAD
] = NULL
;
1598 gtk_widget_destroy(bar
);
1603 * Reloads the document with the specified file encoding.
1604 * @a forced_enc or @c NULL to auto-detect the file encoding.
1606 * @param doc The document to reload.
1607 * @param forced_enc @nullable The file encoding to use or @c NULL to auto-detect the file encoding.
1609 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1612 gboolean
document_reload_force(GeanyDocument
*doc
, const gchar
*forced_enc
)
1615 GeanyDocument
*new_doc
;
1618 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1620 /* Cancel resave bar if still open from previous file deletion */
1621 if (doc
->priv
->info_bars
[MSG_TYPE_RESAVE
] != NULL
)
1622 gtk_info_bar_response(GTK_INFO_BAR(doc
->priv
->info_bars
[MSG_TYPE_RESAVE
]), GTK_RESPONSE_CANCEL
);
1624 /* Use cancel because the response handler would call this recursively */
1625 if (doc
->priv
->info_bars
[MSG_TYPE_RELOAD
] != NULL
)
1626 gtk_info_bar_response(GTK_INFO_BAR(doc
->priv
->info_bars
[MSG_TYPE_RELOAD
]), GTK_RESPONSE_CANCEL
);
1628 /* try to set the cursor to the position before reloading */
1629 pos
= sci_get_current_position(doc
->editor
->sci
);
1630 new_doc
= document_open_file_full(doc
, NULL
, pos
, doc
->readonly
, doc
->file_type
, forced_enc
);
1632 if (file_prefs
.keep_edit_history_on_reload
&& file_prefs
.show_keep_edit_history_on_reload_msg
)
1634 bar
= document_show_message(doc
, GTK_MESSAGE_INFO
,
1635 on_keep_edit_history_on_reload_response
,
1636 GTK_STOCK_OK
, GTK_RESPONSE_ACCEPT
,
1637 _("Discard history"), GTK_RESPONSE_NO
,
1638 NULL
, 0, _("The buffer's previous state is stored in the history and "
1639 "undoing restores it. You can disable this by discarding the history upon "
1640 "reload. This message will not be displayed again but "
1641 "your choice can be changed in the various preferences."),
1642 _("The file has been reloaded."));
1643 doc
->priv
->info_bars
[MSG_TYPE_POST_RELOAD
] = bar
;
1644 file_prefs
.show_keep_edit_history_on_reload_msg
= FALSE
;
1647 return (new_doc
!= NULL
);
1651 /* also used for reloading when forced_enc is NULL */
1652 gboolean
document_reload_prompt(GeanyDocument
*doc
, const gchar
*forced_enc
)
1655 gboolean prompt
, result
= FALSE
;
1657 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1659 /* No need to reload "untitled" (non-file-backed) documents */
1660 if (doc
->file_name
== NULL
)
1663 if (forced_enc
== NULL
)
1664 forced_enc
= doc
->encoding
;
1666 base_name
= g_path_get_basename(doc
->file_name
);
1667 /* don't prompt if edit history is maintained, or if file hasn't been edited at all */
1668 prompt
= !file_prefs
.keep_edit_history_on_reload
&&
1669 (doc
->changed
|| (document_can_undo(doc
) || document_can_redo(doc
)));
1671 if (!prompt
|| dialogs_show_question_full(NULL
, _("_Reload"), GTK_STOCK_CANCEL
,
1672 doc
->changed
? _("Any unsaved changes will be lost.") :
1673 _("Undo history will be lost."),
1674 _("Are you sure you want to reload '%s'?"), base_name
))
1676 result
= document_reload_force(doc
, forced_enc
);
1677 if (forced_enc
!= NULL
)
1678 ui_update_statusbar(doc
, -1);
1685 static void document_update_timestamp(GeanyDocument
*doc
, const gchar
*locale_filename
)
1687 #ifndef USE_GIO_FILEMON
1688 g_return_if_fail(doc
!= NULL
);
1690 get_mtime(locale_filename
, &doc
->priv
->mtime
); /* get the modification time from file and keep it */
1695 /* Sets line and column to the given position byte_pos in the document.
1696 * byte_pos is the position counted in bytes, not characters */
1697 static void get_line_column_from_pos(GeanyDocument
*doc
, guint byte_pos
, gint
*line
, gint
*column
)
1702 /* for some reason we can use byte count instead of character count here */
1703 *line
= sci_get_line_from_position(doc
->editor
->sci
, byte_pos
);
1704 line_start
= sci_get_position_from_line(doc
->editor
->sci
, *line
);
1705 /* get the column in the line */
1706 *column
= byte_pos
- line_start
;
1708 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1709 * skip one byte(i++) and decrease the column number which is based on byte count */
1710 for (i
= line_start
; i
< (line_start
+ *column
); i
++)
1712 if (sci_get_char_at(doc
->editor
->sci
, i
) < 0)
1721 static void replace_header_filename(GeanyDocument
*doc
)
1725 struct Sci_TextToFind ttf
;
1727 g_return_if_fail(doc
!= NULL
);
1728 g_return_if_fail(doc
->file_type
!= NULL
);
1730 filebase
= g_regex_escape_string(GEANY_STRING_UNTITLED
, -1);
1731 if (doc
->file_type
->extension
)
1732 SETPTR(filebase
, g_strconcat("\\b", filebase
, "\\.\\w+", NULL
));
1734 SETPTR(filebase
, g_strconcat("\\b", filebase
, "\\b", NULL
));
1736 filename
= g_path_get_basename(doc
->file_name
);
1738 /* only search the first 3 lines */
1740 ttf
.chrg
.cpMax
= sci_get_position_from_line(doc
->editor
->sci
, 4);
1741 ttf
.lpstrText
= filebase
;
1743 if (search_find_text(doc
->editor
->sci
, GEANY_FIND_MATCHCASE
| GEANY_FIND_REGEXP
, &ttf
, NULL
) != -1)
1745 sci_set_target_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1746 sci_set_target_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1747 sci_replace_target(doc
->editor
->sci
, filename
, FALSE
);
1755 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1756 * you still have to call @ref document_save_file_as() to change the @a doc object.
1757 * It also stops monitoring for file changes to prevent receiving too many file change events
1758 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1760 * @param doc The current document which should be renamed.
1761 * @param new_filename The new filename in UTF-8 encoding.
1766 void document_rename_file(GeanyDocument
*doc
, const gchar
*new_filename
)
1768 gchar
*old_locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1769 gchar
*new_locale_filename
= utils_get_locale_from_utf8(new_filename
);
1772 /* stop file monitoring to avoid getting events for deleting/creating files,
1773 * it's re-setup in document_save_file_as() */
1774 document_stop_file_monitoring(doc
);
1776 result
= g_rename(old_locale_filename
, new_locale_filename
);
1779 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
,
1780 _("Error renaming file."), g_strerror(errno
));
1782 g_free(old_locale_filename
);
1783 g_free(new_locale_filename
);
1787 static void protect_document(GeanyDocument
*doc
)
1789 /* do not call queue_colourise because to we want to keep the text-changed indication! */
1790 if (!doc
->priv
->protected++)
1791 sci_set_readonly(doc
->editor
->sci
, TRUE
);
1793 ui_update_tab_status(doc
);
1797 static void unprotect_document(GeanyDocument
*doc
)
1799 g_return_if_fail(doc
->priv
->protected > 0);
1801 if (!--doc
->priv
->protected && doc
->readonly
== FALSE
)
1802 sci_set_readonly(doc
->editor
->sci
, FALSE
);
1804 ui_update_tab_status(doc
);
1808 /* Return TRUE if the document doesn't have a full filename set.
1809 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1810 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1812 gboolean
document_need_save_as(GeanyDocument
*doc
)
1814 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1816 return (doc
->file_name
== NULL
|| !g_path_is_absolute(doc
->file_name
));
1821 * Saves the document, detecting the filetype.
1823 * @param doc The document for the file to save.
1824 * @param utf8_fname @nullable The new name for the document, in UTF-8, or @c NULL.
1825 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1827 * @see document_save_file().
1832 gboolean
document_save_file_as(GeanyDocument
*doc
, const gchar
*utf8_fname
)
1837 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1839 new_file
= document_need_save_as(doc
) || (utf8_fname
!= NULL
&& strcmp(doc
->file_name
, utf8_fname
) != 0);
1840 if (utf8_fname
!= NULL
)
1841 SETPTR(doc
->file_name
, g_strdup(utf8_fname
));
1843 /* reset real path, it's retrieved again in document_save() */
1844 SETPTR(doc
->real_path
, NULL
);
1846 /* detect filetype */
1847 if (doc
->file_type
->id
== GEANY_FILETYPES_NONE
)
1849 GeanyFiletype
*ft
= filetypes_detect_from_document(doc
);
1851 document_set_filetype(doc
, ft
);
1852 if (document_get_current() == doc
)
1854 ignore_callback
= TRUE
;
1855 filetypes_select_radio_item(doc
->file_type
);
1856 ignore_callback
= FALSE
;
1862 // assume user wants to throw away read-only setting
1863 sci_set_readonly(doc
->editor
->sci
, FALSE
);
1864 doc
->readonly
= FALSE
;
1865 if (doc
->priv
->protected > 0)
1866 unprotect_document(doc
);
1869 replace_header_filename(doc
);
1871 ret
= document_save_file(doc
, TRUE
);
1873 /* file monitoring support, add file monitoring after the file has been saved
1874 * to ignore any earlier events */
1875 monitor_file_setup(doc
);
1876 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1881 static gsize
save_convert_to_encoding(GeanyDocument
*doc
, gchar
**data
, gsize
*len
)
1883 GError
*conv_error
= NULL
;
1884 gchar
* conv_file_contents
= NULL
;
1888 g_return_val_if_fail(data
!= NULL
&& *data
!= NULL
, FALSE
);
1889 g_return_val_if_fail(len
!= NULL
, FALSE
);
1891 /* try to convert it from UTF-8 to original encoding */
1892 conv_file_contents
= g_convert(*data
, *len
- 1, doc
->encoding
, "UTF-8",
1893 &bytes_read
, &conv_len
, &conv_error
);
1895 if (conv_error
!= NULL
)
1897 gchar
*text
= g_strdup_printf(
1898 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1902 if (conv_error
->code
== G_CONVERT_ERROR_ILLEGAL_SEQUENCE
)
1907 /* don't read over the doc length */
1908 gint max_len
= MIN((gint
)bytes_read
+ 6, (gint
)*len
- 1);
1909 gchar context
[7]; /* read 6 bytes from Sci + '\0' */
1910 sci_get_text_range(doc
->editor
->sci
, bytes_read
, max_len
, context
);
1912 /* take only one valid Unicode character from the context and discard the leftover */
1913 unic
= g_utf8_get_char_validated(context
, -1);
1914 context_len
= g_unichar_to_utf8(unic
, context
);
1915 context
[context_len
] = '\0';
1916 get_line_column_from_pos(doc
, bytes_read
, &line
, &column
);
1918 error_text
= g_strdup_printf(
1919 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1920 conv_error
->message
, context
, line
+ 1, column
);
1923 error_text
= g_strdup_printf(_("Error message: %s."), conv_error
->message
);
1925 geany_debug("encoding error: %s", conv_error
->message
);
1926 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, text
, error_text
);
1927 g_error_free(conv_error
);
1935 *data
= conv_file_contents
;
1942 static gchar
*write_data_to_disk(const gchar
*locale_filename
,
1943 const gchar
*data
, gsize len
)
1945 GError
*error
= NULL
;
1947 if (file_prefs
.use_safe_file_saving
)
1949 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1950 * This is the only option that handles disk space exhaustion. */
1951 if (g_file_set_contents(locale_filename
, data
, len
, &error
))
1952 geany_debug("Wrote %s with g_file_set_contents().", locale_filename
);
1954 else if (USE_GIO_FILE_OPERATIONS
)
1958 /* Use GIO API to save file (GVFS-safe)
1959 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1960 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1961 fp
= g_file_new_for_path(locale_filename
);
1962 g_file_replace_contents(fp
, data
, len
, NULL
, file_prefs
.gio_unsafe_save_backup
,
1963 G_FILE_CREATE_NONE
, NULL
, NULL
, &error
);
1970 gchar
*display_name
= g_filename_display_name(locale_filename
);
1972 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1973 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1975 fp
= g_fopen(locale_filename
, "wb");
1982 g_file_error_from_errno(save_errno
),
1983 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1985 g_strerror(save_errno
));
1989 gsize bytes_written
;
1992 bytes_written
= fwrite(data
, sizeof(gchar
), len
, fp
);
1994 if (len
!= bytes_written
)
2000 g_file_error_from_errno(save_errno
),
2001 _("Failed to write file '%s': fwrite() failed: %s"),
2003 g_strerror(save_errno
));
2007 /* preserve the fwrite() error if any */
2008 if (fclose(fp
) != 0 && error
== NULL
)
2014 g_file_error_from_errno(save_errno
),
2015 _("Failed to close file '%s': fclose() failed: %s"),
2017 g_strerror(save_errno
));
2021 g_free(display_name
);
2025 gchar
*msg
= g_strdup(error
->message
);
2026 g_error_free(error
);
2027 /* geany will warn about file truncation for unsafe saving below */
2034 static gchar
*save_doc(GeanyDocument
*doc
, const gchar
*locale_filename
,
2035 const gchar
*data
, gsize len
)
2039 g_return_val_if_fail(doc
!= NULL
, g_strdup(g_strerror(EINVAL
)));
2040 g_return_val_if_fail(data
!= NULL
, g_strdup(g_strerror(EINVAL
)));
2042 err
= write_data_to_disk(locale_filename
, data
, len
);
2046 /* now the file is on disk, set real_path */
2047 if (doc
->real_path
== NULL
)
2049 doc
->real_path
= utils_get_real_path(locale_filename
);
2050 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
2051 monitor_file_setup(doc
);
2052 ui_add_recent_document(doc
);
2058 static gboolean
save_file_handle_infobars(GeanyDocument
*doc
, gboolean force
)
2060 GtkWidget
*bar
= NULL
;
2062 document_show_tab(doc
);
2064 if (doc
->priv
->info_bars
[MSG_TYPE_RELOAD
])
2066 if (!dialogs_show_question_full(NULL
, _("_Overwrite"), GTK_STOCK_CANCEL
,
2068 _("The file '%s' on the disk is more recent than the current buffer."),
2071 bar
= doc
->priv
->info_bars
[MSG_TYPE_RELOAD
];
2073 else if (doc
->priv
->info_bars
[MSG_TYPE_RESAVE
])
2075 if (!dialogs_show_question_full(NULL
, GTK_STOCK_SAVE
, GTK_STOCK_CANCEL
,
2076 _("Try to resave the file?"),
2077 _("File \"%s\" was not found on disk!"),
2080 bar
= doc
->priv
->info_bars
[MSG_TYPE_RESAVE
];
2084 g_assert_not_reached();
2087 gtk_info_bar_response(GTK_INFO_BAR(bar
), RESPONSE_DOCUMENT_SAVE
);
2093 * Saves the document.
2094 * Also shows the Save As dialog if necessary.
2095 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
2097 * Saving may include replacing tabs with spaces,
2098 * stripping trailing spaces and adding a final new line at the end of the file, depending
2099 * on user preferences. Then the @c "document-before-save" signal is emitted,
2100 * allowing plugins to modify the document before it is saved, and data is
2101 * actually written to disk.
2103 * On successful saving:
2104 * - GeanyDocument::real_path is set.
2105 * - The filetype is set again or auto-detected if it wasn't set yet.
2106 * - The @c "document-save" signal is emitted for plugins.
2108 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
2109 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
2110 * added in Geany 1.22.
2112 * @param doc The document to save.
2113 * @param force Whether to save the file even if it is not modified.
2115 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
2118 gboolean
document_save_file(GeanyDocument
*doc
, gboolean force
)
2123 gchar
*locale_filename
;
2124 const GeanyFilePrefs
*fp
;
2126 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2128 if (document_need_save_as(doc
))
2130 /* ensure doc is the current tab before showing the dialog */
2131 document_show_tab(doc
);
2132 return dialogs_show_save_as();
2135 if (!force
&& !doc
->changed
)
2139 ui_set_statusbar(TRUE
,
2140 _("Cannot save read-only document '%s'!"), DOC_FILENAME(doc
));
2143 document_check_disk_status(doc
, TRUE
);
2144 if (doc
->priv
->protected)
2145 return save_file_handle_infobars(doc
, force
);
2147 fp
= project_get_file_prefs();
2148 /* replaces tabs with spaces but only if the current file is not a Makefile */
2149 if (fp
->replace_tabs
&& doc
->file_type
->id
!= GEANY_FILETYPES_MAKE
)
2150 editor_replace_tabs(doc
->editor
, TRUE
);
2151 /* strip trailing spaces */
2152 if (fp
->strip_trailing_spaces
)
2153 editor_strip_trailing_spaces(doc
->editor
, TRUE
);
2154 /* ensure the file has a newline at the end */
2155 if (fp
->final_new_line
)
2156 editor_ensure_final_newline(doc
->editor
);
2157 /* ensure newlines are consistent */
2158 if (fp
->ensure_convert_new_lines
)
2159 sci_convert_eols(doc
->editor
->sci
, sci_get_eol_mode(doc
->editor
->sci
));
2161 /* notify plugins which may wish to modify the document before it's saved */
2162 g_signal_emit_by_name(geany_object
, "document-before-save", doc
);
2164 len
= sci_get_length(doc
->editor
->sci
) + 1;
2165 if (doc
->has_bom
&& encodings_is_unicode_charset(doc
->encoding
))
2166 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
2167 * encoding, it will be converted to doc->encoding below and this conversion
2168 * also changes the BOM */
2169 data
= (gchar
*) g_malloc(len
+ 3); /* 3 chars for BOM */
2170 data
[0] = (gchar
) 0xef;
2171 data
[1] = (gchar
) 0xbb;
2172 data
[2] = (gchar
) 0xbf;
2173 sci_get_text(doc
->editor
->sci
, len
, data
+ 3);
2178 data
= (gchar
*) g_malloc(len
);
2179 sci_get_text(doc
->editor
->sci
, len
, data
);
2182 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
2183 if (doc
->encoding
!= NULL
&& ! utils_str_equal(doc
->encoding
, "UTF-8") &&
2184 ! utils_str_equal(doc
->encoding
, encodings
[GEANY_ENCODING_NONE
].charset
))
2186 if (! save_convert_to_encoding(doc
, &data
, &len
))
2197 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2199 /* ignore file changed notification when the file is written */
2200 doc
->priv
->file_disk_status
= FILE_IGNORE
;
2202 /* actually write the content of data to the file on disk */
2203 errmsg
= save_doc(doc
, locale_filename
, data
, len
);
2208 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), errmsg
);
2210 if (!file_prefs
.use_safe_file_saving
)
2213 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg
));
2215 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, _("Error saving file."), errmsg
);
2216 doc
->priv
->file_disk_status
= FILE_OK
;
2218 g_free(locale_filename
);
2223 /* store the opened encoding for undo/redo */
2224 store_saved_encoding(doc
);
2226 /* ignore the following things if we are quitting */
2227 if (! main_status
.quitting
)
2229 sci_set_savepoint(doc
->editor
->sci
);
2231 if (file_prefs
.disk_check_timeout
> 0)
2232 document_update_timestamp(doc
, locale_filename
);
2234 /* update filetype-related things */
2235 document_set_filetype(doc
, doc
->file_type
);
2237 document_update_tab_label(doc
);
2239 msgwin_status_add(_("File %s saved."), doc
->file_name
);
2240 ui_update_statusbar(doc
, -1);
2242 vte_cwd((doc
->real_path
!= NULL
) ? doc
->real_path
: doc
->file_name
, FALSE
);
2245 g_free(locale_filename
);
2247 g_signal_emit_by_name(geany_object
, "document-save", doc
);
2253 /* special search function, used from the find entry in the toolbar
2254 * return TRUE if text was found otherwise FALSE
2255 * return also TRUE if text is empty */
2256 gboolean
document_search_bar_find(GeanyDocument
*doc
, const gchar
*text
, gboolean inc
,
2259 gint start_pos
, search_pos
;
2260 struct Sci_TextToFind ttf
;
2262 g_return_val_if_fail(text
!= NULL
, FALSE
);
2263 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2267 start_pos
= (inc
|| backwards
) ? sci_get_selection_start(doc
->editor
->sci
) :
2268 sci_get_selection_end(doc
->editor
->sci
); /* equal if no selection */
2270 /* search cursor to end or start */
2271 ttf
.chrg
.cpMin
= start_pos
;
2272 ttf
.chrg
.cpMax
= backwards
? 0 : sci_get_length(doc
->editor
->sci
);
2273 ttf
.lpstrText
= (gchar
*)text
;
2274 search_pos
= sci_find_text(doc
->editor
->sci
, 0, &ttf
);
2276 /* if no match, search start (or end) to cursor */
2277 if (search_pos
== -1)
2281 ttf
.chrg
.cpMin
= sci_get_length(doc
->editor
->sci
);
2282 ttf
.chrg
.cpMax
= start_pos
;
2287 ttf
.chrg
.cpMax
= start_pos
+ strlen(text
);
2289 search_pos
= sci_find_text(doc
->editor
->sci
, 0, &ttf
);
2292 if (search_pos
!= -1)
2294 gint line
= sci_get_line_from_position(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
2296 /* unfold maybe folded results */
2297 sci_ensure_line_is_visible(doc
->editor
->sci
, line
);
2299 sci_set_selection_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
2300 sci_set_selection_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
2302 if (! editor_line_in_view(doc
->editor
, line
))
2303 { /* we need to force scrolling in case the cursor is outside of the current visible area
2304 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
2305 * while searching */
2306 editor_scroll_to_line(doc
->editor
, -1, 0.3F
);
2309 sci_scroll_caret(doc
->editor
->sci
); /* may need horizontal scrolling */
2316 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
2319 sci_goto_pos(doc
->editor
->sci
, start_pos
, FALSE
); /* clear selection */
2325 /* General search function, used from the find dialog.
2326 * Returns -1 on failure or the start position of the matching text.
2327 * Will skip past any selection, ignoring it.
2329 * @param text Text to find.
2330 * @param original_text Text as it was entered by user, or @c NULL to use @c text
2332 gint
document_find_text(GeanyDocument
*doc
, const gchar
*text
, const gchar
*original_text
,
2333 GeanyFindFlags flags
, gboolean search_backwards
, GeanyMatchInfo
**match_
,
2334 gboolean scroll
, GtkWidget
*parent
)
2336 gint selection_end
, selection_start
, search_pos
;
2338 g_return_val_if_fail(doc
!= NULL
&& text
!= NULL
, -1);
2342 /* Sci doesn't support searching backwards with a regex */
2343 if (flags
& GEANY_FIND_REGEXP
)
2344 search_backwards
= FALSE
;
2347 original_text
= text
;
2349 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2350 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2351 if ((selection_end
- selection_start
) > 0)
2352 { /* there's a selection so go to the end */
2353 if (search_backwards
)
2354 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2356 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2359 sci_set_search_anchor(doc
->editor
->sci
);
2360 if (search_backwards
)
2361 search_pos
= search_find_prev(doc
->editor
->sci
, text
, flags
, match_
);
2363 search_pos
= search_find_next(doc
->editor
->sci
, text
, flags
, match_
);
2365 if (search_pos
!= -1)
2367 /* unfold maybe folded results */
2368 sci_ensure_line_is_visible(doc
->editor
->sci
,
2369 sci_get_line_from_position(doc
->editor
->sci
, search_pos
));
2371 doc
->editor
->scroll_percent
= 0.3F
;
2375 gint sci_len
= sci_get_length(doc
->editor
->sci
);
2377 /* if we just searched the whole text, give up searching. */
2378 if ((selection_end
== 0 && ! search_backwards
) ||
2379 (selection_end
== sci_len
&& search_backwards
))
2381 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), original_text
);
2386 /* we searched only part of the document, so ask whether to wraparound. */
2387 if (search_prefs
.always_wrap
||
2388 dialogs_show_question_full(parent
, GTK_STOCK_FIND
, GTK_STOCK_CANCEL
,
2389 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text
))
2393 sci_set_current_position(doc
->editor
->sci
, (search_backwards
) ? sci_len
: 0, FALSE
);
2394 ret
= document_find_text(doc
, text
, original_text
, flags
, search_backwards
, match_
, scroll
, parent
);
2396 { /* return to original cursor position if not found */
2397 sci_set_current_position(doc
->editor
->sci
, selection_start
, FALSE
);
2406 /* Replaces the selection if it matches, otherwise just finds the next match.
2407 * Returns: start of replaced text, or -1 if no replacement was made
2409 * @param find_text Text to find.
2410 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
2412 gint
document_replace_text(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*original_find_text
,
2413 const gchar
*replace_text
, GeanyFindFlags flags
, gboolean search_backwards
)
2415 gint selection_end
, selection_start
, search_pos
;
2416 GeanyMatchInfo
*match
= NULL
;
2418 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, -1);
2423 /* Sci doesn't support searching backwards with a regex */
2424 if (flags
& GEANY_FIND_REGEXP
)
2425 search_backwards
= FALSE
;
2427 if (!original_find_text
)
2428 original_find_text
= find_text
;
2430 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2431 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2432 if (selection_end
== selection_start
)
2434 /* no selection so just find the next match */
2435 document_find_text(doc
, find_text
, original_find_text
, flags
, search_backwards
, NULL
, TRUE
, NULL
);
2438 /* there's a selection so go to the start before finding to search through it
2439 * this ensures there is a match */
2440 if (search_backwards
)
2441 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
2443 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
2445 search_pos
= document_find_text(doc
, find_text
, original_find_text
, flags
, search_backwards
, &match
, TRUE
, NULL
);
2446 /* return if the original selected text did not match (at the start of the selection) */
2447 if (search_pos
!= selection_start
)
2449 if (search_pos
!= -1)
2450 geany_match_info_free(match
);
2454 if (search_pos
!= -1)
2456 gint replace_len
= search_replace_match(doc
->editor
->sci
, match
, replace_text
);
2457 /* select the replacement - find text will skip past the selected text */
2458 sci_set_selection_start(doc
->editor
->sci
, search_pos
);
2459 sci_set_selection_end(doc
->editor
->sci
, search_pos
+ replace_len
);
2460 geany_match_info_free(match
);
2464 /* no match in the selection */
2471 static void show_replace_summary(GeanyDocument
*doc
, gint count
, const gchar
*original_find_text
,
2472 const gchar
*original_replace_text
)
2478 ui_set_statusbar(FALSE
, _("No matches found for \"%s\"."), original_find_text
);
2482 filename
= g_path_get_basename(DOC_FILENAME(doc
));
2483 ui_set_statusbar(TRUE
, ngettext(
2484 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2485 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2486 count
), filename
, count
, original_find_text
, original_replace_text
);
2491 /* Replace all text matches in a certain range within document.
2492 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2493 * or -1 if no text was found.
2494 * scroll_to_match is whether to scroll the last replacement in view (which also
2495 * clears the selection).
2496 * Returns: the number of replacements made. */
2498 document_replace_range(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2499 GeanyFindFlags flags
, gint start
, gint end
, gboolean scroll_to_match
, gint
*new_range_end
)
2502 struct Sci_TextToFind ttf
;
2503 ScintillaObject
*sci
;
2505 if (new_range_end
!= NULL
)
2506 *new_range_end
= -1;
2508 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, 0);
2510 if (! *find_text
|| doc
->readonly
)
2513 sci
= doc
->editor
->sci
;
2515 ttf
.chrg
.cpMin
= start
;
2516 ttf
.chrg
.cpMax
= end
;
2517 ttf
.lpstrText
= (gchar
*)find_text
;
2519 sci_start_undo_action(sci
);
2520 count
= search_replace_range(sci
, &ttf
, flags
, replace_text
);
2521 sci_end_undo_action(sci
);
2524 { /* scroll last match in view, will destroy the existing selection */
2525 if (scroll_to_match
)
2526 sci_goto_pos(sci
, ttf
.chrg
.cpMin
, TRUE
);
2528 if (new_range_end
!= NULL
)
2529 *new_range_end
= ttf
.chrg
.cpMax
;
2535 void document_replace_sel(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2536 const gchar
*original_find_text
, const gchar
*original_replace_text
, GeanyFindFlags flags
)
2538 gint selection_end
, selection_start
, selection_mode
, selected_lines
, last_line
= 0;
2539 gint max_column
= 0, count
= 0;
2540 gboolean replaced
= FALSE
;
2542 g_return_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
);
2547 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2548 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2549 /* do we have a selection? */
2550 if ((selection_end
- selection_start
) == 0)
2556 selection_mode
= sci_get_selection_mode(doc
->editor
->sci
);
2557 selected_lines
= sci_get_lines_selected(doc
->editor
->sci
);
2558 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2559 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2561 gint first_line
, line
;
2563 sci_start_undo_action(doc
->editor
->sci
);
2565 first_line
= sci_get_line_from_position(doc
->editor
->sci
, selection_start
);
2566 /* Find the last line with chars selected (not EOL char) */
2567 last_line
= sci_get_line_from_position(doc
->editor
->sci
,
2568 selection_end
- editor_get_eol_char_len(doc
->editor
));
2569 last_line
= MAX(first_line
, last_line
);
2570 for (line
= first_line
; line
< (first_line
+ selected_lines
); line
++)
2572 gint line_start
= sci_get_pos_at_line_sel_start(doc
->editor
->sci
, line
);
2573 gint line_end
= sci_get_pos_at_line_sel_end(doc
->editor
->sci
, line
);
2575 /* skip line if there is no selection */
2576 if (line_start
!= INVALID_POSITION
)
2578 /* don't let document_replace_range() scroll to match to keep our selection */
2581 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2582 line_start
, line_end
, FALSE
, &new_sel_end
);
2583 if (new_sel_end
!= -1)
2586 /* this gets the greatest column within the selection after replacing */
2587 max_column
= MAX(max_column
,
2588 new_sel_end
- sci_get_position_from_line(doc
->editor
->sci
, line
));
2592 sci_end_undo_action(doc
->editor
->sci
);
2594 else /* handle normal line selection */
2596 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2597 selection_start
, selection_end
, TRUE
, &selection_end
);
2598 if (selection_end
!= -1)
2603 { /* update the selection for the new endpoint */
2605 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2607 /* now we can scroll to the selection and destroy it because we rebuild it later */
2608 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2610 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2611 * the highest column on the last line. The wrapped selection is completely different
2612 * from the original one, so skip the selection at all */
2613 /* TODO is there a better way to handle the wrapped selection? */
2614 if ((sci_get_line_length(doc
->editor
->sci
, last_line
) - 1) >= max_column
)
2615 { /* for keeping and adjusting the selection in multi line rectangle selection we
2616 * need the last line of the original selection and the greatest column number after
2617 * replacing and set the selection end to the last line at the greatest column */
2618 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2619 sci_set_selection_end(doc
->editor
->sci
,
2620 sci_get_position_from_line(doc
->editor
->sci
, last_line
) + max_column
);
2621 sci_set_selection_mode(doc
->editor
->sci
, selection_mode
);
2626 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2627 sci_set_selection_end(doc
->editor
->sci
, selection_end
);
2630 else /* no replacements */
2633 show_replace_summary(doc
, count
, original_find_text
, original_replace_text
);
2637 /* returns number of replacements made. */
2638 gint
document_replace_all(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2639 const gchar
*original_find_text
, const gchar
*original_replace_text
, GeanyFindFlags flags
)
2642 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, FALSE
);
2647 len
= sci_get_length(doc
->editor
->sci
);
2648 count
= document_replace_range(
2649 doc
, find_text
, replace_text
, flags
, 0, len
, TRUE
, NULL
);
2651 show_replace_summary(doc
, count
, original_find_text
, original_replace_text
);
2657 * Parses or re-parses the document's buffer and updates the type
2658 * keywords and symbol list.
2660 * @param doc The document.
2662 void document_update_tags(GeanyDocument
*doc
)
2667 g_return_if_fail(DOC_VALID(doc
));
2668 g_return_if_fail(app
->tm_workspace
!= NULL
);
2670 /* early out if it's a new file or doesn't support tags */
2671 if (! doc
->file_name
|| ! doc
->file_type
|| !filetype_has_tags(doc
->file_type
))
2673 /* We must call sidebar_update_tag_list() before returning,
2674 * to ensure that the symbol list is always updated properly (e.g.
2675 * when creating a new document with a partial filename set. */
2676 sidebar_update_tag_list(doc
, FALSE
);
2680 /* create a new TM file if there isn't one yet */
2683 gchar
*locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2686 /* lookup the name rather than using filetype name to support custom filetypes */
2687 name
= tm_source_file_get_lang_name(doc
->file_type
->lang
);
2688 doc
->tm_file
= tm_source_file_new(locale_filename
, name
);
2689 g_free(locale_filename
);
2692 tm_workspace_add_source_file_noupdate(doc
->tm_file
);
2695 /* early out if there's no tm source file and we couldn't create one */
2696 if (doc
->tm_file
== NULL
)
2698 /* We must call sidebar_update_tag_list() before returning,
2699 * to ensure that the symbol list is always updated properly (e.g.
2700 * when creating a new document with a partial filename set. */
2701 sidebar_update_tag_list(doc
, FALSE
);
2705 /* Parse Scintilla's buffer directly using TagManager
2706 * Note: this buffer *MUST NOT* be modified */
2707 len
= sci_get_length(doc
->editor
->sci
);
2708 buffer_ptr
= (guchar
*) SSM(doc
->editor
->sci
, SCI_GETCHARACTERPOINTER
, 0, 0);
2709 tm_workspace_update_source_file_buffer(doc
->tm_file
, buffer_ptr
, len
);
2711 sidebar_update_tag_list(doc
, TRUE
);
2712 document_highlight_tags(doc
);
2716 /* Re-highlights type keywords without re-parsing the whole document. */
2717 void document_highlight_tags(GeanyDocument
*doc
)
2719 GString
*keywords_str
;
2722 /* some filetypes support type keywords (such as struct names), but not
2723 * necessarily all filetypes for a particular scintilla lexer. this
2724 * tells us whether the filetype supports keywords, and if so
2725 * which index to use for the scintilla keywords set. */
2726 switch (doc
->file_type
->id
)
2728 case GEANY_FILETYPES_C
:
2729 case GEANY_FILETYPES_CPP
:
2730 case GEANY_FILETYPES_CS
:
2731 case GEANY_FILETYPES_D
:
2732 case GEANY_FILETYPES_JAVA
:
2733 case GEANY_FILETYPES_OBJECTIVEC
:
2734 case GEANY_FILETYPES_VALA
:
2735 case GEANY_FILETYPES_RUST
:
2736 case GEANY_FILETYPES_GO
:
2739 /* index of the keyword set in the Scintilla lexer, for
2740 * example in LexCPP.cxx, see "cppWordLists" global array.
2741 * TODO: this magic number should be a member of the filetype */
2746 return; /* early out if type keywords are not supported */
2748 if (!app
->tm_workspace
->tags_array
)
2751 /* get any type keywords and tell scintilla about them
2752 * this will cause the type keywords to be colourized in scintilla */
2753 keywords_str
= symbols_find_typenames_as_string(doc
->file_type
->lang
, FALSE
);
2756 gchar
*keywords
= g_string_free(keywords_str
, FALSE
);
2757 guint hash
= g_str_hash(keywords
);
2759 if (hash
!= doc
->priv
->keyword_hash
)
2761 sci_set_keywords(doc
->editor
->sci
, keyword_idx
, keywords
);
2762 queue_colourise(doc
); /* force re-highlighting the entire document */
2763 doc
->priv
->keyword_hash
= hash
;
2770 static gboolean
on_document_update_tag_list_idle(gpointer data
)
2772 GeanyDocument
*doc
= data
;
2774 if (! DOC_VALID(doc
))
2777 if (! main_status
.quitting
)
2778 document_update_tags(doc
);
2780 doc
->priv
->tag_list_update_source
= 0;
2782 /* don't update the tags until another modification of the buffer */
2787 void document_update_tag_list_in_idle(GeanyDocument
*doc
)
2789 if (editor_prefs
.autocompletion_update_freq
<= 0 || ! filetype_has_tags(doc
->file_type
))
2792 /* prevent "stacking up" callback handlers, we only need one to run soon */
2793 if (doc
->priv
->tag_list_update_source
!= 0)
2794 g_source_remove(doc
->priv
->tag_list_update_source
);
2796 doc
->priv
->tag_list_update_source
= g_timeout_add_full(G_PRIORITY_LOW
,
2797 editor_prefs
.autocompletion_update_freq
, on_document_update_tag_list_idle
, doc
, NULL
);
2801 static void document_load_config(GeanyDocument
*doc
, GeanyFiletype
*type
,
2802 gboolean filetype_changed
)
2804 g_return_if_fail(doc
);
2806 type
= filetypes
[GEANY_FILETYPES_NONE
];
2808 if (filetype_changed
)
2810 doc
->file_type
= type
;
2812 /* delete tm file object to force creation of a new one */
2813 if (doc
->tm_file
!= NULL
)
2815 tm_workspace_remove_source_file(doc
->tm_file
);
2816 tm_source_file_free(doc
->tm_file
);
2817 doc
->tm_file
= NULL
;
2819 /* load tags files before highlighting (some lexers highlight global typenames) */
2820 if (type
->id
!= GEANY_FILETYPES_NONE
)
2821 symbols_global_tags_loaded(type
->id
);
2823 highlighting_set_styles(doc
->editor
->sci
, type
);
2824 editor_set_indentation_guides(doc
->editor
);
2825 build_menu_update(doc
);
2826 queue_colourise(doc
);
2827 /* forces re-setting SCI_SETKEYWORDS which seems to be needed with
2828 * Scintilla 5 to colorize them properly */
2829 doc
->priv
->keyword_hash
= 0;
2830 if (type
->priv
->symbol_list_sort_mode
== SYMBOLS_SORT_USE_PREVIOUS
)
2831 doc
->priv
->symbol_list_sort_mode
= interface_prefs
.symbols_sort_mode
;
2833 doc
->priv
->symbol_list_sort_mode
= type
->priv
->symbol_list_sort_mode
;
2836 document_update_tags(doc
);
2840 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2841 * @param doc The document to use.
2842 * @param type The filetype. */
2844 void document_set_filetype(GeanyDocument
*doc
, GeanyFiletype
*type
)
2846 gboolean ft_changed
;
2847 GeanyFiletype
*old_ft
;
2849 g_return_if_fail(doc
);
2851 type
= filetypes
[GEANY_FILETYPES_NONE
];
2853 old_ft
= doc
->file_type
;
2854 geany_debug("%s : %s (%s)",
2855 (doc
->file_name
!= NULL
) ? doc
->file_name
: "unknown",
2857 (doc
->encoding
!= NULL
) ? doc
->encoding
: "unknown");
2859 ft_changed
= (doc
->file_type
!= type
); /* filetype has changed */
2860 document_load_config(doc
, type
, ft_changed
);
2864 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
2866 /* assume that if previous filetype was none and the settings are the default ones, this
2867 * is the first time the filetype is carefully set, so we should apply indent settings */
2868 if ((! old_ft
|| old_ft
->id
== GEANY_FILETYPES_NONE
) &&
2869 doc
->editor
->indent_type
== iprefs
->type
&&
2870 doc
->editor
->indent_width
== iprefs
->width
)
2872 document_apply_indent_settings(doc
);
2873 ui_document_show_hide(doc
);
2876 sidebar_openfiles_update(doc
); /* to update the icon */
2877 g_signal_emit_by_name(geany_object
, "document-filetype-set", doc
, old_ft
);
2882 void document_reload_config(GeanyDocument
*doc
)
2884 document_load_config(doc
, doc
->file_type
, TRUE
);
2889 * Sets the encoding of a document.
2890 * This function only set the encoding of the %document, it does not any conversions. The new
2891 * encoding is used when e.g. saving the file.
2893 * @param doc The document to use.
2894 * @param new_encoding The encoding to be set for the document.
2897 void document_set_encoding(GeanyDocument
*doc
, const gchar
*new_encoding
)
2899 if (doc
== NULL
|| new_encoding
== NULL
||
2900 utils_str_equal(new_encoding
, doc
->encoding
))
2903 g_free(doc
->encoding
);
2904 doc
->encoding
= g_strdup(new_encoding
);
2906 ui_update_statusbar(doc
, -1);
2907 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets
.window
, "menu_write_unicode_bom1"),
2908 encodings_is_unicode_charset(doc
->encoding
));
2912 /* own Undo / Redo implementation to be able to undo / redo changes
2913 * to the encoding or the Unicode BOM (which are Scintilla independet).
2914 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2916 /* Clears an Undo or Redo buffer. */
2917 void document_undo_clear_stack(GTrashStack
**stack
)
2919 while (g_trash_stack_height(stack
) > 0)
2921 undo_action
*a
= g_trash_stack_pop(stack
);
2923 if (G_LIKELY(a
!= NULL
))
2929 g_free(a
->data
); break;
2938 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2939 void document_undo_clear(GeanyDocument
*doc
)
2941 document_undo_clear_stack(&doc
->priv
->undo_actions
);
2942 document_undo_clear_stack(&doc
->priv
->redo_actions
);
2944 if (! main_status
.quitting
&& doc
->editor
!= NULL
)
2945 document_set_text_changed(doc
, FALSE
);
2949 /* Adds an undo action without clearing the redo stack. This function should
2950 * not be called directly, generally (use document_undo_add() instead), but is
2951 * used by document_redo() in order not to erase the redo stack while moving
2952 * an action from the redo stack to the undo stack. */
2953 void document_undo_add_internal(GeanyDocument
*doc
, guint type
, gpointer data
)
2955 undo_action
*action
;
2957 g_return_if_fail(doc
!= NULL
);
2959 action
= g_new0(undo_action
, 1);
2960 action
->type
= type
;
2961 action
->data
= data
;
2963 g_trash_stack_push(&doc
->priv
->undo_actions
, action
);
2965 /* avoid unnecessary redraws */
2966 if (type
!= UNDO_SCINTILLA
|| !doc
->changed
)
2967 document_set_text_changed(doc
, TRUE
);
2969 ui_update_popup_reundo_items(doc
);
2972 /* note: this is called on SCN_MODIFIED notifications */
2973 void document_undo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2975 /* Clear the redo actions stack before adding the undo action. */
2976 document_undo_clear_stack(&doc
->priv
->redo_actions
);
2978 document_undo_add_internal(doc
, type
, data
);
2982 gboolean
document_can_undo(GeanyDocument
*doc
)
2984 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2986 if (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0 || sci_can_undo(doc
->editor
->sci
))
2993 static void update_changed_state(GeanyDocument
*doc
)
2996 (sci_is_modified(doc
->editor
->sci
) ||
2997 doc
->has_bom
!= doc
->priv
->saved_encoding
.has_bom
||
2998 ! utils_str_equal(doc
->encoding
, doc
->priv
->saved_encoding
.encoding
));
2999 document_set_text_changed(doc
, doc
->changed
);
3003 void document_undo(GeanyDocument
*doc
)
3005 undo_action
*action
;
3007 g_return_if_fail(doc
!= NULL
);
3009 action
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
3011 if (G_UNLIKELY(action
== NULL
))
3013 /* fallback, should not be necessary */
3014 geany_debug("%s: fallback used", G_STRFUNC
);
3015 sci_undo(doc
->editor
->sci
);
3019 switch (action
->type
)
3021 case UNDO_SCINTILLA
:
3023 document_redo_add(doc
, UNDO_SCINTILLA
, NULL
);
3025 sci_undo(doc
->editor
->sci
);
3030 document_redo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
3032 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
3033 ui_update_statusbar(doc
, -1);
3034 ui_document_show_hide(doc
);
3039 /* use the "old" encoding */
3040 document_redo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
3042 document_set_encoding(doc
, (const gchar
*)action
->data
);
3043 g_free(action
->data
);
3045 ui_update_statusbar(doc
, -1);
3046 ui_document_show_hide(doc
);
3051 undo_action
*next_action
;
3053 document_redo_add(doc
, UNDO_EOL
, GINT_TO_POINTER(sci_get_eol_mode(doc
->editor
->sci
)));
3055 sci_set_eol_mode(doc
->editor
->sci
, GPOINTER_TO_INT(action
->data
));
3057 ui_update_statusbar(doc
, -1);
3058 ui_document_show_hide(doc
);
3060 /* When undoing, UNDO_EOL is always followed by UNDO_SCINTILLA
3061 * which undos the line endings in the editor and should be
3062 * performed together with UNDO_EOL. */
3063 next_action
= g_trash_stack_peek(&doc
->priv
->undo_actions
);
3064 if (next_action
&& next_action
->type
== UNDO_SCINTILLA
)
3070 UndoReloadData
*data
= (UndoReloadData
*)action
->data
;
3071 gint eol_mode
= data
->eol_mode
;
3074 /* We reuse 'data' for the redo action, so read the current EOL mode
3075 * into it before proceeding. */
3076 data
->eol_mode
= editor_get_eol_char_mode(doc
->editor
);
3078 /* Undo the rest of the actions which are part of the reloading process. */
3079 for (i
= 0; i
< data
->actions_count
; i
++)
3082 /* Restore the previous EOL mode. */
3083 sci_set_eol_mode(doc
->editor
->sci
, eol_mode
);
3084 /* This might affect the status bar and document menu, so update them. */
3085 ui_update_statusbar(doc
, -1);
3086 ui_document_show_hide(doc
);
3088 document_redo_add(doc
, UNDO_RELOAD
, data
);
3094 g_free(action
); /* free the action which was taken from the stack */
3096 update_changed_state(doc
);
3097 ui_update_popup_reundo_items(doc
);
3101 gboolean
document_can_redo(GeanyDocument
*doc
)
3103 g_return_val_if_fail(doc
!= NULL
, FALSE
);
3105 if (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0 || sci_can_redo(doc
->editor
->sci
))
3112 void document_redo(GeanyDocument
*doc
)
3114 undo_action
*action
;
3116 g_return_if_fail(doc
!= NULL
);
3118 action
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
3120 if (G_UNLIKELY(action
== NULL
))
3122 /* fallback, should not be necessary */
3123 geany_debug("%s: fallback used", G_STRFUNC
);
3124 sci_redo(doc
->editor
->sci
);
3128 switch (action
->type
)
3130 case UNDO_SCINTILLA
:
3132 undo_action
*next_action
;
3134 document_undo_add_internal(doc
, UNDO_SCINTILLA
, NULL
);
3136 sci_redo(doc
->editor
->sci
);
3138 /* When redoing an EOL change, the UNDO_SCINTILLA which changes
3139 * the line ends in the editor is followed by UNDO_EOL
3140 * which should be performed together with UNDO_SCINTILLA. */
3141 next_action
= g_trash_stack_peek(&doc
->priv
->redo_actions
);
3142 if (next_action
!= NULL
&& next_action
->type
== UNDO_EOL
)
3148 document_undo_add_internal(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
3150 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
3151 ui_update_statusbar(doc
, -1);
3152 ui_document_show_hide(doc
);
3157 document_undo_add_internal(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
3159 document_set_encoding(doc
, (const gchar
*)action
->data
);
3160 g_free(action
->data
);
3162 ui_update_statusbar(doc
, -1);
3163 ui_document_show_hide(doc
);
3168 document_undo_add_internal(doc
, UNDO_EOL
, GINT_TO_POINTER(sci_get_eol_mode(doc
->editor
->sci
)));
3170 sci_set_eol_mode(doc
->editor
->sci
, GPOINTER_TO_INT(action
->data
));
3172 ui_update_statusbar(doc
, -1);
3173 ui_document_show_hide(doc
);
3178 UndoReloadData
*data
= (UndoReloadData
*)action
->data
;
3179 gint eol_mode
= data
->eol_mode
;
3182 /* We reuse 'data' for the undo action, so read the current EOL mode
3183 * into it before proceeding. */
3184 data
->eol_mode
= editor_get_eol_char_mode(doc
->editor
);
3186 /* Redo the rest of the actions which are part of the reloading process. */
3187 for (i
= 0; i
< data
->actions_count
; i
++)
3190 /* Restore the previous EOL mode. */
3191 sci_set_eol_mode(doc
->editor
->sci
, eol_mode
);
3192 /* This might affect the status bar and document menu, so update them. */
3193 ui_update_statusbar(doc
, -1);
3194 ui_document_show_hide(doc
);
3196 document_undo_add_internal(doc
, UNDO_RELOAD
, data
);
3202 g_free(action
); /* free the action which was taken from the stack */
3204 update_changed_state(doc
);
3205 ui_update_popup_reundo_items(doc
);
3209 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
3211 undo_action
*action
;
3213 g_return_if_fail(doc
!= NULL
);
3215 action
= g_new0(undo_action
, 1);
3216 action
->type
= type
;
3217 action
->data
= data
;
3219 g_trash_stack_push(&doc
->priv
->redo_actions
, action
);
3221 if (type
!= UNDO_SCINTILLA
|| !doc
->changed
)
3222 document_set_text_changed(doc
, TRUE
);
3224 ui_update_popup_reundo_items(doc
);
3231 STATUS_DISK_CHANGED
,
3240 } document_status_styles
[] = {
3241 { "geany-document-status-changed", {0}, FALSE
},
3242 { "geany-document-status-disk-changed", {0}, FALSE
},
3243 { "geany-document-status-readonly", {0}, FALSE
}
3247 static gint
document_get_status_id(GeanyDocument
*doc
)
3250 return STATUS_CHANGED
;
3251 #ifdef USE_GIO_FILEMON
3252 else if (doc
->priv
->file_disk_status
== FILE_CHANGED
)
3254 else if (doc
->priv
->protected)
3256 return STATUS_DISK_CHANGED
;
3257 else if (doc
->readonly
)
3258 return STATUS_READONLY
;
3264 /* returns an identifier that is to be set as a widget name or class to get it styled
3265 * depending on the document status (changed, readonly, etc.)
3266 * a NULL return value means default (unchanged) style */
3267 const gchar
*document_get_status_widget_class(GeanyDocument
*doc
)
3271 g_return_val_if_fail(doc
!= NULL
, NULL
);
3273 status
= document_get_status_id(doc
);
3277 return document_status_styles
[status
].name
;
3282 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
3283 * Returned colors are red if the document has changes, green if the document is read-only
3284 * or simply @c NULL if the document is unmodified but writable.
3286 * @param doc The document to use.
3288 * @return @nullable The color for the document or @c NULL if the default color should be used.
3289 * The color object is owned by Geany and should not be modified or freed.
3294 const GdkColor
*document_get_status_color(GeanyDocument
*doc
)
3298 g_return_val_if_fail(doc
!= NULL
, NULL
);
3300 status
= document_get_status_id(doc
);
3303 if (! document_status_styles
[status
].loaded
)
3306 GtkWidgetPath
*path
= gtk_widget_path_new();
3307 GtkStyleContext
*ctx
= gtk_style_context_new();
3308 gtk_widget_path_append_type(path
, GTK_TYPE_WINDOW
);
3309 gtk_widget_path_append_type(path
, GTK_TYPE_BOX
);
3310 gtk_widget_path_append_type(path
, GTK_TYPE_NOTEBOOK
);
3311 gtk_widget_path_append_type(path
, GTK_TYPE_LABEL
);
3312 gtk_widget_path_iter_set_name(path
, -1, document_status_styles
[status
].name
);
3313 gtk_style_context_set_screen(ctx
, gtk_widget_get_screen(GTK_WIDGET(doc
->editor
->sci
)));
3314 gtk_style_context_set_path(ctx
, path
);
3315 gtk_style_context_get_color(ctx
, gtk_style_context_get_state(ctx
), &color
);
3316 document_status_styles
[status
].color
.red
= 0xffff * color
.red
;
3317 document_status_styles
[status
].color
.green
= 0xffff * color
.green
;
3318 document_status_styles
[status
].color
.blue
= 0xffff * color
.blue
;
3319 document_status_styles
[status
].loaded
= TRUE
;
3320 gtk_widget_path_unref(path
);
3321 g_object_unref(ctx
);
3323 return &document_status_styles
[status
].color
;
3327 /** Accessor function for @ref GeanyData::documents_array items.
3328 * @warning Always check the returned document is valid (@c doc->is_valid).
3329 * @param idx @c GeanyData::documents_array index.
3330 * @return @transfer{none} @nullable The document, or @c NULL if @a idx is out of range.
3335 GeanyDocument
*document_index(gint idx
)
3337 return (idx
>= 0 && idx
< (gint
) documents_array
->len
) ? documents
[idx
] : NULL
;
3341 GeanyDocument
*document_clone(GeanyDocument
*old_doc
)
3345 ScintillaObject
*old_sci
;
3347 g_return_val_if_fail(old_doc
, NULL
);
3348 old_sci
= old_doc
->editor
->sci
;
3349 if (sci_has_selection(old_sci
))
3350 text
= sci_get_selection_contents(old_sci
);
3352 text
= sci_get_contents(old_sci
, -1);
3354 doc
= document_new_file(NULL
, old_doc
->file_type
, text
);
3356 document_set_text_changed(doc
, TRUE
);
3358 /* copy file properties */
3359 doc
->editor
->line_wrapping
= old_doc
->editor
->line_wrapping
;
3360 doc
->editor
->line_breaking
= old_doc
->editor
->line_breaking
;
3361 doc
->editor
->auto_indent
= old_doc
->editor
->auto_indent
;
3362 editor_set_indent(doc
->editor
, old_doc
->editor
->indent_type
,
3363 old_doc
->editor
->indent_width
);
3364 doc
->readonly
= old_doc
->readonly
;
3365 doc
->has_bom
= old_doc
->has_bom
;
3366 doc
->priv
->protected = 0;
3367 document_set_encoding(doc
, old_doc
->encoding
);
3368 sci_set_lines_wrapped(doc
->editor
->sci
, doc
->editor
->line_wrapping
);
3369 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
3372 ui_document_show_hide(doc
);
3377 /* @return TRUE if all files were saved or had their changes discarded. */
3378 gboolean
document_account_for_unsaved(void)
3380 guint p
, page_count
;
3382 page_count
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
3383 /* iterate over documents in tabs order */
3384 for (p
= 0; p
< page_count
; p
++)
3386 GeanyDocument
*doc
= document_get_from_page(p
);
3388 if (DOC_VALID(doc
) && doc
->changed
)
3390 if (! dialogs_show_unsaved_file(doc
))
3399 static void force_close_all(void)
3403 main_status
.closing_all
= TRUE
;
3407 document_close(documents
[i
]);
3410 main_status
.closing_all
= FALSE
;
3414 gboolean
document_close_all(void)
3416 if (! document_account_for_unsaved())
3426 * Shows a message related to a document.
3428 * Use this whenever the user needs to see a document-related message,
3429 * for example when the file was externally modified or deleted.
3431 * Any of the buttons can be @c NULL. If not @c NULL, @a btn_1's
3432 * @a response_1 response will be the default for the @c GtkInfoBar or
3435 * @param doc @c GeanyDocument.
3436 * @param msgtype The type of message.
3437 * @param response_cb A callback function called when there's a response.
3438 * @param btn_1 The first action area button.
3439 * @param response_1 The response for @a btn_1.
3440 * @param btn_2 The second action area button.
3441 * @param response_2 The response for @a btn_2.
3442 * @param btn_3 The third action area button.
3443 * @param response_3 The response for @a btn_3.
3444 * @param extra_text Text to show below the main message.
3445 * @param format The text format for the main message.
3446 * @param ... Used with @a format as in @c printf.
3450 static GtkWidget
* document_show_message(GeanyDocument
*doc
, GtkMessageType msgtype
,
3451 void (*response_cb
)(GtkWidget
*info_bar
, gint response_id
, GeanyDocument
*doc
),
3452 const gchar
*btn_1
, GtkResponseType response_1
,
3453 const gchar
*btn_2
, GtkResponseType response_2
,
3454 const gchar
*btn_3
, GtkResponseType response_3
,
3455 const gchar
*extra_text
, const gchar
*format
, ...)
3458 gchar
*text
, *markup
;
3459 GtkWidget
*hbox
, *icon
, *label
, *content_area
;
3460 GtkWidget
*info_widget
, *parent
;
3461 parent
= document_get_notebook_child(doc
);
3463 va_start(args
, format
);
3464 text
= g_strdup_vprintf(format
, args
);
3467 markup
= g_markup_printf_escaped("<span size=\"larger\">%s</span>", text
);
3470 info_widget
= gtk_info_bar_new();
3471 /* must be done now else Gtk-WARNING: widget not within a GtkWindow */
3472 gtk_box_pack_start(GTK_BOX(parent
), info_widget
, FALSE
, TRUE
, 0);
3474 gtk_info_bar_set_message_type(GTK_INFO_BAR(info_widget
), msgtype
);
3477 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget
), btn_1
, response_1
);
3479 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget
), btn_2
, response_2
);
3481 gtk_info_bar_add_button(GTK_INFO_BAR(info_widget
), btn_3
, response_3
);
3483 content_area
= gtk_info_bar_get_content_area(GTK_INFO_BAR(info_widget
));
3485 label
= geany_wrap_label_new(NULL
);
3486 gtk_label_set_markup(GTK_LABEL(label
), markup
);
3489 g_signal_connect(info_widget
, "response", G_CALLBACK(response_cb
), doc
);
3491 hbox
= gtk_box_new(GTK_ORIENTATION_HORIZONTAL
, 12);
3492 gtk_box_pack_start(GTK_BOX(content_area
), hbox
, TRUE
, TRUE
, 0);
3496 case GTK_MESSAGE_INFO
:
3497 icon
= gtk_image_new_from_stock(GTK_STOCK_DIALOG_INFO
, GTK_ICON_SIZE_DIALOG
);
3499 case GTK_MESSAGE_WARNING
:
3500 icon
= gtk_image_new_from_stock(GTK_STOCK_DIALOG_WARNING
, GTK_ICON_SIZE_DIALOG
);
3502 case GTK_MESSAGE_QUESTION
:
3503 icon
= gtk_image_new_from_stock(GTK_STOCK_DIALOG_QUESTION
, GTK_ICON_SIZE_DIALOG
);
3505 case GTK_MESSAGE_ERROR
:
3506 icon
= gtk_image_new_from_stock(GTK_STOCK_DIALOG_ERROR
, GTK_ICON_SIZE_DIALOG
);
3514 gtk_box_pack_start(GTK_BOX(hbox
), icon
, FALSE
, TRUE
, 0);
3518 GtkWidget
*vbox
= gtk_box_new(GTK_ORIENTATION_VERTICAL
, 6);
3519 GtkWidget
*extra_label
= geany_wrap_label_new(extra_text
);
3521 gtk_box_pack_start(GTK_BOX(vbox
), label
, TRUE
, TRUE
, 0);
3522 gtk_box_pack_start(GTK_BOX(vbox
), extra_label
, TRUE
, TRUE
, 0);
3523 gtk_box_pack_start(GTK_BOX(hbox
), vbox
, TRUE
, TRUE
, 0);
3526 gtk_box_pack_start(GTK_BOX(hbox
), label
, TRUE
, TRUE
, 0);
3528 gtk_box_reorder_child(GTK_BOX(parent
), info_widget
, 0);
3530 gtk_widget_show_all(info_widget
);
3536 static void on_monitor_reload_file_response(GtkWidget
*bar
, gint response_id
, GeanyDocument
*doc
)
3538 gboolean close
= FALSE
;
3540 // disable info bar so actions complete normally
3541 unprotect_document(doc
);
3542 doc
->priv
->info_bars
[MSG_TYPE_RELOAD
] = NULL
;
3544 if (response_id
== RESPONSE_DOCUMENT_RELOAD
)
3546 close
= doc
->changed
?
3547 document_reload_prompt(doc
, doc
->encoding
) :
3548 document_reload_force(doc
, doc
->encoding
);
3550 else if (response_id
== RESPONSE_DOCUMENT_SAVE
)
3552 close
= document_save_file(doc
, TRUE
); // force overwrite
3554 else if (response_id
== GTK_RESPONSE_CANCEL
)
3556 document_set_text_changed(doc
, TRUE
);
3561 doc
->priv
->info_bars
[MSG_TYPE_RELOAD
] = bar
;
3562 protect_document(doc
);
3565 gtk_widget_destroy(bar
);
3569 static gboolean
on_sci_key(GtkWidget
*widget
, GdkEventKey
*event
, gpointer data
)
3571 GtkInfoBar
*bar
= GTK_INFO_BAR(data
);
3573 g_return_val_if_fail(event
->type
== GDK_KEY_PRESS
, FALSE
);
3575 switch (event
->keyval
)
3578 case GDK_KEY_ISO_Left_Tab
:
3580 GtkWidget
*action_area
= gtk_info_bar_get_action_area(bar
);
3581 GtkDirectionType dir
= event
->keyval
== GDK_KEY_Tab
? GTK_DIR_TAB_FORWARD
: GTK_DIR_TAB_BACKWARD
;
3582 gtk_widget_child_focus(action_area
, dir
);
3585 case GDK_KEY_Escape
:
3587 gtk_info_bar_response(bar
, GTK_RESPONSE_CANCEL
);
3596 /* Sets up a signal handler to intercept some keys during the lifetime of the GtkInfoBar */
3597 static void enable_key_intercept(GeanyDocument
*doc
, GtkWidget
*bar
)
3599 /* automatically focus editor again on bar close */
3600 g_signal_connect_object(bar
, "destroy", G_CALLBACK(gtk_widget_grab_focus
), doc
->editor
->sci
,
3602 g_signal_connect_object(doc
->editor
->sci
, "key-press-event", G_CALLBACK(on_sci_key
), bar
, 0);
3606 static void monitor_reload_file(GeanyDocument
*doc
)
3608 if (! doc
->changed
&& file_prefs
.reload_clean_doc_on_file_change
)
3610 document_reload_force(doc
, doc
->encoding
);
3614 gchar
*base_name
= g_path_get_basename(doc
->file_name
);
3616 /* show this message only once */
3617 if (doc
->priv
->info_bars
[MSG_TYPE_RELOAD
] == NULL
)
3621 bar
= document_show_message(doc
, GTK_MESSAGE_QUESTION
, on_monitor_reload_file_response
,
3622 _("_Reload"), RESPONSE_DOCUMENT_RELOAD
,
3623 _("_Overwrite"), RESPONSE_DOCUMENT_SAVE
,
3624 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
3625 _("Do you want to reload it?"),
3626 _("The file '%s' on the disk is more recent than the current buffer."),
3629 protect_document(doc
);
3630 doc
->priv
->info_bars
[MSG_TYPE_RELOAD
] = bar
;
3631 enable_key_intercept(doc
, bar
);
3637 static void on_monitor_resave_missing_file_response(GtkWidget
*bar
,
3641 gboolean close
= TRUE
;
3643 unprotect_document(doc
);
3645 if (response_id
== RESPONSE_DOCUMENT_SAVE
)
3646 close
= dialogs_show_save_as();
3650 doc
->priv
->info_bars
[MSG_TYPE_RESAVE
] = NULL
;
3651 gtk_widget_destroy(bar
);
3655 /* protect back the document if save didn't occur */
3656 protect_document(doc
);
3661 static void monitor_resave_missing_file(GeanyDocument
*doc
)
3663 if (doc
->priv
->info_bars
[MSG_TYPE_RESAVE
] == NULL
)
3665 GtkWidget
*bar
= doc
->priv
->info_bars
[MSG_TYPE_RELOAD
];
3667 if (bar
!= NULL
) /* the "file on disk is newer" warning is now moot */
3668 gtk_info_bar_response(GTK_INFO_BAR(bar
), GTK_RESPONSE_CANCEL
);
3670 bar
= document_show_message(doc
, GTK_MESSAGE_WARNING
,
3671 on_monitor_resave_missing_file_response
,
3672 GTK_STOCK_SAVE
, RESPONSE_DOCUMENT_SAVE
,
3673 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
3674 NULL
, GTK_RESPONSE_NONE
,
3675 _("Try to resave the file?"),
3676 _("File \"%s\" was not found on disk!"),
3679 protect_document(doc
);
3680 document_set_text_changed(doc
, TRUE
);
3681 /* don't prompt more than once */
3682 SETPTR(doc
->real_path
, NULL
);
3683 doc
->priv
->info_bars
[MSG_TYPE_RESAVE
] = bar
;
3684 enable_key_intercept(doc
, bar
);
3689 /* Set force to force a disk check, otherwise it is ignored if there was a check
3690 * in the last file_prefs.disk_check_timeout seconds.
3691 * @return @c TRUE if the file has changed. */
3692 gboolean
document_check_disk_status(GeanyDocument
*doc
, gboolean force
)
3694 gboolean ret
= FALSE
;
3695 gboolean use_gio_filemon
;
3697 gchar
*locale_filename
;
3698 FileDiskStatus old_status
;
3700 g_return_val_if_fail(doc
!= NULL
, FALSE
);
3702 /* ignore remote files and documents that have never been saved to disk */
3703 if (notebook_switch_in_progress() || file_prefs
.disk_check_timeout
== 0
3704 || doc
->real_path
== NULL
|| doc
->priv
->is_remote
)
3707 use_gio_filemon
= (doc
->priv
->monitor
!= NULL
);
3709 if (use_gio_filemon
)
3711 if (doc
->priv
->file_disk_status
!= FILE_CHANGED
&& ! force
)
3716 time_t cur_time
= time(NULL
);
3718 if (! force
&& doc
->priv
->last_check
> (cur_time
- file_prefs
.disk_check_timeout
))
3721 doc
->priv
->last_check
= cur_time
;
3724 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
3725 if (!get_mtime(locale_filename
, &mtime
))
3727 monitor_resave_missing_file(doc
);
3728 /* doc may be closed now */
3731 else if (doc
->priv
->mtime
< mtime
)
3733 /* make sure the user is not prompted again after he cancelled the "reload file?" message */
3734 doc
->priv
->mtime
= mtime
;
3735 monitor_reload_file(doc
);
3736 /* doc may be closed now */
3739 g_free(locale_filename
);
3742 { /* doc can get invalid when a document was closed */
3743 old_status
= doc
->priv
->file_disk_status
;
3744 doc
->priv
->file_disk_status
= FILE_OK
;
3745 if (old_status
!= doc
->priv
->file_disk_status
)
3746 ui_update_tab_status(doc
);
3752 /** Compares documents by their display names.
3753 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3754 * @note 'Display name' means the base name of the document's filename.
3756 * @param a @c GeanyDocument**.
3757 * @param b @c GeanyDocument**.
3758 * @warning The arguments take the address of each document pointer.
3759 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3764 gint
document_compare_by_display_name(gconstpointer a
, gconstpointer b
)
3766 GeanyDocument
*doc_a
= *((GeanyDocument
**) a
);
3767 GeanyDocument
*doc_b
= *((GeanyDocument
**) b
);
3768 gchar
*base_name_a
, *base_name_b
;
3771 base_name_a
= g_path_get_basename(DOC_FILENAME(doc_a
));
3772 base_name_b
= g_path_get_basename(DOC_FILENAME(doc_b
));
3774 result
= strcmp(base_name_a
, base_name_b
);
3776 g_free(base_name_a
);
3777 g_free(base_name_b
);
3783 /** Compares documents by their tab order.
3784 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3786 * @param a @c GeanyDocument**.
3787 * @param b @c GeanyDocument**.
3788 * @warning The arguments take the address of each document pointer.
3789 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3791 * @since 0.21 (GEANY_API_VERSION 209)
3794 gint
document_compare_by_tab_order(gconstpointer a
, gconstpointer b
)
3796 GeanyDocument
*doc_a
= *((GeanyDocument
**) a
);
3797 GeanyDocument
*doc_b
= *((GeanyDocument
**) b
);
3798 gint notebook_position_doc_a
;
3799 gint notebook_position_doc_b
;
3801 notebook_position_doc_a
= document_get_notebook_page(doc_a
);
3802 notebook_position_doc_b
= document_get_notebook_page(doc_b
);
3804 if (notebook_position_doc_a
< notebook_position_doc_b
)
3806 if (notebook_position_doc_a
> notebook_position_doc_b
)
3813 /** Compares documents by their tab order, in reverse order.
3814 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
3816 * @param a @c GeanyDocument**.
3817 * @param b @c GeanyDocument**.
3818 * @warning The arguments take the address of each document pointer.
3819 * @return Negative value if a < b; zero if a = b; positive value if a > b.
3821 * @since 0.21 (GEANY_API_VERSION 209)
3824 gint
document_compare_by_tab_order_reverse(gconstpointer a
, gconstpointer b
)
3826 return -1 * document_compare_by_tab_order(a
, b
);
3830 void document_grab_focus(GeanyDocument
*doc
)
3832 g_return_if_fail(doc
!= NULL
);
3834 gtk_widget_grab_focus(GTK_WIDGET(doc
->editor
->sci
));
3837 static void *copy_(void *src
) { return src
; }
3838 static void free_(void *doc
) { }
3841 * Gets the GType of GeanyDocument
3843 * @return the GeanyDocument type */
3845 GType
document_get_type (void);
3847 G_DEFINE_BOXED_TYPE(GeanyDocument
, document
, copy_
, free_
);
3850 gpointer
document_get_data(const GeanyDocument
*doc
, const gchar
*key
)
3852 return g_datalist_get_data(&doc
->priv
->data
, key
);
3856 void document_set_data(GeanyDocument
*doc
, const gchar
*key
, gpointer data
)
3858 g_datalist_set_data(&doc
->priv
->data
, key
, data
);
3862 void document_set_data_full(GeanyDocument
*doc
, const gchar
*key
,
3863 gpointer data
, GDestroyNotify free_func
)
3865 g_datalist_set_data_full(&doc
->priv
->data
, key
, data
, free_func
);