2 * document.c - this file is part of Geany, a fast and lightweight IDE
4 * Copyright 2005-2011 Enrico Tröger <enrico(dot)troeger(at)uvena(dot)de>
5 * Copyright 2006-2011 Nick Treleaven <nick(dot)treleaven(at)btinternet(dot)com>
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, write to the Free Software
19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
23 * Document related actions: new, save, open, etc.
24 * Also Scintilla search actions.
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
38 #ifdef HAVE_SYS_TYPES_H
39 # include <sys/types.h>
44 /* gstdio.h also includes sys/stat.h */
45 #include <glib/gstdio.h>
47 /* uncomment to use GIO based file monitoring, though it is not completely stable yet */
48 /*#define USE_GIO_FILEMON 1*/
52 #include "documentprivate.h"
53 #include "filetypes.h"
55 #include "sciwrappers.h"
58 #include "msgwindow.h"
59 #include "templates.h"
63 #include "encodings.h"
69 #include "highlighting.h"
73 #include "filetypesprivate.h"
78 GeanyFilePrefs file_prefs
;
80 /** Dynamic array of GeanyDocument pointers holding information about the notebook tabs.
81 * Once a pointer is added to this, it is never freed. This means you can keep a pointer
82 * to a document over time, but it might no longer represent a notebook tab. To check this,
83 * check @c doc_ptr->is_valid. Of course, the pointer may represent a different
86 * You also need to check @c GeanyDocument::is_valid when iterating over this array,
87 * although usually you would just use the foreach_document() macro.
89 * Never assume that the order of document pointers is the same as the order of notebook tabs.
90 * Notebook tabs can be reordered. Use @c document_get_from_page(). */
91 GPtrArray
*documents_array
= NULL
;
94 /* an undo action, also used for redo actions */
97 GTrashStack
*next
; /* pointer to the next stack element(required for the GTrashStack) */
98 guint type
; /* to identify the action */
99 gpointer
*data
; /* the old value (before the change), in case of a redo action
100 * it contains the new value */
104 static void document_undo_clear(GeanyDocument
*doc
);
105 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
);
106 static gboolean
remove_page(guint page_num
);
110 * Finds a document whose @c real_path field matches the given filename.
112 * @param realname The filename to search, which should be identical to the
113 * string returned by @c tm_get_real_path().
115 * @return The matching document, or @c NULL.
116 * @note This is only really useful when passing a @c TMWorkObject::file_name.
117 * @see GeanyDocument::real_path.
118 * @see document_find_by_filename().
122 GeanyDocument
* document_find_by_real_path(const gchar
*realname
)
127 return NULL
; /* file doesn't exist on disk */
129 for (i
= 0; i
< documents_array
->len
; i
++)
131 GeanyDocument
*doc
= documents
[i
];
133 if (! doc
->is_valid
|| ! doc
->real_path
)
136 if (utils_filenamecmp(realname
, doc
->real_path
) == 0)
145 /* dereference symlinks, /../ junk in path and return locale encoding */
146 static gchar
*get_real_path_from_utf8(const gchar
*utf8_filename
)
148 gchar
*locale_name
= utils_get_locale_from_utf8(utf8_filename
);
149 gchar
*realname
= tm_get_real_path(locale_name
);
157 * Finds a document with the given filename.
158 * This matches either an exact GeanyDocument::file_name string, or variant
159 * filenames with relative elements in the path (e.g. @c "/dir/..//name" will
162 * @param utf8_filename The filename to search (in UTF-8 encoding).
164 * @return The matching document, or @c NULL.
165 * @see document_find_by_real_path().
167 GeanyDocument
*document_find_by_filename(const gchar
*utf8_filename
)
173 g_return_val_if_fail(utf8_filename
!= NULL
, NULL
);
175 /* First search GeanyDocument::file_name, so we can find documents with a
176 * filename set but not saved on disk, like vcdiff produces */
177 for (i
= 0; i
< documents_array
->len
; i
++)
181 if (! doc
->is_valid
|| doc
->file_name
== NULL
)
184 if (utils_filenamecmp(utf8_filename
, doc
->file_name
) == 0)
189 /* Now try matching based on the realpath(), which is unique per file on disk */
190 realname
= get_real_path_from_utf8(utf8_filename
);
191 doc
= document_find_by_real_path(realname
);
197 /* returns the document which has sci, or NULL. */
198 GeanyDocument
*document_find_by_sci(ScintillaObject
*sci
)
202 g_return_val_if_fail(sci
!= NULL
, NULL
);
204 for (i
= 0; i
< documents_array
->len
; i
++)
206 if (documents
[i
]->is_valid
&& documents
[i
]->editor
->sci
== sci
)
213 /** Gets the notebook page index for a document.
214 * @param doc The document.
217 gint
document_get_notebook_page(GeanyDocument
*doc
)
219 g_return_val_if_fail(doc
!= NULL
, -1);
221 return gtk_notebook_page_num(GTK_NOTEBOOK(main_widgets
.notebook
),
222 GTK_WIDGET(doc
->editor
->sci
));
227 * Finds the document for the given notebook page @a page_num.
229 * @param page_num The notebook page number to search.
231 * @return The corresponding document for the given notebook page, or @c NULL.
233 GeanyDocument
*document_get_from_page(guint page_num
)
235 ScintillaObject
*sci
;
237 if (page_num
>= documents_array
->len
)
240 sci
= (ScintillaObject
*)gtk_notebook_get_nth_page(
241 GTK_NOTEBOOK(main_widgets
.notebook
), page_num
);
243 return document_find_by_sci(sci
);
248 * Finds the current document.
250 * @return A pointer to the current document or @c NULL if there are no opened documents.
252 GeanyDocument
*document_get_current(void)
254 gint cur_page
= gtk_notebook_get_current_page(GTK_NOTEBOOK(main_widgets
.notebook
));
260 ScintillaObject
*sci
= (ScintillaObject
*)
261 gtk_notebook_get_nth_page(GTK_NOTEBOOK(main_widgets
.notebook
), cur_page
);
263 return document_find_by_sci(sci
);
268 void document_init_doclist()
270 documents_array
= g_ptr_array_new();
274 void document_finalize()
278 for (i
= 0; i
< documents_array
->len
; i
++)
279 g_free(documents
[i
]);
280 g_ptr_array_free(documents_array
, TRUE
);
285 * Returns the last part of the filename of the given GeanyDocument. The result is also
286 * truncated to a maximum of @a length characters in case the filename is very long.
288 * @param doc The document to use.
289 * @param length The length of the resulting string or -1 to use a default value.
291 * @return The ellipsized last part of the filename of @a doc, should be freed when no
296 /* TODO make more use of this */
297 gchar
*document_get_basename_for_display(GeanyDocument
*doc
, gint length
)
299 gchar
*base_name
, *short_name
;
301 g_return_val_if_fail(doc
!= NULL
, NULL
);
306 base_name
= g_path_get_basename(DOC_FILENAME(doc
));
307 short_name
= utils_str_middle_truncate(base_name
, (guint
)length
);
315 void document_update_tab_label(GeanyDocument
*doc
)
320 g_return_if_fail(doc
!= NULL
);
322 short_name
= document_get_basename_for_display(doc
, -1);
324 /* we need to use the event box for the tooltip, labels don't get the necessary events */
325 parent
= gtk_widget_get_parent(doc
->priv
->tab_label
);
326 parent
= gtk_widget_get_parent(parent
);
328 gtk_label_set_text(GTK_LABEL(doc
->priv
->tab_label
), short_name
);
330 gtk_widget_set_tooltip_text(parent
, DOC_FILENAME(doc
));
337 * Updates the tab labels, the status bar, the window title and some save-sensitive buttons
338 * according to the document's save state.
339 * This is called by Geany mostly when opening or saving files.
341 * @param doc The document to use.
342 * @param changed Whether the document state should indicate changes have been made.
344 void document_set_text_changed(GeanyDocument
*doc
, gboolean changed
)
346 g_return_if_fail(doc
!= NULL
);
348 doc
->changed
= changed
;
350 if (! main_status
.quitting
)
352 ui_update_tab_status(doc
);
353 ui_save_buttons_toggle(changed
);
354 ui_set_window_title(doc
);
355 ui_update_statusbar(doc
, -1);
360 /* returns the next free place in the document list,
361 * or -1 if the documents_array is full */
362 static gint
document_get_new_idx(void)
366 for (i
= 0; i
< documents_array
->len
; i
++)
368 if (documents
[i
]->editor
== NULL
)
377 static void queue_colourise(GeanyDocument
*doc
)
379 /* Colourise the editor before it is next drawn */
380 doc
->priv
->colourise_needed
= TRUE
;
382 /* If the editor doesn't need drawing (e.g. after saving the current
383 * document), we need to force a redraw, so the expose event is triggered.
384 * This ensures we don't start colourising before all documents are opened/saved,
385 * only once the editor is drawn. */
386 gtk_widget_queue_draw(GTK_WIDGET(doc
->editor
->sci
));
390 #ifdef USE_GIO_FILEMON
391 static void monitor_file_changed_cb(G_GNUC_UNUSED GFileMonitor
*monitor
, G_GNUC_UNUSED GFile
*file
,
392 G_GNUC_UNUSED GFile
*other_file
, GFileMonitorEvent event
,
395 g_return_if_fail(doc
!= NULL
);
397 if (file_prefs
.disk_check_timeout
== 0)
400 geany_debug("%s: event: %d previous file status: %d",
401 G_STRFUNC
, event
, doc
->priv
->file_disk_status
);
404 case G_FILE_MONITOR_EVENT_CHANGES_DONE_HINT
:
406 if (doc
->priv
->file_disk_status
== FILE_IGNORE
)
407 doc
->priv
->file_disk_status
= FILE_OK
;
409 doc
->priv
->file_disk_status
= FILE_CHANGED
;
410 g_message("%s: FILE_CHANGED", G_STRFUNC
);
413 case G_FILE_MONITOR_EVENT_DELETED
:
415 doc
->priv
->file_disk_status
= FILE_CHANGED
;
416 g_message("%s: FILE_MISSING", G_STRFUNC
);
422 if (doc
->priv
->file_disk_status
!= FILE_OK
)
424 ui_update_tab_status(doc
);
430 static void document_stop_file_monitoring(GeanyDocument
*doc
)
432 g_return_if_fail(doc
!= NULL
);
434 if (doc
->priv
->monitor
!= NULL
)
436 g_object_unref(doc
->priv
->monitor
);
437 doc
->priv
->monitor
= NULL
;
442 static void monitor_file_setup(GeanyDocument
*doc
)
444 g_return_if_fail(doc
!= NULL
);
445 /* Disable file monitoring completely for remote files (i.e. remote GIO files) as GFileMonitor
446 * doesn't work at all for remote files and legacy polling is too slow. */
447 if (! doc
->priv
->is_remote
)
449 #ifdef USE_GIO_FILEMON
450 gchar
*locale_filename
;
452 /* stop any previous monitoring */
453 document_stop_file_monitoring(doc
);
455 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
456 if (locale_filename
!= NULL
&& g_file_test(locale_filename
, G_FILE_TEST_EXISTS
))
458 /* get a file monitor and connect to the 'changed' signal */
459 GFile
*file
= g_file_new_for_path(locale_filename
);
460 doc
->priv
->monitor
= g_file_monitor_file(file
, G_FILE_MONITOR_NONE
, NULL
, NULL
);
461 g_signal_connect(doc
->priv
->monitor
, "changed",
462 G_CALLBACK(monitor_file_changed_cb
), doc
);
464 /* we set the rate limit according to the GUI pref but it's most probably not used */
465 g_file_monitor_set_rate_limit(doc
->priv
->monitor
, file_prefs
.disk_check_timeout
* 1000);
467 g_object_unref(file
);
469 g_free(locale_filename
);
472 doc
->priv
->file_disk_status
= FILE_OK
;
476 void document_try_focus(GeanyDocument
*doc
, GtkWidget
*source_widget
)
478 /* doc might not be valid e.g. if user closed a tab whilst Geany is opening files */
481 GtkWidget
*sci
= GTK_WIDGET(doc
->editor
->sci
);
482 GtkWidget
*focusw
= gtk_window_get_focus(GTK_WINDOW(main_widgets
.window
));
484 if (source_widget
== NULL
)
485 source_widget
= doc
->priv
->tag_tree
;
487 if (focusw
== source_widget
)
488 gtk_widget_grab_focus(sci
);
493 static gboolean
on_idle_focus(gpointer doc
)
495 document_try_focus(doc
, NULL
);
500 /* Creates a new document and editor, adding a tab in the notebook.
501 * @return The created document */
502 static GeanyDocument
*document_create(const gchar
*utf8_filename
)
506 gint cur_pages
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
510 doc
= document_get_current();
511 /* remove the empty document first */
512 if (doc
!= NULL
&& doc
->file_name
== NULL
&& ! doc
->changed
)
513 /* prevent immediately opening another new doc with
514 * new_document_after_close pref */
518 new_idx
= document_get_new_idx();
519 if (new_idx
== -1) /* expand the array, no free places */
521 doc
= g_new0(GeanyDocument
, 1);
523 new_idx
= documents_array
->len
;
524 g_ptr_array_add(documents_array
, doc
);
527 doc
= documents
[new_idx
];
529 /* initialize default document settings */
530 doc
->priv
= g_new0(GeanyDocumentPrivate
, 1);
531 doc
->index
= new_idx
;
532 doc
->file_name
= g_strdup(utf8_filename
);
533 doc
->editor
= editor_create(doc
);
534 #ifndef USE_GIO_FILEMON
535 doc
->priv
->last_check
= time(NULL
);
538 sidebar_openfiles_add(doc
); /* sets doc->iter */
540 notebook_new_tab(doc
);
542 /* select document in sidebar */
544 GtkTreeSelection
*sel
;
546 sel
= gtk_tree_view_get_selection(GTK_TREE_VIEW(tv
.tree_openfiles
));
547 gtk_tree_selection_select_iter(sel
, &doc
->priv
->iter
);
550 ui_document_buttons_update();
552 doc
->is_valid
= TRUE
; /* do this last to prevent UI updating with NULL items. */
558 * Closes the given document.
560 * @param doc The document to remove.
562 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
566 gboolean
document_close(GeanyDocument
*doc
)
568 g_return_val_if_fail(doc
, FALSE
);
570 return document_remove_page(document_get_notebook_page(doc
));
574 /* Call document_remove_page() instead, this is only needed for document_create()
575 * to prevent re-opening a new document when the last document is closed (if enabled). */
576 static gboolean
remove_page(guint page_num
)
578 GeanyDocument
*doc
= document_get_from_page(page_num
);
580 g_return_val_if_fail(doc
!= NULL
, FALSE
);
582 if (doc
->changed
&& ! dialogs_show_unsaved_file(doc
))
585 /* tell any plugins that the document is about to be closed */
586 g_signal_emit_by_name(geany_object
, "document-close", doc
);
588 /* Checking real_path makes it likely the file exists on disk */
589 if (! main_status
.closing_all
&& doc
->real_path
!= NULL
)
590 ui_add_recent_document(doc
);
592 doc
->is_valid
= FALSE
;
594 if (! main_status
.quitting
)
596 notebook_remove_page(page_num
);
597 sidebar_remove_document(doc
);
598 navqueue_remove_file(doc
->file_name
);
599 msgwin_status_add(_("File %s closed."), DOC_FILENAME(doc
));
601 g_free(doc
->encoding
);
602 g_free(doc
->priv
->saved_encoding
.encoding
);
603 g_free(doc
->file_name
);
604 g_free(doc
->real_path
);
605 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
607 editor_destroy(doc
->editor
);
608 doc
->editor
= NULL
; /* needs to be NULL for document_undo_clear() call below */
610 document_stop_file_monitoring(doc
);
612 document_undo_clear(doc
);
616 /* reset document settings to defaults for re-use */
617 memset(doc
, 0, sizeof(GeanyDocument
));
619 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
621 sidebar_update_tag_list(NULL
, FALSE
);
622 ui_set_window_title(NULL
);
623 ui_save_buttons_toggle(FALSE
);
624 ui_update_popup_reundo_items(NULL
);
625 ui_document_buttons_update();
626 build_menu_update(NULL
);
633 * Removes the given notebook tab at @a page_num and clears all related information
634 * in the document list.
636 * @param page_num The notebook page number to remove.
638 * @return @c TRUE if the document was actually removed or @c FALSE otherwise.
640 gboolean
document_remove_page(guint page_num
)
642 gboolean done
= remove_page(page_num
);
644 if (done
&& ui_prefs
.new_document_after_close
)
645 document_new_file_if_non_open();
651 /* used to keep a record of the unchanged document state encoding */
652 static void store_saved_encoding(GeanyDocument
*doc
)
654 g_free(doc
->priv
->saved_encoding
.encoding
);
655 doc
->priv
->saved_encoding
.encoding
= g_strdup(doc
->encoding
);
656 doc
->priv
->saved_encoding
.has_bom
= doc
->has_bom
;
660 /* Opens a new empty document only if there are no other documents open */
661 GeanyDocument
*document_new_file_if_non_open(void)
663 if (gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)) == 0)
664 return document_new_file(NULL
, NULL
, NULL
);
671 * Creates a new document.
672 * Line endings in @a text will be converted to the default setting.
673 * Afterwards, the @c "document-new" signal is emitted for plugins.
675 * @param utf8_filename The file name in UTF-8 encoding, or @c NULL to open a file as "untitled".
676 * @param ft The filetype to set or @c NULL to detect it from @a filename if not @c NULL.
677 * @param text The initial content of the file (in UTF-8 encoding), or @c NULL.
679 * @return The new document.
681 GeanyDocument
*document_new_file(const gchar
*utf8_filename
, GeanyFiletype
*ft
, const gchar
*text
)
685 if (utf8_filename
&& g_path_is_absolute(utf8_filename
))
688 tmp
= utils_strdupa(utf8_filename
); /* work around const */
689 utils_tidy_path(tmp
);
692 doc
= document_create(utf8_filename
);
694 g_assert(doc
!= NULL
);
696 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
699 GString
*template = g_string_new(text
);
700 utils_ensure_same_eol_characters(template, file_prefs
.default_eol_character
);
702 sci_set_text(doc
->editor
->sci
, template->str
);
703 g_string_free(template, TRUE
);
706 sci_clear_all(doc
->editor
->sci
);
708 sci_set_eol_mode(doc
->editor
->sci
, file_prefs
.default_eol_character
);
710 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
711 sci_empty_undo_buffer(doc
->editor
->sci
);
713 doc
->encoding
= g_strdup(encodings
[file_prefs
.default_new_encoding
].charset
);
714 /* store the opened encoding for undo/redo */
715 store_saved_encoding(doc
);
717 if (ft
== NULL
&& utf8_filename
!= NULL
) /* guess the filetype from the filename if one is given */
718 ft
= filetypes_detect_from_document(doc
);
720 document_set_filetype(doc
, ft
); /* also re-parses tags */
722 ui_set_window_title(doc
);
723 build_menu_update(doc
);
724 document_set_text_changed(doc
, FALSE
);
725 ui_document_show_hide(doc
); /* update the document menu */
727 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
728 /* bring it in front, jump to the start and grab the focus */
729 editor_goto_pos(doc
->editor
, 0, FALSE
);
730 document_try_focus(doc
, NULL
);
732 #ifdef USE_GIO_FILEMON
733 monitor_file_setup(doc
);
735 doc
->priv
->mtime
= time(NULL
);
738 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
739 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
), doc
->editor
);
741 g_signal_emit_by_name(geany_object
, "document-new", doc
);
743 msgwin_status_add(_("New file \"%s\" opened."),
751 * Opens a document specified by @a locale_filename.
752 * Afterwards, the @c "document-open" signal is emitted for plugins.
754 * @param locale_filename The filename of the document to load, in locale encoding.
755 * @param readonly Whether to open the document in read-only mode.
756 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
757 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
759 * @return The document opened or @c NULL.
761 GeanyDocument
*document_open_file(const gchar
*locale_filename
, gboolean readonly
,
762 GeanyFiletype
*ft
, const gchar
*forced_enc
)
764 return document_open_file_full(NULL
, locale_filename
, 0, readonly
, ft
, forced_enc
);
770 gchar
*data
; /* null-terminated file data */
771 gsize len
; /* string length of data */
774 time_t mtime
; /* modification time, read by stat::st_mtime */
779 /* loads textfile data, verifies and converts to forced_enc or UTF-8. Also handles BOM. */
780 static gboolean
load_text_file(const gchar
*locale_filename
, const gchar
*display_filename
,
781 FileData
*filedata
, const gchar
*forced_enc
)
786 filedata
->data
= NULL
;
788 filedata
->enc
= NULL
;
789 filedata
->bom
= FALSE
;
790 filedata
->readonly
= FALSE
;
792 if (g_stat(locale_filename
, &st
) != 0)
794 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"),
795 display_filename
, g_strerror(errno
));
799 filedata
->mtime
= st
.st_mtime
;
801 if (! g_file_get_contents(locale_filename
, &filedata
->data
, NULL
, &err
))
803 ui_set_statusbar(TRUE
, "%s", err
->message
);
808 filedata
->len
= (gsize
) st
.st_size
;
809 if (! encodings_convert_to_utf8_auto(&filedata
->data
, &filedata
->len
, forced_enc
,
810 &filedata
->enc
, &filedata
->bom
, &filedata
->readonly
))
814 ui_set_statusbar(TRUE
, _("The file \"%s\" is not valid %s."),
815 display_filename
, forced_enc
);
819 ui_set_statusbar(TRUE
,
820 _("The file \"%s\" does not look like a text file or the file encoding is not supported."),
823 g_free(filedata
->data
);
827 if (filedata
->readonly
)
829 const gchar
*warn_msg
= _(
830 "The file \"%s\" could not be opened properly and has been truncated. " \
831 "This can occur if the file contains a NULL byte. " \
832 "Be aware that saving it can cause data loss.\nThe file was set to read-only.");
834 if (main_status
.main_window_realized
)
835 dialogs_show_msgbox(GTK_MESSAGE_WARNING
, warn_msg
, display_filename
);
837 ui_set_statusbar(TRUE
, warn_msg
, display_filename
);
844 /* Sets the cursor position on opening a file. First it sets the line when cl_options.goto_line
845 * is set, otherwise it sets the line when pos is greater than zero and finally it sets the column
846 * if cl_options.goto_column is set.
848 * returns the new position which may have changed */
849 static gint
set_cursor_position(GeanyEditor
*editor
, gint pos
)
851 if (cl_options
.goto_line
>= 0)
852 { /* goto line which was specified on command line and then undefine the line */
853 sci_goto_line(editor
->sci
, cl_options
.goto_line
- 1, TRUE
);
854 editor
->scroll_percent
= 0.5F
;
855 cl_options
.goto_line
= -1;
859 sci_set_current_position(editor
->sci
, pos
, FALSE
);
860 editor
->scroll_percent
= 0.5F
;
863 if (cl_options
.goto_column
>= 0)
864 { /* goto column which was specified on command line and then undefine the column */
866 gint new_pos
= sci_get_current_position(editor
->sci
) + cl_options
.goto_column
;
867 sci_set_current_position(editor
->sci
, new_pos
, FALSE
);
868 editor
->scroll_percent
= 0.5F
;
869 cl_options
.goto_column
= -1;
872 return sci_get_current_position(editor
->sci
);
876 /* Count lines that start with some hard tabs then a soft tab. */
877 static gboolean
detect_tabs_and_spaces(GeanyEditor
*editor
)
879 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
880 ScintillaObject
*sci
= editor
->sci
;
882 struct Sci_TextToFind ttf
;
883 gchar
*soft_tab
= g_strnfill((gsize
)iprefs
->width
, ' ');
884 gchar
*regex
= g_strconcat("^\t+", soft_tab
, "[^ ]", NULL
);
889 ttf
.chrg
.cpMax
= sci_get_length(sci
);
890 ttf
.lpstrText
= regex
;
895 pos
= sci_find_text(sci
, SCFIND_REGEXP
, &ttf
);
897 break; /* no more matches */
899 ttf
.chrg
.cpMin
= ttf
.chrgText
.cpMax
+ 1; /* search after this match */
902 /* The 0.02 is a low weighting to ignore a few possibly accidental occurrences */
903 return count
> sci_get_line_count(sci
) * 0.02;
907 /* Detect the indent type based on counting the leading indent characters for each line.
908 * Returns whether detection succeeded, and the detected type in *type_ upon success */
909 gboolean
document_detect_indent_type(GeanyDocument
*doc
, GeanyIndentType
*type_
)
911 GeanyEditor
*editor
= doc
->editor
;
912 ScintillaObject
*sci
= editor
->sci
;
913 gint line
, line_count
;
914 gsize tabs
= 0, spaces
= 0;
916 if (detect_tabs_and_spaces(editor
))
918 *type_
= GEANY_INDENT_TYPE_BOTH
;
922 line_count
= sci_get_line_count(sci
);
923 for (line
= 0; line
< line_count
; line
++)
925 gint pos
= sci_get_position_from_line(sci
, line
);
928 /* most code will have indent total <= 24, otherwise it's more likely to be
929 * alignment than indentation */
930 if (sci_get_line_indentation(sci
, line
) > 24)
933 c
= sci_get_char_at(sci
, pos
);
936 /* check for at least 2 spaces */
937 else if (c
== ' ' && sci_get_char_at(sci
, pos
+ 1) == ' ')
940 if (spaces
== 0 && tabs
== 0)
943 /* the factors may need to be tweaked */
944 if (spaces
> tabs
* 4)
945 *type_
= GEANY_INDENT_TYPE_SPACES
;
946 else if (tabs
> spaces
* 4)
947 *type_
= GEANY_INDENT_TYPE_TABS
;
949 *type_
= GEANY_INDENT_TYPE_BOTH
;
955 /* Detect the indent width based on counting the leading indent characters for each line.
956 * Returns whether detection succeeded, and the detected width in *width_ upon success */
957 static gboolean
detect_indent_width(GeanyEditor
*editor
, GeanyIndentType type
, gint
*width_
)
959 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(editor
);
960 ScintillaObject
*sci
= editor
->sci
;
961 gint line
, line_count
;
962 gint widths
[7] = { 0 }; /* width can be from 2 to 8 */
963 gint count
, width
, i
;
965 /* can't easily detect the supposed width of a tab, guess the default is OK */
966 if (type
== GEANY_INDENT_TYPE_TABS
)
969 /* force 8 at detection time for tab & spaces -- anyway we don't use tabs at this point */
970 sci_set_tab_width(sci
, 8);
972 line_count
= sci_get_line_count(sci
);
973 for (line
= 0; line
< line_count
; line
++)
975 width
= sci_get_line_indentation(sci
, line
);
976 /* most code will have indent total <= 24, otherwise it's more likely to be
977 * alignment than indentation */
980 /* < 2 is no indentation */
984 for (i
= G_N_ELEMENTS(widths
) - 1; i
>= 0; i
--)
986 if ((width
% (i
+ 2)) == 0)
991 width
= iprefs
->width
;
992 for (i
= G_N_ELEMENTS(widths
) - 1; i
>= 0; i
--)
994 /* give large indents higher weight not to be fooled by spurious indents */
995 if (widths
[i
] >= count
* 1.5)
1010 /* same as detect_indent_width() but uses editor's indent type */
1011 gboolean
document_detect_indent_width(GeanyDocument
*doc
, gint
*width_
)
1013 return detect_indent_width(doc
->editor
, doc
->editor
->indent_type
, width_
);
1017 void document_apply_indent_settings(GeanyDocument
*doc
)
1019 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
1020 GeanyIndentType type
= iprefs
->type
;
1021 gint width
= iprefs
->width
;
1023 if (iprefs
->detect_type
&& document_detect_indent_type(doc
, &type
))
1025 if (type
!= iprefs
->type
)
1027 const gchar
*name
= NULL
;
1031 case GEANY_INDENT_TYPE_SPACES
:
1034 case GEANY_INDENT_TYPE_TABS
:
1037 case GEANY_INDENT_TYPE_BOTH
:
1038 name
= _("Tabs and Spaces");
1041 /* For translators: first wildcard is the indentation mode (Spaces, Tabs, Tabs
1042 * and Spaces), the second one is the filename */
1043 ui_set_statusbar(TRUE
, _("Setting %s indentation mode for %s."), name
,
1047 else if (doc
->file_type
->indent_type
> -1)
1048 type
= doc
->file_type
->indent_type
;
1050 if (iprefs
->detect_width
&& detect_indent_width(doc
->editor
, type
, &width
))
1052 if (width
!= iprefs
->width
)
1054 ui_set_statusbar(TRUE
, _("Setting indentation width to %d for %s."), width
,
1058 else if (doc
->file_type
->indent_width
> -1)
1059 width
= doc
->file_type
->indent_width
;
1061 editor_set_indent(doc
->editor
, type
, width
);
1065 void document_show_tab(GeanyDocument
*doc
)
1067 gtk_notebook_set_current_page(GTK_NOTEBOOK(main_widgets
.notebook
),
1068 document_get_notebook_page(doc
));
1072 /* To open a new file, set doc to NULL; filename should be locale encoded.
1073 * To reload a file, set the doc for the document to be reloaded; filename should be NULL.
1074 * pos is the cursor position, which can be overridden by --line and --column.
1075 * forced_enc can be NULL to detect the file encoding.
1076 * Returns: doc of the opened file or NULL if an error occurred. */
1077 GeanyDocument
*document_open_file_full(GeanyDocument
*doc
, const gchar
*filename
, gint pos
,
1078 gboolean readonly
, GeanyFiletype
*ft
, const gchar
*forced_enc
)
1081 gboolean reload
= (doc
== NULL
) ? FALSE
: TRUE
;
1082 gchar
*utf8_filename
= NULL
;
1083 gchar
*display_filename
= NULL
;
1084 gchar
*locale_filename
= NULL
;
1085 GeanyFiletype
*use_ft
;
1090 utf8_filename
= g_strdup(doc
->file_name
);
1091 locale_filename
= utils_get_locale_from_utf8(utf8_filename
);
1095 /* filename must not be NULL when opening a file */
1096 g_return_val_if_fail(filename
, NULL
);
1099 /* if filename is a shortcut, try to resolve it */
1100 locale_filename
= win32_get_shortcut_target(filename
);
1102 locale_filename
= g_strdup(filename
);
1104 /* remove relative junk */
1105 utils_tidy_path(locale_filename
);
1107 /* try to get the UTF-8 equivalent for the filename, fallback to filename if error */
1108 utf8_filename
= utils_get_utf8_from_locale(locale_filename
);
1110 /* if file is already open, switch to it and go */
1111 doc
= document_find_by_filename(utf8_filename
);
1114 ui_add_recent_document(doc
); /* either add or reorder recent item */
1115 /* show the doc before reload dialog */
1116 document_show_tab(doc
);
1117 document_check_disk_status(doc
, TRUE
); /* force a file changed check */
1120 if (reload
|| doc
== NULL
)
1121 { /* doc possibly changed */
1122 display_filename
= utils_str_middle_truncate(utf8_filename
, 100);
1124 if (! load_text_file(locale_filename
, display_filename
, &filedata
, forced_enc
))
1126 g_free(display_filename
);
1127 g_free(utf8_filename
);
1128 g_free(locale_filename
);
1134 doc
= document_create(utf8_filename
);
1135 g_return_val_if_fail(doc
!= NULL
, NULL
); /* really should not happen */
1137 /* file exists on disk, set real_path */
1138 setptr(doc
->real_path
, tm_get_real_path(locale_filename
));
1140 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1141 monitor_file_setup(doc
);
1144 sci_set_undo_collection(doc
->editor
->sci
, FALSE
); /* avoid creation of an undo action */
1145 sci_empty_undo_buffer(doc
->editor
->sci
);
1147 /* add the text to the ScintillaObject */
1148 sci_set_readonly(doc
->editor
->sci
, FALSE
); /* to allow replacing text */
1149 sci_set_text(doc
->editor
->sci
, filedata
.data
); /* NULL terminated data */
1150 queue_colourise(doc
); /* Ensure the document gets colourised. */
1152 /* detect & set line endings */
1153 editor_mode
= utils_get_line_endings(filedata
.data
, filedata
.len
);
1154 sci_set_eol_mode(doc
->editor
->sci
, editor_mode
);
1155 g_free(filedata
.data
);
1157 sci_set_undo_collection(doc
->editor
->sci
, TRUE
);
1159 doc
->priv
->mtime
= filedata
.mtime
; /* get the modification time from file and keep it */
1160 g_free(doc
->encoding
); /* if reloading, free old encoding */
1161 doc
->encoding
= filedata
.enc
;
1162 doc
->has_bom
= filedata
.bom
;
1163 store_saved_encoding(doc
); /* store the opened encoding for undo/redo */
1165 doc
->readonly
= readonly
|| filedata
.readonly
;
1166 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
1168 /* update line number margin width */
1169 doc
->priv
->line_count
= sci_get_line_count(doc
->editor
->sci
);
1170 sci_set_line_numbers(doc
->editor
->sci
, editor_prefs
.show_linenumber_margin
, 0);
1175 /* "the" SCI signal (connect after initial setup(i.e. adding text)) */
1176 g_signal_connect(doc
->editor
->sci
, "sci-notify", G_CALLBACK(editor_sci_notify_cb
),
1179 use_ft
= (ft
!= NULL
) ? ft
: filetypes_detect_from_document(doc
);
1183 document_undo_clear(doc
);
1187 /* update taglist, typedef keywords and build menu if necessary */
1188 document_set_filetype(doc
, use_ft
);
1190 /* set indentation settings after setting the filetype */
1192 editor_set_indent(doc
->editor
, doc
->editor
->indent_type
, doc
->editor
->indent_width
); /* resetup sci */
1194 document_apply_indent_settings(doc
);
1196 document_set_text_changed(doc
, FALSE
); /* also updates tab state */
1197 ui_document_show_hide(doc
); /* update the document menu */
1199 /* finally add current file to recent files menu, but not the files from the last session */
1200 if (! main_status
.opening_session_files
)
1201 ui_add_recent_document(doc
);
1205 g_signal_emit_by_name(geany_object
, "document-reload", doc
);
1206 ui_set_statusbar(TRUE
, _("File %s reloaded."), display_filename
);
1210 g_signal_emit_by_name(geany_object
, "document-open", doc
);
1211 /* For translators: this is the status window message for opening a file. %d is the number
1212 * of the newly opened file, %s indicates whether the file is opened read-only
1213 * (it is replaced with the string ", read-only"). */
1214 msgwin_status_add(_("File %s opened(%d%s)."),
1215 display_filename
, gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
)),
1216 (readonly
) ? _(", read-only") : "");
1220 g_free(display_filename
);
1221 g_free(utf8_filename
);
1222 g_free(locale_filename
);
1224 /* set the cursor position according to pos, cl_options.goto_line and cl_options.goto_column */
1225 pos
= set_cursor_position(doc
->editor
, pos
);
1226 /* now bring the file in front */
1227 editor_goto_pos(doc
->editor
, pos
, FALSE
);
1229 /* finally, let the editor widget grab the focus so you can start coding
1231 g_idle_add(on_idle_focus
, doc
);
1236 /* Takes a new line separated list of filename URIs and opens each file.
1237 * length is the length of the string */
1238 void document_open_file_list(const gchar
*data
, gsize length
)
1244 g_return_if_fail(data
!= NULL
);
1246 list
= g_strsplit(data
, utils_get_eol_char(utils_get_line_endings(data
, length
)), 0);
1248 for (i
= 0; list
[i
] != NULL
; i
++)
1250 filename
= g_filename_from_uri(list
[i
], NULL
, NULL
);
1251 if (G_UNLIKELY(filename
== NULL
))
1253 document_open_file(filename
, FALSE
, NULL
, NULL
);
1262 * Opens each file in the list @a filenames.
1263 * Internally, document_open_file() is called for every list item.
1265 * @param filenames A list of filenames to load, in locale encoding.
1266 * @param readonly Whether to open the document in read-only mode.
1267 * @param ft The filetype for the document or @c NULL to auto-detect the filetype.
1268 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1270 void document_open_files(const GSList
*filenames
, gboolean readonly
, GeanyFiletype
*ft
,
1271 const gchar
*forced_enc
)
1275 for (item
= filenames
; item
!= NULL
; item
= g_slist_next(item
))
1277 document_open_file(item
->data
, readonly
, ft
, forced_enc
);
1283 * Reloads the document with the specified file encoding
1284 * @a forced_enc or @c NULL to auto-detect the file encoding.
1286 * @param doc The document to reload.
1287 * @param forced_enc The file encoding to use or @c NULL to auto-detect the file encoding.
1289 * @return @c TRUE if the document was actually reloaded or @c FALSE otherwise.
1291 gboolean
document_reload_file(GeanyDocument
*doc
, const gchar
*forced_enc
)
1294 GeanyDocument
*new_doc
;
1296 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1298 /* try to set the cursor to the position before reloading */
1299 pos
= sci_get_current_position(doc
->editor
->sci
);
1300 new_doc
= document_open_file_full(doc
, NULL
, pos
, doc
->readonly
, doc
->file_type
, forced_enc
);
1302 return (new_doc
!= NULL
);
1306 static gboolean
document_update_timestamp(GeanyDocument
*doc
, const gchar
*locale_filename
)
1308 #ifndef USE_GIO_FILEMON
1311 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1313 /* stat the file to get the timestamp, otherwise on Windows the actual
1314 * timestamp can be ahead of time(NULL) */
1315 if (g_stat(locale_filename
, &st
) != 0)
1317 ui_set_statusbar(TRUE
, _("Could not open file %s (%s)"), doc
->file_name
,
1322 doc
->priv
->mtime
= st
.st_mtime
; /* get the modification time from file and keep it */
1328 /* Sets line and column to the given position byte_pos in the document.
1329 * byte_pos is the position counted in bytes, not characters */
1330 static void get_line_column_from_pos(GeanyDocument
*doc
, guint byte_pos
, gint
*line
, gint
*column
)
1335 /* for some reason we can use byte count instead of character count here */
1336 *line
= sci_get_line_from_position(doc
->editor
->sci
, byte_pos
);
1337 line_start
= sci_get_position_from_line(doc
->editor
->sci
, *line
);
1338 /* get the column in the line */
1339 *column
= byte_pos
- line_start
;
1341 /* any non-ASCII characters are encoded with two bytes(UTF-8, always in Scintilla), so
1342 * skip one byte(i++) and decrease the column number which is based on byte count */
1343 for (i
= line_start
; i
< (line_start
+ *column
); i
++)
1345 if (sci_get_char_at(doc
->editor
->sci
, i
) < 0)
1354 static void replace_header_filename(GeanyDocument
*doc
)
1358 struct Sci_TextToFind ttf
;
1360 g_return_if_fail(doc
!= NULL
);
1361 g_return_if_fail(doc
->file_type
!= NULL
);
1363 if (doc
->file_type
->extension
)
1364 filebase
= g_strconcat("\\<", GEANY_STRING_UNTITLED
, "\\.\\w+", NULL
);
1366 filebase
= g_strdup(GEANY_STRING_UNTITLED
);
1368 filename
= g_path_get_basename(doc
->file_name
);
1370 /* only search the first 3 lines */
1372 ttf
.chrg
.cpMax
= sci_get_position_from_line(doc
->editor
->sci
, 3);
1373 ttf
.lpstrText
= filebase
;
1375 if (search_find_text(doc
->editor
->sci
, SCFIND_MATCHCASE
| SCFIND_REGEXP
, &ttf
) != -1)
1377 sci_set_target_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1378 sci_set_target_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1379 sci_replace_target(doc
->editor
->sci
, filename
, FALSE
);
1387 * Renames the file in @a doc to @a new_filename. Only the file on disk is actually renamed,
1388 * you still have to call @ref document_save_file_as() to change the @a doc object.
1389 * It also stops monitoring for file changes to prevent receiving too many file change events
1390 * while renaming. File monitoring is setup again in @ref document_save_file_as().
1392 * @param doc The current document which should be renamed.
1393 * @param new_filename The new filename in UTF-8 encoding.
1397 void document_rename_file(GeanyDocument
*doc
, const gchar
*new_filename
)
1399 gchar
*old_locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1400 gchar
*new_locale_filename
= utils_get_locale_from_utf8(new_filename
);
1403 /* stop file monitoring to avoid getting events for deleting/creating files,
1404 * it's re-setup in document_save_file_as() */
1405 document_stop_file_monitoring(doc
);
1407 result
= g_rename(old_locale_filename
, new_locale_filename
);
1410 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
,
1411 _("Error renaming file."), g_strerror(errno
));
1413 g_free(old_locale_filename
);
1414 g_free(new_locale_filename
);
1418 /* Return TRUE if the document doesn't have a full filename set.
1419 * This makes filenames without a path show the save as dialog, e.g. for file templates.
1420 * Otherwise just use the set filename instead of asking the user - e.g. for command-line
1422 gboolean
document_need_save_as(GeanyDocument
*doc
)
1424 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1426 return (doc
->file_name
== NULL
|| !g_path_is_absolute(doc
->file_name
));
1431 * Saves the document, detecting the filetype.
1433 * @param doc The document for the file to save.
1434 * @param utf8_fname The new name for the document, in UTF-8, or NULL.
1435 * @return @c TRUE if the file was saved or @c FALSE if the file could not be saved.
1437 * @see document_save_file().
1441 gboolean
document_save_file_as(GeanyDocument
*doc
, const gchar
*utf8_fname
)
1445 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1447 if (utf8_fname
!= NULL
)
1448 setptr(doc
->file_name
, g_strdup(utf8_fname
));
1450 /* reset real path, it's retrieved again in document_save() */
1451 setptr(doc
->real_path
, NULL
);
1453 /* detect filetype */
1454 if (doc
->file_type
->id
== GEANY_FILETYPES_NONE
)
1456 GeanyFiletype
*ft
= filetypes_detect_from_document(doc
);
1458 document_set_filetype(doc
, ft
);
1459 if (document_get_current() == doc
)
1461 ignore_callback
= TRUE
;
1462 filetypes_select_radio_item(doc
->file_type
);
1463 ignore_callback
= FALSE
;
1466 replace_header_filename(doc
);
1468 ret
= document_save_file(doc
, TRUE
);
1470 /* file monitoring support, add file monitoring after the file has been saved
1471 * to ignore any earlier events */
1472 monitor_file_setup(doc
);
1473 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1476 ui_add_recent_document(doc
);
1481 static gsize
save_convert_to_encoding(GeanyDocument
*doc
, gchar
**data
, gsize
*len
)
1483 GError
*conv_error
= NULL
;
1484 gchar
* conv_file_contents
= NULL
;
1488 g_return_val_if_fail(data
!= NULL
|| *data
== NULL
, FALSE
);
1489 g_return_val_if_fail(len
!= NULL
, FALSE
);
1491 /* try to convert it from UTF-8 to original encoding */
1492 conv_file_contents
= g_convert(*data
, *len
- 1, doc
->encoding
, "UTF-8",
1493 &bytes_read
, &conv_len
, &conv_error
);
1495 if (conv_error
!= NULL
)
1497 gchar
*text
= g_strdup_printf(
1498 _("An error occurred while converting the file from UTF-8 in \"%s\". The file remains unsaved."),
1502 if (conv_error
->code
== G_CONVERT_ERROR_ILLEGAL_SEQUENCE
)
1504 gchar
*context
= NULL
;
1508 /* don't read over the doc length */
1509 gint max_len
= MIN((gint
)bytes_read
+ 6, (gint
)*len
- 1);
1510 context
= g_malloc(7); /* read 6 bytes from Sci + '\0' */
1511 sci_get_text_range(doc
->editor
->sci
, bytes_read
, max_len
, context
);
1513 /* take only one valid Unicode character from the context and discard the leftover */
1514 unic
= g_utf8_get_char_validated(context
, -1);
1515 context_len
= g_unichar_to_utf8(unic
, context
);
1516 context
[context_len
] = '\0';
1517 get_line_column_from_pos(doc
, bytes_read
, &line
, &column
);
1519 error_text
= g_strdup_printf(
1520 _("Error message: %s\nThe error occurred at \"%s\" (line: %d, column: %d)."),
1521 conv_error
->message
, context
, line
+ 1, column
);
1525 error_text
= g_strdup_printf(_("Error message: %s."), conv_error
->message
);
1527 geany_debug("encoding error: %s", conv_error
->message
);
1528 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, text
, error_text
);
1529 g_error_free(conv_error
);
1537 *data
= conv_file_contents
;
1544 static gchar
*write_data_to_disk(const gchar
*locale_filename
,
1545 const gchar
*data
, gint len
)
1547 GError
*error
= NULL
;
1549 if (file_prefs
.use_safe_file_saving
)
1551 /* Use old GLib API for safe saving (GVFS-safe, but alters ownership and permissons).
1552 * This is the only option that handles disk space exhaustion. */
1553 if (g_file_set_contents(locale_filename
, data
, len
, &error
))
1554 geany_debug("Wrote %s with g_file_set_contents().", locale_filename
);
1556 else if (file_prefs
.use_gio_unsafe_file_saving
)
1560 /* Use GIO API to save file (GVFS-safe)
1561 * It is best in most GVFS setups but don't seem to work correctly on some more complex
1562 * setups (saving from some VM to their host, over some SMB shares, etc.) */
1563 fp
= g_file_new_for_path(locale_filename
);
1564 g_file_replace_contents(fp
, data
, len
, NULL
, file_prefs
.gio_unsafe_save_backup
,
1565 G_FILE_CREATE_NONE
, NULL
, NULL
, &error
);
1572 gchar
*display_name
= g_filename_display_name(locale_filename
);
1574 /* Use POSIX API for unsafe saving (GVFS-unsafe) */
1575 /* The error handling is taken from glib-2.26.0 gfileutils.c */
1577 fp
= g_fopen(locale_filename
, "wb");
1584 g_file_error_from_errno(save_errno
),
1585 _("Failed to open file '%s' for writing: fopen() failed: %s"),
1587 g_strerror(save_errno
));
1594 bytes_written
= fwrite(data
, sizeof(gchar
), len
, fp
);
1596 if (len
!= bytes_written
)
1602 g_file_error_from_errno(save_errno
),
1603 _("Failed to write file '%s': fwrite() failed: %s"),
1605 g_strerror(save_errno
));
1609 /* preserve the fwrite() error if any */
1610 if (fclose(fp
) != 0 && error
== NULL
)
1616 g_file_error_from_errno(save_errno
),
1617 _("Failed to close file '%s': fclose() failed: %s"),
1619 g_strerror(save_errno
));
1623 g_free(display_name
);
1627 gchar
*msg
= g_strdup(error
->message
);
1628 g_error_free(error
);
1629 /* geany will warn about file truncation for unsafe saving below */
1636 static gchar
*save_doc(GeanyDocument
*doc
, const gchar
*locale_filename
,
1637 const gchar
*data
, gint len
)
1641 g_return_val_if_fail(doc
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1642 g_return_val_if_fail(data
!= NULL
, g_strdup(g_strerror(EINVAL
)));
1644 err
= write_data_to_disk(locale_filename
, data
, len
);
1648 /* now the file is on disk, set real_path */
1649 if (doc
->real_path
== NULL
)
1651 doc
->real_path
= tm_get_real_path(locale_filename
);
1652 doc
->priv
->is_remote
= utils_is_remote_path(locale_filename
);
1653 monitor_file_setup(doc
);
1660 * Saves the document.
1661 * Also shows the Save As dialog if necessary.
1662 * If the file is not modified, this function may do nothing unless @a force is set to @c TRUE.
1664 * Saving may include replacing tabs by spaces,
1665 * stripping trailing spaces and adding a final new line at the end of the file, depending
1666 * on user preferences. Then the @c "document-before-save" signal is emitted,
1667 * allowing plugins to modify the document before it is saved, and data is
1668 * actually written to disk.
1670 * On successful saving:
1671 * - GeanyDocument::real_path is set.
1672 * - The filetype is set again or auto-detected if it wasn't set yet.
1673 * - The @c "document-save" signal is emitted for plugins.
1675 * @warning You should ensure @c doc->file_name has an absolute path unless you want the
1676 * Save As dialog to be shown. A @c NULL value also shows the dialog. This behaviour was
1677 * added in Geany 1.22.
1679 * @param doc The document to save.
1680 * @param force Whether to save the file even if it is not modified.
1682 * @return @c TRUE if the file was saved or @c FALSE if the file could not or should not be saved.
1684 gboolean
document_save_file(GeanyDocument
*doc
, gboolean force
)
1689 gchar
*locale_filename
;
1691 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1693 if (document_need_save_as(doc
))
1695 /* ensure doc is the current tab before showing the dialog */
1696 document_show_tab(doc
);
1697 return dialogs_show_save_as();
1700 /* the "changed" flag should exclude the "readonly" flag, but check it anyway for safety */
1701 if (! force
&& ! ui_prefs
.allow_always_save
&& (! doc
->changed
|| doc
->readonly
))
1704 /* replaces tabs by spaces but only if the current file is not a Makefile */
1705 if (file_prefs
.replace_tabs
&& doc
->file_type
->id
!= GEANY_FILETYPES_MAKE
)
1706 editor_replace_tabs(doc
->editor
);
1707 /* strip trailing spaces */
1708 if (file_prefs
.strip_trailing_spaces
)
1709 editor_strip_trailing_spaces(doc
->editor
);
1710 /* ensure the file has a newline at the end */
1711 if (file_prefs
.final_new_line
)
1712 editor_ensure_final_newline(doc
->editor
);
1713 /* ensure newlines are consistent */
1714 if (file_prefs
.ensure_convert_new_lines
)
1715 sci_convert_eols(doc
->editor
->sci
, sci_get_eol_mode(doc
->editor
->sci
));
1717 /* notify plugins which may wish to modify the document before it's saved */
1718 g_signal_emit_by_name(geany_object
, "document-before-save", doc
);
1720 len
= sci_get_length(doc
->editor
->sci
) + 1;
1721 if (doc
->has_bom
&& encodings_is_unicode_charset(doc
->encoding
))
1722 { /* always write a UTF-8 BOM because in this moment the text itself is still in UTF-8
1723 * encoding, it will be converted to doc->encoding below and this conversion
1724 * also changes the BOM */
1725 data
= (gchar
*) g_malloc(len
+ 3); /* 3 chars for BOM */
1726 data
[0] = (gchar
) 0xef;
1727 data
[1] = (gchar
) 0xbb;
1728 data
[2] = (gchar
) 0xbf;
1729 sci_get_text(doc
->editor
->sci
, len
, data
+ 3);
1734 data
= (gchar
*) g_malloc(len
);
1735 sci_get_text(doc
->editor
->sci
, len
, data
);
1738 /* save in original encoding, skip when it is already UTF-8 or has the encoding "None" */
1739 if (doc
->encoding
!= NULL
&& ! utils_str_equal(doc
->encoding
, "UTF-8") &&
1740 ! utils_str_equal(doc
->encoding
, encodings
[GEANY_ENCODING_NONE
].charset
))
1742 if (! save_convert_to_encoding(doc
, &data
, &len
))
1753 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
1755 /* ignore file changed notification when the file is written */
1756 doc
->priv
->file_disk_status
= FILE_IGNORE
;
1758 /* actually write the content of data to the file on disk */
1759 errmsg
= save_doc(doc
, locale_filename
, data
, len
);
1764 ui_set_statusbar(TRUE
, _("Error saving file (%s)."), errmsg
);
1766 if (!file_prefs
.use_safe_file_saving
)
1769 g_strdup_printf(_("%s\n\nThe file on disk may now be truncated!"), errmsg
));
1771 dialogs_show_msgbox_with_secondary(GTK_MESSAGE_ERROR
, _("Error saving file."), errmsg
);
1772 doc
->priv
->file_disk_status
= FILE_OK
;
1774 g_free(locale_filename
);
1779 /* store the opened encoding for undo/redo */
1780 store_saved_encoding(doc
);
1782 /* ignore the following things if we are quitting */
1783 if (! main_status
.quitting
)
1785 sci_set_savepoint(doc
->editor
->sci
);
1787 if (file_prefs
.disk_check_timeout
> 0)
1788 document_update_timestamp(doc
, locale_filename
);
1790 /* update filetype-related things */
1791 document_set_filetype(doc
, doc
->file_type
);
1793 document_update_tab_label(doc
);
1795 msgwin_status_add(_("File %s saved."), doc
->file_name
);
1796 ui_update_statusbar(doc
, -1);
1798 vte_cwd((doc
->real_path
!= NULL
) ? doc
->real_path
: doc
->file_name
, FALSE
);
1801 g_free(locale_filename
);
1803 g_signal_emit_by_name(geany_object
, "document-save", doc
);
1809 /* special search function, used from the find entry in the toolbar
1810 * return TRUE if text was found otherwise FALSE
1811 * return also TRUE if text is empty */
1812 gboolean
document_search_bar_find(GeanyDocument
*doc
, const gchar
*text
, gint flags
, gboolean inc
,
1815 gint start_pos
, search_pos
;
1816 struct Sci_TextToFind ttf
;
1818 g_return_val_if_fail(text
!= NULL
, FALSE
);
1819 g_return_val_if_fail(doc
!= NULL
, FALSE
);
1823 start_pos
= (inc
|| backwards
) ? sci_get_selection_start(doc
->editor
->sci
) :
1824 sci_get_selection_end(doc
->editor
->sci
); /* equal if no selection */
1826 /* search cursor to end or start */
1827 ttf
.chrg
.cpMin
= start_pos
;
1828 ttf
.chrg
.cpMax
= backwards
? 0 : sci_get_length(doc
->editor
->sci
);
1829 ttf
.lpstrText
= (gchar
*)text
;
1830 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1832 /* if no match, search start (or end) to cursor */
1833 if (search_pos
== -1)
1837 ttf
.chrg
.cpMin
= sci_get_length(doc
->editor
->sci
);
1838 ttf
.chrg
.cpMax
= start_pos
;
1843 ttf
.chrg
.cpMax
= start_pos
+ strlen(text
);
1845 search_pos
= sci_find_text(doc
->editor
->sci
, flags
, &ttf
);
1848 if (search_pos
!= -1)
1850 gint line
= sci_get_line_from_position(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1852 /* unfold maybe folded results */
1853 sci_ensure_line_is_visible(doc
->editor
->sci
, line
);
1855 sci_set_selection_start(doc
->editor
->sci
, ttf
.chrgText
.cpMin
);
1856 sci_set_selection_end(doc
->editor
->sci
, ttf
.chrgText
.cpMax
);
1858 if (! editor_line_in_view(doc
->editor
, line
))
1859 { /* we need to force scrolling in case the cursor is outside of the current visible area
1860 * GeanyDocument::scroll_percent doesn't work because sci isn't always updated
1861 * while searching */
1862 editor_scroll_to_line(doc
->editor
, -1, 0.3F
);
1865 sci_scroll_caret(doc
->editor
->sci
); /* may need horizontal scrolling */
1872 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), text
);
1875 sci_goto_pos(doc
->editor
->sci
, start_pos
, FALSE
); /* clear selection */
1881 /* General search function, used from the find dialog.
1882 * Returns -1 on failure or the start position of the matching text.
1883 * Will skip past any selection, ignoring it.
1885 * @param text Text to find.
1886 * @param original_text Text as it was entered by user, or @c NULL to use @c text
1888 gint
document_find_text(GeanyDocument
*doc
, const gchar
*text
, const gchar
*original_text
,
1889 gint flags
, gboolean search_backwards
, gboolean scroll
, GtkWidget
*parent
)
1891 gint selection_end
, selection_start
, search_pos
;
1893 g_return_val_if_fail(doc
!= NULL
&& text
!= NULL
, -1);
1897 /* Sci doesn't support searching backwards with a regex */
1898 if (flags
& SCFIND_REGEXP
)
1899 search_backwards
= FALSE
;
1902 original_text
= text
;
1904 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
1905 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
1906 if ((selection_end
- selection_start
) > 0)
1907 { /* there's a selection so go to the end */
1908 if (search_backwards
)
1909 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
1911 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
1914 sci_set_search_anchor(doc
->editor
->sci
);
1915 if (search_backwards
)
1916 search_pos
= sci_search_prev(doc
->editor
->sci
, flags
, text
);
1918 search_pos
= search_find_next(doc
->editor
->sci
, text
, flags
);
1920 if (search_pos
!= -1)
1922 /* unfold maybe folded results */
1923 sci_ensure_line_is_visible(doc
->editor
->sci
,
1924 sci_get_line_from_position(doc
->editor
->sci
, search_pos
));
1926 doc
->editor
->scroll_percent
= 0.3F
;
1930 gint sci_len
= sci_get_length(doc
->editor
->sci
);
1932 /* if we just searched the whole text, give up searching. */
1933 if ((selection_end
== 0 && ! search_backwards
) ||
1934 (selection_end
== sci_len
&& search_backwards
))
1936 ui_set_statusbar(FALSE
, _("\"%s\" was not found."), original_text
);
1941 /* we searched only part of the document, so ask whether to wraparound. */
1942 if (search_prefs
.suppress_dialogs
||
1943 dialogs_show_question_full(parent
, GTK_STOCK_FIND
, GTK_STOCK_CANCEL
,
1944 _("Wrap search and find again?"), _("\"%s\" was not found."), original_text
))
1948 sci_set_current_position(doc
->editor
->sci
, (search_backwards
) ? sci_len
: 0, FALSE
);
1949 ret
= document_find_text(doc
, text
, original_text
, flags
, search_backwards
, scroll
, parent
);
1951 { /* return to original cursor position if not found */
1952 sci_set_current_position(doc
->editor
->sci
, selection_start
, FALSE
);
1961 /* Replaces the selection if it matches, otherwise just finds the next match.
1962 * Returns: start of replaced text, or -1 if no replacement was made
1964 * @param find_text Text to find.
1965 * @param original_find_text Text to find as it was entered by user, or @c NULL to use @c find_text
1967 gint
document_replace_text(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*original_find_text
,
1968 const gchar
*replace_text
, gint flags
, gboolean search_backwards
)
1970 gint selection_end
, selection_start
, search_pos
;
1972 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, -1);
1977 /* Sci doesn't support searching backwards with a regex */
1978 if (flags
& SCFIND_REGEXP
)
1979 search_backwards
= FALSE
;
1981 if (!original_find_text
)
1982 original_find_text
= find_text
;
1984 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
1985 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
1986 if (selection_end
== selection_start
)
1988 /* no selection so just find the next match */
1989 document_find_text(doc
, find_text
, original_find_text
, flags
, search_backwards
, TRUE
, NULL
);
1992 /* there's a selection so go to the start before finding to search through it
1993 * this ensures there is a match */
1994 if (search_backwards
)
1995 sci_goto_pos(doc
->editor
->sci
, selection_end
, TRUE
);
1997 sci_goto_pos(doc
->editor
->sci
, selection_start
, TRUE
);
1999 search_pos
= document_find_text(doc
, find_text
, original_find_text
, flags
, search_backwards
, TRUE
, NULL
);
2000 /* return if the original selected text did not match (at the start of the selection) */
2001 if (search_pos
!= selection_start
)
2004 if (search_pos
!= -1)
2007 /* search next/prev will select matching text, which we use to set the replace target */
2008 sci_target_from_selection(doc
->editor
->sci
);
2009 replace_len
= search_replace_target(doc
->editor
->sci
, replace_text
, flags
& SCFIND_REGEXP
);
2010 /* select the replacement - find text will skip past the selected text */
2011 sci_set_selection_start(doc
->editor
->sci
, search_pos
);
2012 sci_set_selection_end(doc
->editor
->sci
, search_pos
+ replace_len
);
2016 /* no match in the selection */
2023 static void show_replace_summary(GeanyDocument
*doc
, gint count
, const gchar
*original_find_text
,
2024 const gchar
*original_replace_text
)
2030 ui_set_statusbar(FALSE
, _("No matches found for \"%s\"."), original_find_text
);
2034 filename
= g_path_get_basename(DOC_FILENAME(doc
));
2035 ui_set_statusbar(TRUE
, ngettext(
2036 "%s: replaced %d occurrence of \"%s\" with \"%s\".",
2037 "%s: replaced %d occurrences of \"%s\" with \"%s\".",
2038 count
), filename
, count
, original_find_text
, original_replace_text
);
2043 /* Replace all text matches in a certain range within document.
2044 * If not NULL, *new_range_end is set to the new range endpoint after replacing,
2045 * or -1 if no text was found.
2046 * scroll_to_match is whether to scroll the last replacement in view (which also
2047 * clears the selection).
2048 * Returns: the number of replacements made. */
2050 document_replace_range(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2051 gint flags
, gint start
, gint end
, gboolean scroll_to_match
, gint
*new_range_end
)
2054 struct Sci_TextToFind ttf
;
2055 ScintillaObject
*sci
;
2057 if (new_range_end
!= NULL
)
2058 *new_range_end
= -1;
2060 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, 0);
2062 if (! *find_text
|| doc
->readonly
)
2065 sci
= doc
->editor
->sci
;
2067 ttf
.chrg
.cpMin
= start
;
2068 ttf
.chrg
.cpMax
= end
;
2069 ttf
.lpstrText
= (gchar
*)find_text
;
2071 sci_start_undo_action(sci
);
2072 count
= search_replace_range(sci
, &ttf
, flags
, replace_text
);
2073 sci_end_undo_action(sci
);
2076 { /* scroll last match in view, will destroy the existing selection */
2077 if (scroll_to_match
)
2078 sci_goto_pos(sci
, ttf
.chrg
.cpMin
, TRUE
);
2080 if (new_range_end
!= NULL
)
2081 *new_range_end
= ttf
.chrg
.cpMax
;
2087 void document_replace_sel(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2088 const gchar
*original_find_text
, const gchar
*original_replace_text
, gint flags
)
2090 gint selection_end
, selection_start
, selection_mode
, selected_lines
, last_line
= 0;
2091 gint max_column
= 0, count
= 0;
2092 gboolean replaced
= FALSE
;
2094 g_return_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
);
2099 selection_start
= sci_get_selection_start(doc
->editor
->sci
);
2100 selection_end
= sci_get_selection_end(doc
->editor
->sci
);
2101 /* do we have a selection? */
2102 if ((selection_end
- selection_start
) == 0)
2108 selection_mode
= sci_get_selection_mode(doc
->editor
->sci
);
2109 selected_lines
= sci_get_lines_selected(doc
->editor
->sci
);
2110 /* handle rectangle, multi line selections (it doesn't matter on a single line) */
2111 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2113 gint first_line
, line
;
2115 sci_start_undo_action(doc
->editor
->sci
);
2117 first_line
= sci_get_line_from_position(doc
->editor
->sci
, selection_start
);
2118 /* Find the last line with chars selected (not EOL char) */
2119 last_line
= sci_get_line_from_position(doc
->editor
->sci
,
2120 selection_end
- editor_get_eol_char_len(doc
->editor
));
2121 last_line
= MAX(first_line
, last_line
);
2122 for (line
= first_line
; line
< (first_line
+ selected_lines
); line
++)
2124 gint line_start
= sci_get_pos_at_line_sel_start(doc
->editor
->sci
, line
);
2125 gint line_end
= sci_get_pos_at_line_sel_end(doc
->editor
->sci
, line
);
2127 /* skip line if there is no selection */
2128 if (line_start
!= INVALID_POSITION
)
2130 /* don't let document_replace_range() scroll to match to keep our selection */
2133 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2134 line_start
, line_end
, FALSE
, &new_sel_end
);
2135 if (new_sel_end
!= -1)
2138 /* this gets the greatest column within the selection after replacing */
2139 max_column
= MAX(max_column
,
2140 new_sel_end
- sci_get_position_from_line(doc
->editor
->sci
, line
));
2144 sci_end_undo_action(doc
->editor
->sci
);
2146 else /* handle normal line selection */
2148 count
+= document_replace_range(doc
, find_text
, replace_text
, flags
,
2149 selection_start
, selection_end
, TRUE
, &selection_end
);
2150 if (selection_end
!= -1)
2155 { /* update the selection for the new endpoint */
2157 if (selection_mode
== SC_SEL_RECTANGLE
&& selected_lines
> 1)
2159 /* now we can scroll to the selection and destroy it because we rebuild it later */
2160 /*sci_goto_pos(doc->editor->sci, selection_start, FALSE);*/
2162 /* Note: the selection will be wrapped to last_line + 1 if max_column is greater than
2163 * the highest column on the last line. The wrapped selection is completely different
2164 * from the original one, so skip the selection at all */
2165 /* TODO is there a better way to handle the wrapped selection? */
2166 if ((sci_get_line_length(doc
->editor
->sci
, last_line
) - 1) >= max_column
)
2167 { /* for keeping and adjusting the selection in multi line rectangle selection we
2168 * need the last line of the original selection and the greatest column number after
2169 * replacing and set the selection end to the last line at the greatest column */
2170 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2171 sci_set_selection_end(doc
->editor
->sci
,
2172 sci_get_position_from_line(doc
->editor
->sci
, last_line
) + max_column
);
2173 sci_set_selection_mode(doc
->editor
->sci
, selection_mode
);
2178 sci_set_selection_start(doc
->editor
->sci
, selection_start
);
2179 sci_set_selection_end(doc
->editor
->sci
, selection_end
);
2182 else /* no replacements */
2185 show_replace_summary(doc
, count
, original_find_text
, original_replace_text
);
2189 /* returns number of replacements made. */
2190 gint
document_replace_all(GeanyDocument
*doc
, const gchar
*find_text
, const gchar
*replace_text
,
2191 const gchar
*original_find_text
, const gchar
*original_replace_text
, gint flags
)
2194 g_return_val_if_fail(doc
!= NULL
&& find_text
!= NULL
&& replace_text
!= NULL
, FALSE
);
2199 len
= sci_get_length(doc
->editor
->sci
);
2200 count
= document_replace_range(
2201 doc
, find_text
, replace_text
, flags
, 0, len
, TRUE
, NULL
);
2203 show_replace_summary(doc
, count
, original_find_text
, original_replace_text
);
2209 * Parses or re-parses the document's buffer and updates the type
2210 * keywords and symbol list.
2212 * @param doc The document.
2214 void document_update_tags(GeanyDocument
*doc
)
2218 GString
*keywords_str
;
2222 g_return_if_fail(DOC_VALID(doc
));
2223 g_return_if_fail(app
->tm_workspace
!= NULL
);
2225 /* early out if it's a new file or doesn't support tags */
2226 if (! doc
->file_name
|| ! doc
->file_type
|| !filetype_has_tags(doc
->file_type
))
2228 /* We must call sidebar_update_tag_list() before returning,
2229 * to ensure that the symbol list is always updated properly (e.g.
2230 * when creating a new document with a partial filename set. */
2231 sidebar_update_tag_list(doc
, FALSE
);
2235 /* create a new TM file if there isn't one yet */
2238 gchar
*locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2241 /* lookup the name rather than using filetype name to support custom filetypes */
2242 name
= tm_source_file_get_lang_name(doc
->file_type
->lang
);
2243 doc
->tm_file
= tm_source_file_new(locale_filename
, FALSE
, name
);
2244 g_free(locale_filename
);
2246 if (doc
->tm_file
&& !tm_workspace_add_object(doc
->tm_file
))
2248 tm_work_object_free(doc
->tm_file
);
2249 doc
->tm_file
= NULL
;
2253 /* early out if there's no work object and we couldn't create one */
2254 if (doc
->tm_file
== NULL
)
2256 /* We must call sidebar_update_tag_list() before returning,
2257 * to ensure that the symbol list is always updated properly (e.g.
2258 * when creating a new document with a partial filename set. */
2259 sidebar_update_tag_list(doc
, FALSE
);
2263 /* Parse Scintilla's buffer directly using TagManager
2264 * Note: this buffer *MUST NOT* be modified */
2265 len
= sci_get_length(doc
->editor
->sci
);
2266 buffer_ptr
= (guchar
*) scintilla_send_message(doc
->editor
->sci
, SCI_GETCHARACTERPOINTER
, 0, 0);
2267 tm_source_file_buffer_update(doc
->tm_file
, buffer_ptr
, len
, TRUE
);
2269 sidebar_update_tag_list(doc
, TRUE
);
2271 /* some filetypes support type keywords (such as struct names), but not
2272 * necessarily all filetypes for a particular scintilla lexer. this
2273 * tells us whether the filetype supports keywords, and if so
2274 * which index to use for the scintilla keywords set. */
2275 switch (doc
->file_type
->id
)
2277 case GEANY_FILETYPES_C
:
2278 case GEANY_FILETYPES_CPP
:
2279 case GEANY_FILETYPES_CS
:
2280 case GEANY_FILETYPES_D
:
2281 case GEANY_FILETYPES_JAVA
:
2282 case GEANY_FILETYPES_OBJECTIVEC
:
2283 case GEANY_FILETYPES_VALA
:
2286 /* index of the keyword set in the Scintilla lexer, for
2287 * example in LexCPP.cxx, see "cppWordLists" global array.
2288 * TODO: this magic number should be a member of the filetype */
2293 return; /* early out if type keywords are not supported */
2296 /* get any type keywords and tell scintilla about them
2297 * this will cause the type keywords to be colourized in scintilla */
2298 keywords_str
= symbols_find_tags_as_string(app
->tm_workspace
->work_object
.tags_array
,
2299 TM_GLOBAL_TYPE_MASK
, doc
->file_type
->lang
);
2302 keywords
= g_string_free(keywords_str
, FALSE
);
2303 sci_set_keywords(doc
->editor
->sci
, keyword_idx
, keywords
);
2309 static gboolean
on_document_update_tag_list_idle(gpointer data
)
2311 GeanyDocument
*doc
= data
;
2313 if (! DOC_VALID(doc
))
2316 if (! main_status
.quitting
)
2317 document_update_tags(doc
);
2319 doc
->priv
->tag_list_update_source
= 0;
2321 /* don't update the tags until another modification of the buffer */
2326 void document_update_tag_list_in_idle(GeanyDocument
*doc
)
2328 if (editor_prefs
.autocompletion_update_freq
<= 0 || ! filetype_has_tags(doc
->file_type
))
2331 /* prevent "stacking up" callback handlers, we only need one to run soon */
2332 if (doc
->priv
->tag_list_update_source
!= 0)
2333 g_source_remove(doc
->priv
->tag_list_update_source
);
2335 doc
->priv
->tag_list_update_source
= g_timeout_add_full(G_PRIORITY_LOW
,
2336 editor_prefs
.autocompletion_update_freq
, on_document_update_tag_list_idle
, doc
, NULL
);
2340 static void document_load_config(GeanyDocument
*doc
, GeanyFiletype
*type
,
2341 gboolean filetype_changed
)
2343 g_return_if_fail(doc
);
2345 type
= filetypes
[GEANY_FILETYPES_NONE
];
2347 if (filetype_changed
)
2349 doc
->file_type
= type
;
2351 /* delete tm file object to force creation of a new one */
2352 if (doc
->tm_file
!= NULL
)
2354 tm_workspace_remove_object(doc
->tm_file
, TRUE
, TRUE
);
2355 doc
->tm_file
= NULL
;
2357 /* load tags files before highlighting (some lexers highlight global typenames) */
2358 if (type
->id
!= GEANY_FILETYPES_NONE
)
2359 symbols_global_tags_loaded(type
->id
);
2361 highlighting_set_styles(doc
->editor
->sci
, type
);
2362 editor_set_indentation_guides(doc
->editor
);
2363 build_menu_update(doc
);
2364 queue_colourise(doc
);
2365 doc
->priv
->symbol_list_sort_mode
= type
->priv
->symbol_list_sort_mode
;
2368 document_update_tags(doc
);
2372 /** Sets the filetype of the document (which controls syntax highlighting and tags)
2373 * @param doc The document to use.
2374 * @param type The filetype. */
2375 void document_set_filetype(GeanyDocument
*doc
, GeanyFiletype
*type
)
2377 gboolean ft_changed
;
2378 GeanyFiletype
*old_ft
;
2380 g_return_if_fail(doc
);
2382 type
= filetypes
[GEANY_FILETYPES_NONE
];
2384 old_ft
= doc
->file_type
;
2385 geany_debug("%s : %s (%s)",
2386 (doc
->file_name
!= NULL
) ? doc
->file_name
: "unknown",
2388 (doc
->encoding
!= NULL
) ? doc
->encoding
: "unknown");
2390 ft_changed
= (doc
->file_type
!= type
); /* filetype has changed */
2391 document_load_config(doc
, type
, ft_changed
);
2395 const GeanyIndentPrefs
*iprefs
= editor_get_indent_prefs(NULL
);
2397 /* assume that if previous filetype was none and the settings are the default ones, this
2398 * is the first time the filetype is carefully set, so we should apply indent settings */
2399 if (old_ft
&& old_ft
->id
== GEANY_FILETYPES_NONE
&&
2400 doc
->editor
->indent_type
== iprefs
->type
&&
2401 doc
->editor
->indent_width
== iprefs
->width
)
2403 document_apply_indent_settings(doc
);
2404 ui_document_show_hide(doc
);
2407 sidebar_openfiles_update(doc
); /* to update the icon */
2408 g_signal_emit_by_name(geany_object
, "document-filetype-set", doc
, old_ft
);
2413 void document_reload_config(GeanyDocument
*doc
)
2415 document_load_config(doc
, doc
->file_type
, TRUE
);
2420 * Sets the encoding of a document.
2421 * This function only set the encoding of the %document, it does not any conversions. The new
2422 * encoding is used when e.g. saving the file.
2424 * @param doc The document to use.
2425 * @param new_encoding The encoding to be set for the document.
2427 void document_set_encoding(GeanyDocument
*doc
, const gchar
*new_encoding
)
2429 if (doc
== NULL
|| new_encoding
== NULL
||
2430 utils_str_equal(new_encoding
, doc
->encoding
))
2433 g_free(doc
->encoding
);
2434 doc
->encoding
= g_strdup(new_encoding
);
2436 ui_update_statusbar(doc
, -1);
2437 gtk_widget_set_sensitive(ui_lookup_widget(main_widgets
.window
, "menu_write_unicode_bom1"),
2438 encodings_is_unicode_charset(doc
->encoding
));
2442 /* own Undo / Redo implementation to be able to undo / redo changes
2443 * to the encoding or the Unicode BOM (which are Scintilla independet).
2444 * All Scintilla events are stored in the undo / redo buffer and are passed through. */
2446 /* Clears the Undo and Redo buffer (to be called when reloading or closing the document) */
2447 void document_undo_clear(GeanyDocument
*doc
)
2451 while (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0)
2453 a
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2454 if (G_LIKELY(a
!= NULL
))
2458 case UNDO_ENCODING
: g_free(a
->data
); break;
2464 doc
->priv
->undo_actions
= NULL
;
2466 while (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0)
2468 a
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2469 if (G_LIKELY(a
!= NULL
))
2473 case UNDO_ENCODING
: g_free(a
->data
); break;
2479 doc
->priv
->redo_actions
= NULL
;
2481 if (! main_status
.quitting
&& doc
->editor
!= NULL
)
2482 document_set_text_changed(doc
, FALSE
);
2486 void document_undo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2488 undo_action
*action
;
2490 g_return_if_fail(doc
!= NULL
);
2492 action
= g_new0(undo_action
, 1);
2493 action
->type
= type
;
2494 action
->data
= data
;
2496 g_trash_stack_push(&doc
->priv
->undo_actions
, action
);
2498 document_set_text_changed(doc
, TRUE
);
2499 ui_update_popup_reundo_items(doc
);
2503 gboolean
document_can_undo(GeanyDocument
*doc
)
2505 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2507 if (g_trash_stack_height(&doc
->priv
->undo_actions
) > 0 || sci_can_undo(doc
->editor
->sci
))
2514 static void update_changed_state(GeanyDocument
*doc
)
2517 (sci_is_modified(doc
->editor
->sci
) ||
2518 doc
->has_bom
!= doc
->priv
->saved_encoding
.has_bom
||
2519 ! utils_str_equal(doc
->encoding
, doc
->priv
->saved_encoding
.encoding
));
2520 document_set_text_changed(doc
, doc
->changed
);
2524 void document_undo(GeanyDocument
*doc
)
2526 undo_action
*action
;
2528 g_return_if_fail(doc
!= NULL
);
2530 action
= g_trash_stack_pop(&doc
->priv
->undo_actions
);
2532 if (G_UNLIKELY(action
== NULL
))
2534 /* fallback, should not be necessary */
2535 geany_debug("%s: fallback used", G_STRFUNC
);
2536 sci_undo(doc
->editor
->sci
);
2540 switch (action
->type
)
2542 case UNDO_SCINTILLA
:
2544 document_redo_add(doc
, UNDO_SCINTILLA
, NULL
);
2546 sci_undo(doc
->editor
->sci
);
2551 document_redo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2553 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2554 ui_update_statusbar(doc
, -1);
2555 ui_document_show_hide(doc
);
2560 /* use the "old" encoding */
2561 document_redo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2563 document_set_encoding(doc
, (const gchar
*)action
->data
);
2565 ignore_callback
= TRUE
;
2566 encodings_select_radio_item((const gchar
*)action
->data
);
2567 ignore_callback
= FALSE
;
2569 g_free(action
->data
);
2575 g_free(action
); /* free the action which was taken from the stack */
2577 update_changed_state(doc
);
2578 ui_update_popup_reundo_items(doc
);
2582 gboolean
document_can_redo(GeanyDocument
*doc
)
2584 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2586 if (g_trash_stack_height(&doc
->priv
->redo_actions
) > 0 || sci_can_redo(doc
->editor
->sci
))
2593 void document_redo(GeanyDocument
*doc
)
2595 undo_action
*action
;
2597 g_return_if_fail(doc
!= NULL
);
2599 action
= g_trash_stack_pop(&doc
->priv
->redo_actions
);
2601 if (G_UNLIKELY(action
== NULL
))
2603 /* fallback, should not be necessary */
2604 geany_debug("%s: fallback used", G_STRFUNC
);
2605 sci_redo(doc
->editor
->sci
);
2609 switch (action
->type
)
2611 case UNDO_SCINTILLA
:
2613 document_undo_add(doc
, UNDO_SCINTILLA
, NULL
);
2615 sci_redo(doc
->editor
->sci
);
2620 document_undo_add(doc
, UNDO_BOM
, GINT_TO_POINTER(doc
->has_bom
));
2622 doc
->has_bom
= GPOINTER_TO_INT(action
->data
);
2623 ui_update_statusbar(doc
, -1);
2624 ui_document_show_hide(doc
);
2629 document_undo_add(doc
, UNDO_ENCODING
, g_strdup(doc
->encoding
));
2631 document_set_encoding(doc
, (const gchar
*)action
->data
);
2633 ignore_callback
= TRUE
;
2634 encodings_select_radio_item((const gchar
*)action
->data
);
2635 ignore_callback
= FALSE
;
2637 g_free(action
->data
);
2643 g_free(action
); /* free the action which was taken from the stack */
2645 update_changed_state(doc
);
2646 ui_update_popup_reundo_items(doc
);
2650 static void document_redo_add(GeanyDocument
*doc
, guint type
, gpointer data
)
2652 undo_action
*action
;
2654 g_return_if_fail(doc
!= NULL
);
2656 action
= g_new0(undo_action
, 1);
2657 action
->type
= type
;
2658 action
->data
= data
;
2660 g_trash_stack_push(&doc
->priv
->redo_actions
, action
);
2662 document_set_text_changed(doc
, TRUE
);
2663 ui_update_popup_reundo_items(doc
);
2668 * Gets the status color of the document, or @c NULL if default widget coloring should be used.
2669 * Returned colors are red if the document has changes, green if the document is read-only
2670 * or simply @c NULL if the document is unmodified but writable.
2672 * @param doc The document to use.
2674 * @return The color for the document or @c NULL if the default color should be used. The color
2675 * object is owned by Geany and should not be modified or freed.
2679 const GdkColor
*document_get_status_color(GeanyDocument
*doc
)
2681 static GdkColor red
= {0, 0xFFFF, 0, 0};
2682 static GdkColor green
= {0, 0, 0x7FFF, 0};
2683 #ifdef USE_GIO_FILEMON
2684 static GdkColor orange
= {0, 0xFFFF, 0x7FFF, 0};
2686 GdkColor
*color
= NULL
;
2688 g_return_val_if_fail(doc
!= NULL
, NULL
);
2692 #ifdef USE_GIO_FILEMON
2693 else if (doc
->priv
->file_disk_status
== FILE_CHANGED
)
2696 else if (doc
->readonly
)
2699 return color
; /* return pointer to static GdkColor. */
2703 /** Accessor function for @ref GeanyData::documents_array items.
2704 * @warning Always check the returned document is valid (@c doc->is_valid).
2705 * @param idx @c documents_array index.
2706 * @return The document, or @c NULL if @a idx is out of range.
2710 GeanyDocument
*document_index(gint idx
)
2712 return (idx
>= 0 && idx
< (gint
) documents_array
->len
) ? documents
[idx
] : NULL
;
2716 /* create a new file and copy file content and properties */
2717 GeanyDocument
*document_clone(GeanyDocument
*old_doc
, const gchar
*utf8_filename
)
2723 g_return_val_if_fail(old_doc
!= NULL
, NULL
);
2725 len
= sci_get_length(old_doc
->editor
->sci
) + 1;
2726 text
= (gchar
*) g_malloc(len
);
2727 sci_get_text(old_doc
->editor
->sci
, len
, text
);
2728 /* use old file type (or maybe NULL for auto detect would be better?) */
2729 doc
= document_new_file(utf8_filename
, old_doc
->file_type
, text
);
2732 /* copy file properties */
2733 doc
->editor
->line_wrapping
= old_doc
->editor
->line_wrapping
;
2734 doc
->readonly
= old_doc
->readonly
;
2735 doc
->has_bom
= old_doc
->has_bom
;
2736 document_set_encoding(doc
, old_doc
->encoding
);
2737 sci_set_lines_wrapped(doc
->editor
->sci
, doc
->editor
->line_wrapping
);
2738 sci_set_readonly(doc
->editor
->sci
, doc
->readonly
);
2740 ui_document_show_hide(doc
);
2745 /* @note If successful, this should always be followed up with a call to
2746 * document_close_all().
2747 * @return TRUE if all files were saved or had their changes discarded. */
2748 gboolean
document_account_for_unsaved(void)
2750 guint i
, p
, page_count
;
2752 page_count
= gtk_notebook_get_n_pages(GTK_NOTEBOOK(main_widgets
.notebook
));
2753 /* iterate over documents in tabs order */
2754 for (p
= 0; p
< page_count
; p
++)
2756 GeanyDocument
*doc
= document_get_from_page(p
);
2758 if (DOC_VALID(doc
) && doc
->changed
)
2760 if (! dialogs_show_unsaved_file(doc
))
2764 /* all documents should now be accounted for, so ignore any changes */
2765 foreach_document (i
)
2767 documents
[i
]->changed
= FALSE
;
2773 static void force_close_all(void)
2775 guint i
, len
= documents_array
->len
;
2777 /* check all documents have been accounted for */
2778 for (i
= 0; i
< len
; i
++)
2780 if (documents
[i
]->is_valid
)
2782 g_return_if_fail(!documents
[i
]->changed
);
2785 main_status
.closing_all
= TRUE
;
2789 document_close(documents
[i
]);
2792 main_status
.closing_all
= FALSE
;
2796 gboolean
document_close_all(void)
2798 if (! document_account_for_unsaved())
2807 static void monitor_reload_file(GeanyDocument
*doc
)
2809 gchar
*base_name
= g_path_get_basename(doc
->file_name
);
2812 ret
= dialogs_show_prompt(NULL
,
2813 GTK_STOCK_CLOSE
, GTK_RESPONSE_CLOSE
,
2814 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
2815 _("_Reload"), GTK_RESPONSE_ACCEPT
,
2816 _("Do you want to reload it?"),
2817 _("The file '%s' on the disk is more recent than\nthe current buffer."),
2821 if (ret
== GTK_RESPONSE_ACCEPT
)
2822 document_reload_file(doc
, doc
->encoding
);
2823 else if (ret
== GTK_RESPONSE_CLOSE
)
2824 document_close(doc
);
2828 static gboolean
monitor_resave_missing_file(GeanyDocument
*doc
)
2830 gboolean want_reload
= FALSE
;
2831 gboolean file_saved
= FALSE
;
2834 ret
= dialogs_show_prompt(NULL
,
2835 _("Close _without saving"), GTK_RESPONSE_CLOSE
,
2836 GTK_STOCK_CANCEL
, GTK_RESPONSE_CANCEL
,
2837 GTK_STOCK_SAVE
, GTK_RESPONSE_ACCEPT
,
2838 _("Try to resave the file?"),
2839 _("File \"%s\" was not found on disk!"),
2841 if (ret
== GTK_RESPONSE_ACCEPT
)
2843 file_saved
= dialogs_show_save_as();
2846 else if (ret
== GTK_RESPONSE_CLOSE
)
2848 document_close(doc
);
2850 if (ret
!= GTK_RESPONSE_CLOSE
&& ! file_saved
)
2852 /* file is missing - set unsaved state */
2853 document_set_text_changed(doc
, TRUE
);
2854 /* don't prompt more than once */
2855 setptr(doc
->real_path
, NULL
);
2862 /* Set force to force a disk check, otherwise it is ignored if there was a check
2863 * in the last file_prefs.disk_check_timeout seconds.
2864 * @return @c TRUE if the file has changed. */
2865 gboolean
document_check_disk_status(GeanyDocument
*doc
, gboolean force
)
2867 gboolean ret
= FALSE
;
2868 gboolean use_gio_filemon
;
2869 time_t cur_time
= 0;
2871 gchar
*locale_filename
;
2872 FileDiskStatus old_status
;
2874 g_return_val_if_fail(doc
!= NULL
, FALSE
);
2876 /* ignore remote files and documents that have never been saved to disk */
2877 if (file_prefs
.disk_check_timeout
== 0 || doc
->real_path
== NULL
|| doc
->priv
->is_remote
)
2880 use_gio_filemon
= (doc
->priv
->monitor
!= NULL
);
2882 if (use_gio_filemon
)
2884 if (doc
->priv
->file_disk_status
!= FILE_CHANGED
&& ! force
)
2889 cur_time
= time(NULL
);
2890 if (! force
&& doc
->priv
->last_check
> (cur_time
- file_prefs
.disk_check_timeout
))
2893 doc
->priv
->last_check
= cur_time
;
2896 locale_filename
= utils_get_locale_from_utf8(doc
->file_name
);
2897 if (g_stat(locale_filename
, &st
) != 0)
2899 monitor_resave_missing_file(doc
);
2900 /* doc may be closed now */
2903 else if (! use_gio_filemon
&& /* ignore check when using GIO */
2904 doc
->priv
->mtime
> cur_time
)
2906 g_warning("%s: Something is wrong with the time stamps.", G_STRFUNC
);
2907 /* Note: on Windows st.st_mtime can be newer than cur_time */
2909 else if (doc
->priv
->mtime
< st
.st_mtime
)
2911 doc
->priv
->mtime
= st
.st_mtime
;
2912 monitor_reload_file(doc
);
2913 /* doc may be closed now */
2916 g_free(locale_filename
);
2919 { /* doc can get invalid when a document was closed */
2920 old_status
= doc
->priv
->file_disk_status
;
2921 doc
->priv
->file_disk_status
= FILE_OK
;
2922 if (old_status
!= doc
->priv
->file_disk_status
)
2923 ui_update_tab_status(doc
);
2929 /** Compares documents by their display names.
2930 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2931 * @note 'Display name' means the base name of the document's filename.
2933 * @param a @c GeanyDocument**.
2934 * @param b @c GeanyDocument**.
2935 * @warning The arguments take the address of each document pointer.
2936 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2940 gint
document_compare_by_display_name(gconstpointer a
, gconstpointer b
)
2942 GeanyDocument
*doc_a
= *((GeanyDocument
**) a
);
2943 GeanyDocument
*doc_b
= *((GeanyDocument
**) b
);
2944 gchar
*base_name_a
, *base_name_b
;
2947 base_name_a
= g_path_get_basename(DOC_FILENAME(doc_a
));
2948 base_name_b
= g_path_get_basename(DOC_FILENAME(doc_b
));
2950 result
= strcmp(base_name_a
, base_name_b
);
2952 g_free(base_name_a
);
2953 g_free(base_name_b
);
2959 /** Compares documents by their tab order.
2960 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2962 * @param a @c GeanyDocument**.
2963 * @param b @c GeanyDocument**.
2964 * @warning The arguments take the address of each document pointer.
2965 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2967 * @since 0.21 (GEANY_API_VERSION 209)
2969 gint
document_compare_by_tab_order(gconstpointer a
, gconstpointer b
)
2971 GeanyDocument
*doc_a
= *((GeanyDocument
**) a
);
2972 GeanyDocument
*doc_b
= *((GeanyDocument
**) b
);
2973 gint notebook_position_doc_a
;
2974 gint notebook_position_doc_b
;
2976 notebook_position_doc_a
= document_get_notebook_page(doc_a
);
2977 notebook_position_doc_b
= document_get_notebook_page(doc_b
);
2979 if (notebook_position_doc_a
< notebook_position_doc_b
)
2981 if (notebook_position_doc_a
> notebook_position_doc_b
)
2988 /** Compares documents by their tab order, in reverse order.
2989 * This matches @c GCompareFunc for use with e.g. @c g_ptr_array_sort().
2991 * @param a @c GeanyDocument**.
2992 * @param b @c GeanyDocument**.
2993 * @warning The arguments take the address of each document pointer.
2994 * @return Negative value if a < b; zero if a = b; positive value if a > b.
2996 * @since 0.21 (GEANY_API_VERSION 209)
2998 gint
document_compare_by_tab_order_reverse(gconstpointer a
, gconstpointer b
)
3000 GeanyDocument
*doc_a
= *((GeanyDocument
**) a
);
3001 GeanyDocument
*doc_b
= *((GeanyDocument
**) b
);
3002 gint notebook_position_doc_a
;
3003 gint notebook_position_doc_b
;
3005 notebook_position_doc_a
= document_get_notebook_page(doc_a
);
3006 notebook_position_doc_b
= document_get_notebook_page(doc_b
);
3008 if (notebook_position_doc_a
< notebook_position_doc_b
)
3010 if (notebook_position_doc_a
> notebook_position_doc_b
)
3017 void document_grab_focus(GeanyDocument
*doc
)
3019 g_return_if_fail(doc
!= NULL
);
3021 gtk_widget_grab_focus(GTK_WIDGET(doc
->editor
->sci
));