Display code fragments in GtkSourceView and maintain line numbers

A problem I found while developing for coala is that i needed a Sourcecode printing widget which would print snippets of code. The obvious choice was to use GtkSourceView. A fundemental problem I discovered was that while it prints snippets of code from a file it does not maintain line numbers which was critical for my application.

The Solution:

GtkSourceView has a gutter object which holds all the objects in the margin. This also includes the line numbers. Thus I assigned a custom line renderer.

class LineRenderer(GtkSource.GutterRendererText): 
    line_offset = 0 
    def __init__(self, start_line, *args, **kwargs): 
        self.line_offset = start_line GtkSource.GutterRendererText.__init__(self, *args, **kwargs) 
    def do_query_data(self, start, end, flags): 
        self.props.text = str(start.get_line() + self.line_offset + 1) 
        label = Gtk.Label() 
        pango_layout = label.get_layout() 
        pango_layout.set_text(self.props.text, len(self.props.text)) 
        self.props.size = pango_layout.get_pixel_size()[0]

The usage

textbuffer = GtkSource.Buffer() 
textview = GtkSource.View(visible=True, buffer=textbuffer, monospace=True, editable=False) 
self.source_view.attach(textview, 0,self.source_view_iter, 2, 1) 
gutter = textview.get_gutter(Gtk.TextWindowType.LEFT) 
renderer = LineRenderer(start_nr, xpad=6, xalign=1.0) 
gutter.insert(renderer, 0)</pre>

Any further queries drop a comment. šŸ™‚


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s