Implement block comment/uncomment in ScintillaNET control

1.3k views Asked by At

I'm trying to implement a custom text-editor in C# using the ScintillaNET component. I've got most of it right until now, but stuck at one point. I want to give the user the ability to block comment/uncomment the selected text. I tried a lot, but cannot find any examples online. The only thing I seem to get from the control's Selection object are the Start and End positions, but that isn't much help

    private void commentBlockToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (txtSQL.Selection.Text.Length > 0)
        {
            String start = txtSQL.Selection.Start.ToString();
            String end = txtSQL.Selection.End.ToString();
            MessageBox.Show(start + "::" + end);

        }
    }

Were any of you able to successfully implement this using the ScintillaNET control?

EDIT: After some improvization, I'm able to do it somehow, but after block is commented, last line moves out of selection!

    private void commentBlockToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (txtSQL.Selection.Text.Length > 0)
        {
            Range range = txtSQL.Selection.Range;
            int f = range.StartingLine.Number;
            int t = range.EndingLine.Number;
            int endpos = txtSQL.Selection.End;
            for (int i = f; i <= t; i++)
            {
                //txtSQL.GoTo.Line(i);
                string tstr = txtSQL.Lines[i].Text.Replace(Environment.NewLine, "");
                txtSQL.Lines[i].Text = "--" + tstr;
            }
        }
    }
2

There are 2 answers

0
Prahlad Yeri On BEST ANSWER

After a bit of experimentation, I found a way to accomplish this. Though I doubt if it is the most elegant of solutions!

    private void commentBlockToolStripMenuItem_Click(object sender, EventArgs e)
    {
        if (txtSQL.Selection.Text.Length > 0)
        {
            Range range = txtSQL.Selection.Range;
            int f = range.StartingLine.Number;
            int t = range.EndingLine.Number;
            for (int i = f; i <= t; i++)
            {
                txtSQL.InsertText(txtSQL.Lines[i].StartPosition,"--");
            }
            txtSQL.Selection.Start = txtSQL.Lines[f].StartPosition;
            txtSQL.Selection.End = txtSQL.Lines[t].EndPosition;
        }
    }
1
user1974633 On

Actually I found a very simple solution to this. To block comment do

scintilla1.Lexing.LineComment();

And to block uncomment do

scintilla1.Lexing.LineUncomment();