Skip to content

Commit 4a74dc6

Browse files
sc0wlukefromdc
authored andcommitted
pluma-document: Fix: don't crash using files with 'bom'
Fixes #301
1 parent bc64980 commit 4a74dc6

File tree

1 file changed

+60
-1
lines changed

1 file changed

+60
-1
lines changed

‎pluma/pluma-document.c‎

Lines changed: 60 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -650,12 +650,58 @@ pluma_document_class_init (PlumaDocumentClass *klass)
650650
g_type_class_add_private (object_class, sizeof(PlumaDocumentPrivate));
651651
}
652652

653+
static gboolean
654+
file_with_bom (GFile *file)
655+
{
656+
FILE *testfile;
657+
gchar c;
658+
int i;
659+
gchar *bom;
660+
gchar *file_path;
661+
gboolean has_bom;
662+
663+
file_path = g_file_get_path (file);
664+
665+
testfile = fopen (file_path, "r");
666+
667+
g_free (file_path);
668+
669+
if (testfile == NULL)
670+
{
671+
perror ("fopen");
672+
return FALSE;
673+
}
674+
675+
bom = "";
676+
677+
for (i = 0; i < 3; i++)
678+
{
679+
c = fgetc (testfile);
680+
681+
if (c == EOF)
682+
break;
683+
else
684+
bom = g_strdup_printf ("%s%c", bom, c);
685+
}
686+
687+
fclose (testfile);
688+
689+
if (g_strcmp0 (bom, "\357\273\277") == 0)
690+
has_bom = TRUE;
691+
else
692+
has_bom = FALSE;
693+
694+
g_free (bom);
695+
return has_bom;
696+
}
697+
653698
static void
654699
set_language (PlumaDocument *doc,
655700
GtkSourceLanguage *lang,
656701
gboolean set_by_user)
657702
{
658703
GtkSourceLanguage *old_lang;
704+
const gchar *bom_langs;
659705

660706
pluma_debug (DEBUG_DOCUMENT);
661707

@@ -664,7 +710,20 @@ set_language (PlumaDocument *doc,
664710
if (old_lang == lang)
665711
return;
666712

667-
gtk_source_buffer_set_language (GTK_SOURCE_BUFFER (doc), lang);
713+
bom_langs = "asp,dtl,docbook,html,mxml,mallard,markdown,mediawiki,php,tera,xml,xslt";
714+
715+
if (g_strrstr (bom_langs, gtk_source_language_get_id (lang)))
716+
{
717+
GFile *file;
718+
file = pluma_document_get_location (doc);
719+
720+
if (!file_with_bom (file))
721+
gtk_source_buffer_set_language (GTK_SOURCE_BUFFER (doc), lang);
722+
723+
g_object_unref (file);
724+
}
725+
else
726+
gtk_source_buffer_set_language (GTK_SOURCE_BUFFER (doc), lang);
668727

669728
if (lang != NULL)
670729
gtk_source_buffer_set_highlight_syntax (GTK_SOURCE_BUFFER (doc),

0 commit comments

Comments
 (0)