Search code examples
pythongtk3gtksourceview

Syntax highlighting with GTK3 SourceView


How do you enable syntax highlighting in GtkSourceView using GTK3? My code below is not working.

# HTML view
self.scrolledwindow_html = builder.get_object('scrolledwindow_html')
self.sourceview_html = GtkSource.View()
self.buffer_html = self.sourceview_html.get_buffer()

lang_manager = GtkSource.LanguageManager()
self.buffer_html.set_language(lang_manager.get_language('html'))
self.scrolledwindow_html.add(self.sourceview_html)

Giving an error:

AttributeError: 'TextBuffer' object has no attribute 'set_language'


Solution

  • It seems like the sourceview is initialising itself with a Gtk.TextBuffer (which doesn't know about syntax highlighting) instead of a GtkSource.Buffer (which does). Force it to use your choice of Buffer by making the buffer first, and telling View to use exactly that object:

     self.buffer_html = GtkSource.Buffer()
     self.sourceview_html = GtkSource.View.new_with_buffer(self.buffer_html)