This project is read-only.

Margin width auto adjustable

Topics: Developer Forum, Project Management Forum, User Forum
Aug 4, 2011 at 1:36 PM

Hi all,

I display the line number in the first margin.

I need to set margin width to 40 in order to display 4 digits.

Can this margin width be auto adjustable not to take too much place in the screen if there are not a lot of lines?

Thanks in advance for your help.

Jun 20, 2012 at 2:19 AM

I use the following code to adjust the margin automatically as the number of lines change.  Feel free to use it however you see fit.

I put this code just after the InitializeComponent() call in the control constructor (or form constructor, if you're using it on a form).

// Automatically adjust the left margin to be wide enough to show the largest line number.
int last_measure_lines = -1;
scintilla.TextChanged += (o, e) => {
    int lines = scintilla.Lines.Count;
    if (lines != last_measure_lines) {
        last_measure_lines = lines;
        scintilla.Margins[0].Width = TextRenderer.MeasureText(lines.ToString(), scintilla.Font).Width;
    }
};

Feb 14, 2013 at 2:40 PM
I have the my margin setup wide. but the line number restarts at 99, how can i fix that so it would continue with line numbers 100-102-102 ...?
Feb 14, 2013 at 8:34 PM
acharif, is your margin wide enough to display the additional digits? The margin shouldn't restart, so something must be hiding the extra digits, making it appear to restart.
Jan 9, 2015 at 7:17 PM
Note that the example provided by jk001 does not take into account the Scintilla control's zoom factor.

Rather than referencing scintilla.Font use a new font object, using the zoom factor to adjust the point size.
scintilla.Margins[0].Width = TextRenderer.MeasureText(
    lines.ToString(), 
    new Font(
        scintilla.Font.FontFamily, 
        scintilla.Font.SizeInPoints + scintilla.ZoomFactor, 
        scintilla.Font.Style)
    ).Width;
And since scintilla.ZoomFactor can change without the text changing, the last_measure_lines check needs to allow an override, or a modification of scintilla.ZoomFactor needs to reset last_measure_lines.