Mike's Musings

Do you want code with that mongoose?

1

Syntax highlighting with GtkSourceviewmm 2.0 and Giomm

Can you tell I’ve recently begun coding on personal projects again?  In a follow up to yesterdays post about loading a file with Giomm, last night I decided to upgrade a project I am working on from GtkSourceviewmm 1.0 to 2.0.  This turned out to be more difficult than I initially expected as the API documentation provided with Ubuntu seems to be horribly wrong, it includes functionality that doesn’t exist anymore.  So after referring to the GtkSourceview 2.0 documentation I got it all working so below is a simplified version with all error checking removed but should do the trick.

void load_highlightable_text(Glib::ustring file_name, Glib::RefPtr buffer)
{
	Glib::RefPtr fp = Gio::File::create_for_uri(file_name);

	char *raw;
	gsize read_bytes;
	std::string e_tag;

	fp->load_contents(raw, read_bytes, m_e_tag);

	Glib::ustring buf = raw;

	buffer->begin_not_undoable_action();
	buffer->set_text(buf);
	buffer->end_not_undoable_action();

	// Retrieve the mime type of the file.
	Glib::RefPtr info = fp->query_info();
	Glib::ustring mime_type = Gio::content_type_get_mime_type(info->get_content_type());

	// variables needed for getting the language
	Glib::RefPtr manager = gtksourceview::SourceLanguageManager::create();
	Glib::RefPtr language;

	std::vector lang_ids = manager->get_language_ids();
	std::vector mime_types;

	// Cycle through all available languages matching the first one that will highlight the given mime type
	for(std::vector::iterator i = lang_ids.begin(); i != lang_ids.end(); i++) {
		language = manager->get_language(*i);

		if(language) {
			mime_types = language->get_mime_types();

			for(std::vector::iterator j = mime_types.begin(); j != mime_types.end(); j++) {
				if(*j == mime_type) {
					buffer->set_language(language);
					buffer->set_highlight_syntax(true);
					return;
				}
			}
		}
	}

	return;
}

If anyone knows of a more sane way to do this please tell me as what I have currently looks bloody horrible to me.

One Response to “Syntax highlighting with GtkSourceviewmm 2.0 and Giomm”

  1. lum says:

    Where’s the next post?

Leave a Reply