|
|
Comments and Discussions
|
|
 |

|
When pressing ctrl+z to undo the changes done to the text, the cursor just jumps to the beginning of the line.
|
|
|
|

|
Just included this with a VS2010 solution, works perfectly for syntax highlighting SQL.
Kevin S. Gallagher
Programming is an art form that fights back
|
|
|
|

|
Did anyone notice the problem that when a block of code is pasted into the Syntaxrickbox, only that last line is processed
m_nContentLength = this.TextLength;
int nCurrentSelectionStart = SelectionStart;
int nCurrentSelectionLength = SelectionLength;
m_bPaint = false;
m_nLineStart = nCurrentSelectionStart;
while ((m_nLineStart > 0) && (Text[m_nLineStart - 1] != '\n'))
m_nLineStart--;
m_nLineEnd = nCurrentSelectionStart;
while ((m_nLineEnd < Text.Length) && (Text[m_nLineEnd] != '\n'))
m_nLineEnd++;
m_nLineLength = m_nLineEnd - m_nLineStart;
m_strLine = Text.Substring(m_nLineStart, m_nLineLength);
ProcessLine();
m_bPaint = true;
|
|
|
|

|
I am a beginner c # and I'm a chinese.Sorry,My English is so poor.
I think you can write this way:first
write a class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
public class ChangeColor
{
public void ChangeColorToBlue(string text, Color color, RichTextBox r)
{
int s = 0;
while ((-1 + text.Length - 1) != (s = text.Length - 1 + r.Find(text, s, -1, RichTextBoxFinds.MatchCase | RichTextBoxFinds.WholeWord)))
{
r.SelectionColor = color;
}
}
public void SelectKeyWords(RichTextBox r)
{
int sIndex = r.SelectionStart;
r.SelectAll();
r.SelectionColor = Color.Black;
r.Select(sIndex, 0);
ChangeColorToBlue("static", Color.Blue, r); ChangeColorToBlue("void", Color.Blue, r);
ChangeColorToBlue("using", Color.Blue, r);
ChangeColorToBlue("if", Color.Blue, r);
ChangeColorToBlue("else", Color.Blue, r);
ChangeColorToBlue("public", Color.Blue, r);
ChangeColorToBlue("private", Color.Blue, r);
ChangeColorToBlue("class", Color.Blue, r);
ChangeColorToBlue("new", Color.Blue, r);
ChangeColorToBlue("int", Color.Blue, r);
ChangeColorToBlue("true", Color.Blue, r);
ChangeColorToBlue("double", Color.Blue, r);
ChangeColorToBlue("is", Color.Blue, r);
ChangeColorToBlue("byte", Color.Blue, r);
ChangeColorToBlue("foreach", Color.Blue, r);
ChangeColorToBlue("struct", Color.Blue, r);
ChangeColorToBlue("while", Color.Blue, r);
ChangeColorToBlue("typeof", Color.Blue, r);
ChangeColorToBlue("float", Color.Blue, r);
ChangeColorToBlue("decimal", Color.Blue, r);
r.Select(sIndex, 0);
r.SelectionColor = Color.Black;
}
}
}
And in Form:
you just use it;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
namespace WindowsFormsApplication2
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
[DllImport("user32")]
private static extern int SendMessage(IntPtr hwnd, int wMsg, int wParam, IntPtr lParam);
private void button1_Click(object sender, EventArgs e)
{
string fname = GetFileName();
textBox1.Text = fname;
richTextBox1.Text = show(fname);
}
public string GetFileName()
{
string fname = string.Empty;
OpenFileDialog dlg = new OpenFileDialog();
dlg.InitialDirectory = "c:\\";
dlg.Filter = "All files (*.*)|*.*";
dlg.FilterIndex = 1;
dlg.RestoreDirectory = true;
if (dlg.ShowDialog() == DialogResult.OK)
{
fname = dlg.FileName;
}
return fname;
}
public string show(string fileurl)
{
if (fileurl.Equals(""))
{
return "";
}
else
{
string source = string.Empty;
StreamReader sr = new StreamReader(fileurl, System.Text.Encoding.Default);
string strLine = sr.ReadLine();
while (strLine != null)
{
source += strLine + "\n";
strLine = sr.ReadLine();
}
return source;
}
}
private void richTextBox1_TextChanged(object sender, EventArgs e)
{
base.OnTextChanged(e);
SendMessage(base.Handle, 0xB, 0, IntPtr.Zero);
ChangeColor change = new ChangeColor();
change.SelectKeyWords(richTextBox1);
SendMessage(base.Handle, 0xB, 1, IntPtr.Zero);
this.Refresh();
}
}
}
|
|
|
|
|
|

|
Hi,
There is a small problem with the paint size of the richtextbox , when i open a diffrent text files (i copy only the text from the file) to the richtextbox the size of the richtextbox is exceed from the original size of the scrolls and paint the exceed part in white(i have a sceen capture if you want i can send you).
every time that i open a diffrent text file i debuging the event of size_changed of the richtextbox and i see in the call stack that when the size changed it happen from the function "WndProc" that you created.
can you sugget some soultion for the problem ?
modified 21 Mar '12 - 10:20.
|
|
|
|

|
when I comment out GetscrollPos in C# or vb.net it does not affect multi-line coloring.
Is there a reason why it is coloring only ToEOL when it is converted to Vb.net?
(Trying to color for Chr(34) and C# didn't have that symbol)
|
|
|
|
|

|
idiot - at the very least explain then problems you encounter
|
|
|
|
|

|
Many thanks for this - it has saved me lots of work. (I'm writing an SQL client, so highlighting key words)
|
|
|
|

|
Instead of in a separated class. I just erased the SyntaxSettings class and put all the settings in SyntaxRichTextBox, so now I can edit them in the Properties panel. A lot handier . Great job by the way.
|
|
|
|

|
Hello (again),
another question: how can I edit the properties in the (form) editing mode (not like actually in the code section?) Is there a way to realize this?
Best regards
Tim
|
|
|
|

|
Just move all the settings from SyntaxSettings to SyntaxRichTextBox and then erease all occurrences of "Settings." for "". Voila! (Well, almost actually there is some stuff to be done still).
|
|
|
|

|
Can't enabled the script to work within an "if" statement..
|
|
|
|

|
You say that performance problems solved but only during Load file Ok.
But do you have a solution when you change the text after loading ?
I try the same way with the property selectedRtf but it's to slow because I must use the select method. :(
|
|
|
|

|
do you mean to clear the textbox and paste new text from clipboard?
for this problem i dont have an solution ... (at the moment) sorry
|
|
|
|

|
hi ...
i was searching a lot for the reasing why the syntaxhighlight is that slow.
the problem is not the regex, but the richTextBox.Select. it takes a lomg time to select each keyword an change its color.
so i wrote a helper-class to color very large documents.
it uses the same Settings and should ONLY be used to perform the 'init-coloring'.
example: SyntaxTester -> MainForm -> MainFormLoad()
[...]
// Load a file and update the syntax highlighting.
m_syntaxRichTextBox.LoadFile("../script.lua", RichTextBoxStreamType.PlainText);
//m_syntaxRichTextBox.ProcessAllLines();
SyntaxHighlighter.RtfColoring.ProcessRtfColoring(m_syntaxRichTextBox);
all other methods are ok. so for the first init i use the rtf-coloring and for live-editing i usw the existing richTextBox.Select(...
using System;
using System.Text.RegularExpressions;
namespace SyntaxHighlighter
{
/// <summary>
/// enabes syntaxhighlighting for a richtextbox by using rtf
/// </summary>
public static class RtfColoring
{
public static void ProcessRtfColoring(SyntaxRichTextBox richTextBox)
{
SyntaxSettings Settings = richTextBox.Settings;
if (Settings.Keywords.Count < 1)
return;
// reset the text to get a clear rtf
string strTextToAdd = richTextBox.Text;
richTextBox.Clear();
richTextBox.AppendText(strTextToAdd);
string strRTF = richTextBox.Rtf;
// find index of start of header
int iRTFLoc = strRTF.IndexOf("\\rtf");
// get index of where we'll insert the colour table
// try finding opening bracket of first property of header first
int iInsertLoc = strRTF.IndexOf('{', iRTFLoc);
// if there is no property, we'll insert colour table
// just before the end bracket of the header
if (iInsertLoc == -1) iInsertLoc = strRTF.IndexOf('}', iRTFLoc) - 1;
string strCommentColor = "\\red" + Settings.CommentColor.R.ToString() +
"\\green" + Settings.CommentColor.G.ToString() +
"\\blue" + Settings.CommentColor.B.ToString();
string strStringColor = "\\red" + Settings.StringColor.R.ToString() +
"\\green" + Settings.StringColor.G.ToString() +
"\\blue" + Settings.StringColor.B.ToString();
string strKeywordColor = "\\red" + Settings.KeywordColor.R.ToString() +
"\\green" + Settings.KeywordColor.G.ToString() +
"\\blue" + Settings.KeywordColor.B.ToString();
string strIntegerColor = "\\red" + Settings.IntegerColor.R.ToString() +
"\\green" + Settings.IntegerColor.G.ToString() +
"\\blue" + Settings.IntegerColor.B.ToString();
// insert the colour table at our chosen location
strRTF = strRTF.Insert(iInsertLoc, "{\\colortbl ;" + strCommentColor + ";" + strStringColor + ";" + strKeywordColor + ";" + strIntegerColor + ";}");
// build the keywords regex
string strKeywords = String.Empty;
foreach (string keyword in Settings.Keywords)
{
strKeywords += keyword + ",";
}
strKeywords = strKeywords.Substring(0, strKeywords.Length - 1);
Regex r = new Regex(@", ?");
strKeywords = @"\b(" + r.Replace(strKeywords, @"|") + @")\b";
// start coloring
// Keywords
r = new Regex(strKeywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchKeyword));
// Integers
r = new Regex("(\\b(?:[0-9]*\\.)?[0-9]+\\b)", RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchInteger));
// Comments
r = new Regex("("+Settings.Comment+".*$)", RegexOptions.Multiline | RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchComment));
// Strings
r = new Regex("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"|\'[^\'\\\\\\r\\n]*(?:\\\\.[^\'\\\\\\r\\n]*)*\')", RegexOptions.Singleline | RegexOptions.IgnoreCase);
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchString));
richTextBox.Rtf = strRTF;
}
private static string MatchKeyword(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf3 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
return String.Empty;
}
private static string MatchString(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf2 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
return String.Empty;
}
private static string MatchComment(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf1 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
return String.Empty;
}
private static string MatchInteger(Match match)
{
if (match.Groups[1].Success)
{
return @"\cf4 " + RemoveRtfColors(match.Value) + @"\cf0 ";
}
return String.Empty;
}
/// <summary>
/// remove all rtf-colors from a string
/// </summary>
/// <param name="strText"></param>
/// <returns>String</returns>
private static string RemoveRtfColors(string strText)
{
Regex r = new Regex(@"\\cf[0-9] ");
strText = r.Replace(strText, "");
return strText;
}
}
}
have fun
|
|
|
|

|
Where do I put that code? I made a new class and put the code you pasted in there. The speed is still slow though, what do I need to do afterwards?
Sorry, I am new to C# so it's difficult for me
|
|
|
|

|
Good Work man, super fast now, congrats to the original control author
|
|
|
|

|
Could you show me / upload how this is supposed to be?
Thanks
Email:
ZoMbiESsSZ@Gmail.com
|
|
|
|

|
your code doesn't color first line in rtb?
|
|
|
|

|
Hi,
I tried this too but it makes it quite complex.
I have a simple solution which is to use a temporary richTextBox which is not shown and do the changes to it.
Finally copy rtTemp RTF back to original richTextBox.
The speed is not incredibly better but no flicker.
Here is how I did it:
private static bool isAutoChange = false;
private void richTextBox_TextChanged(object sender, EventArgs e)
{
if (!isAutoChange)
Highlight();
}
private void Highlight()
{
RichTextBox rtTemp = new RichTextBox();
rtTemp.Font = richTextBox.Font;
rtTemp.Rtf = richTextBox.Rtf;
rtTemp.Visible = false;
rtTemp.HideSelection = true;
isAutoChange = true;
richTextBox.Rtf = rtTemp.Rtf;
isAutoChange = false;
}
--
Cui Bono?
|
|
|
|

|
Hello,
Thanks for your article and sources, it works great!
I have a problem when I try to use it to color code in SAS language. The following keywords are not colored, perhaps because of the special character percent: "%let", "%nrbquote("?
Comment lines starting with the star character are not colored either. Would you have any idea to fix this problem?
txt.Settings.Keywords.Add("%let");
txt.Settings.Keywords.Add("%nrbquote(");
txt.Settings.Keywords.Add(");");
txt.Settings.Comment = "/*";
txt.Settings.Comment = "*";
Thank you in advance
Julien
|
|
|
|

|
I am using it for a SQL editor and works great
Kevin S. Gallagher
Programming is an art form that fights back
|
|
|
|
|

|
Hi,
can you please post also the extra function for the comments.
Thanks
|
|
|
|

|
well, I changed the code again and now its very simple:
now i use the old methode for integers, strings and commentsprivate void ProcessRegex(string strRegex, Color color)
{
Regex regKeywords = new Regex(strRegex, RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match regMatch;
for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
{
int nStart = m_nLineStart + regMatch.Index;
int nLenght = regMatch.Length;
SelectionStart = nStart;
SelectionLength = nLenght;
SelectionColor = color;
}
}
and just the new one for highlightingprivate void HighLightRegex(string strRegex, Color color)
{
Regex regKeywords = new Regex(@"\w+", RegexOptions.IgnoreCase | RegexOptions.Compiled);
Match regMatch;
for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
{
string keyword;
if (Settings.Keywords.TryGetValue(regMatch.Value, out keyword))
{
int nStart = m_nLineStart + regMatch.Index;
int nLenght = regMatch.Length;
SelectionStart = nStart;
SelectionLength = nLenght;
SelectionColor = color;
}
}
}
it's still faster then the original code, because the comments, integers and strings aren't using the keywords.
Also I changed the strRegex for strings. Now it also highlights chars (e.g. 'a'):"(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"|\'[^\'\\\\\\r\\n]*(?:\\\\.[^\'\\\\\\r\\n]*)*\')"
if there is an easier way: post reply, please
no_morser
|
|
|
|

|
Hello,
I'm trying to add your new code. But now I've got the problem, that the line with "TryGetValue" occurs an error:
Error1 "System.Collections.Generic.List" has now definition for "TryGetValue",and there is no expanded method with "TryGetValue" found in the code, there is no argument "System.Collections.Generic.List" accepted. (Maybe there are some missing Using-Directive or Assembly?)
the using-directive "using System.Collections.Generic;" is set, so maybe you know whats wrong? Or you update you Download-Code to see whats wrong (Maybe I placed it wrong?!? (I place your new routine right after the old one)
Best regards
Tim
|
|
|
|

|
Can you explain more about this string: "\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\""
Thanks
Tran Ho Le NGuyen
|
|
|
|

|
just like visual studio highlight, the functions are highlighted in different colors as keywords.
it is easy to add this term.
|
|
|
|

|
Hi.
I'm using your excellent control inside my editor.
I've just dragged it to my MainForm and I've registered a method (MainForm_TextChanged)to the TextChanged event.
Then I've implemented MainForm_TextChanged.
But it seems that the application doesn't reach this method when I changes the text of the SyntaxRichTextBox. Do you have any idea what privents MainForm of listening to the TextChanged event?
|
|
|
|

|
at the end of the OnTextChanged event put base.OnTextChanged(e);
|
|
|
|

|
hi, i love this control and i use it in my app.
but my apps users have reported that the textbox highlights a little too slow.
are u planning on a new release better performane?
_____________________________
Don't download it, make it.
Visual Basic /C#
|
|
|
|

|
I really need this one. fortunately I found in my first search from google.
Again, Thanks a lot for sharing.
dnpro
"Very bad programmer"
|
|
|
|

|
What license is the code released under?
Thanks.
|
|
|
|

|
The do-whatever-you-want-licence.
"If knowledge can create problems, it is not through ignorance that we can solve them." Isaac Asimov
|
|
|
|
|

|
Is there any way to background highlight a line if it STARTS WITH "fox", then highlight the entire line AS THE USER IS TYPING ?
|
|
|
|

|
Thank you for the control; it's great. I gave you a 5.
BTW, I used your control in my application and I gave you credit at the bottom of the article. You can check out the article here: http://www.codeproject.com/KB/recipes/EvaluationEngine.aspx
Donald.
|
|
|
|

|
How can I undo and redo in SyntaxRichTextBox?
Please help me...
This is my signature.
|
|
|
|

|
Hi,
To solve Redo/Undo problem:
Use TextEditorControl_KeyUp event instead of TextEditorControl_TextChanged or TextEditorControl_KeyPress events.
Now, Redo/Undo works.
To bypass Redo/Undo selection steps, REWRITE a NEW Undo/Redo and DO base.Undo/base.Redo until Text property changes.
|
|
|
|

|
I do not really think that you need to rewrite the REDO or UNDO.
// <summary>
/// OnTextChanged
/// </summary>
/// <param name="e"></param>
protected override void OnKeyUp(KeyEventArgs e)
{
if (!e.Control)
{
m_nContentLength = this.TextLength;
int nCurrentSelectionStart = SelectionStart;
int nCurrentSelectionLength = SelectionLength;
m_bPaint = false;
// Find the start of the current line.
m_nLineStart = nCurrentSelectionStart;
while ((m_nLineStart > 0) && (Text[m_nLineStart - 1] != '\n'))
m_nLineStart--;
// Find the end of the current line.
m_nLineEnd = nCurrentSelectionStart;
while ((m_nLineEnd < Text.Length) && (Text[m_nLineEnd] != '\n'))
m_nLineEnd++;
// Calculate the length of the line.
m_nLineLength = m_nLineEnd - m_nLineStart;
// Get the current line.
m_strLine = Text.Substring(m_nLineStart, m_nLineLength);
// Process this line.
ProcessLine();
m_bPaint = true;
}
else if (e.KeyCode == Keys.Z)
{
base.OnKeyUp(e);
}
}
should be solving the problem, this is just a quick answer, you might find better idea to solve the problem
|
|
|
|

|
What if you are using html as syntax...
i tried "<html>" & "<html" both... i think "<" is not working..
I was using this RTF Box in a small html editor and taking preview on a WebBrowser, i tried to used TextChanged Event, the Event is not working the Break point on this point doesnt get a hit on text changed.
is it right?
--
ASif Ashraf
MCAD.Net,MCP
Asif.Log@gmail | hotmail.com
92-306-4526526
Sr. dotNet & Flash Developer
Blu Media Works LHR PK
|
|
|
|

|
Probably not.
"If knowledge can create problems, it is not through ignorance that we can solve them." Isaac Asimov
|
|
|
|

|
hmmm..
thats fine.. no problem ....
anyhow i checked and it dint work fine with me.. maybe my own fault... i just added keywords and did nothing else....
bye
--
ASif Ashraf
MCAD.Net,MCP
Asif.Log@gmail | hotmail.com
92-306-4526526
Sr. dotNet & Flash Developer
Blu Media Works LHR PK
|
|
|
|

|
I am using this code as the base of my syntax highlighter and there are several things that i've done to reduce loading time. Here is something you can do:
1. Process line when user hits space bar, rather than having it processed as a new char gets added.
2. Preload regular expressions. I have a DLL with all of my regular expressions in it. The dll is loaded once on start-up and then used throughout the code so that you don't create a new regex instance while abandoning the previous one.
3. Use standard RichTextBox operations to perform line calculations instead of doing everything in loops.
4. When processing a line, split it by empty space and use a for each loop to traverse through a line looking for keywords. This is more efficient than using for loops. I also used a balanced binary tree to store keywords which have already been highlighted and the position of their last character. This way, if i have a duplication keyword on one line i can keep track of them.
All of this reduced loading time significantly. You could also put some operations in threads if you wanted an even better performance.
|
|
|
|

|
How does one go about using adding these optimizations... Im kinda new at this.
|
|
|
|

|
How I Process line when user hits space bar?
This is my signature.
|
|
|
|
 |
|
|
General News Suggestion Question Bug Answer Joke Rant Admin
|
An article on how to enable syntax highlighting in a RichTextBox.
| Type | Article |
| Licence | |
| First Posted | 14 Jun 2005 |
| Views | 283,185 |
| Bookmarked | 208 times |
|
|