|
Hi,
what about multi-line comments ? this is not implemented.
--[[
Multi-line comment 1
Multi-line comment 2
]]
Domi.
|
|
|
|
|
//Hi everybody, I modified the source code in order to produce a code and sql editor. Here is my code.
//Please any enhancement let me know at: aaron.ibanez@godcorporation.com
//-----------------------------------------------------------------------------------------
using DbMappingFactoryCodeGen.CodeGen;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DbMappingFactoryCodeGen.CodeEditor
{
public class CodeEditorTextBox : RichTextBox
{
private readonly Dictionary<languageeditortype, keyword=""> m_Keywords = new Dictionary<languageeditortype, keyword="">()
{
{
LanguageEditorType.CSharp, new Keyword(){
HighlightKewords = @"\b(abstract|as|base|bool|break|byte|case|catch|char|checked|class|const|continue|decimal|default|delegate|do|double|else|enum|event|explicit|extern|false|finally|fixed|float|for|" +
@"foreach|get|goto|if|implicit|in|int|interface|internal|is|lock|long|namespace|new|null|object|operator|out|override|params|private|protected|public|readonly|ref|return|sbyte|sealed|" +
@"set|short|sizeof|stackalloc|static|string|struct|switch|this|throw|true|try|typeof|uint|ulong|unchecked|unsafe|ushort|using|virtual|volatile|void|while|System.DateTime|#region|#endregion)\b",
HighlightKewordsColor = Color.Blue,
HighlightComments = @"(@(?:""[^""]*"")+|""(?:[^""\n\\]+|\\.)*""|'(?:[^'\n\\]+|\\.)*')|//.*|/\*(?s:.*?)\*/",
HighlightCommentsColor = Color.Green,
CaseSensitive = true,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.LightGray,
HighlightStrings = "\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"",
HighlightStringsColor = Color.Red
}
},
{
LanguageEditorType.VB, new Keyword() {
HighlightKewords = @"\b(AddHandler|AddressOf|Alias|And|AndAlso|As|Assembly|Boolean|ByRef|Byte|ByVal|Call|Case|Catch|CBool|CByte|CChar|CDate|CDec|CDbl|Char|CInt|Class|CLng|CObj|Const|Continue|Compare|CSByte|CShort|CSng|CStr|" +
@"CType|CUInt|CULng|CUShort|Date|Decimal|Declare|Default|Delegate|Dim|DirectCast|Do|Double|Each|Else|ElseIf|End|EndIf|Enum|Erase|Error|Event|Exit|False|Finally|For|Friend|Function|Get|" +
@"GetType|GetXMLNamespace|Global|GoSub|GoTo|Handles|If|Implements|Imports|In|Inherits|Integer|Interface|Is|IsNot|Let|Lib|Like|Long|Loop|Me|Mid|Mod|Module|MustInherit|MustOverride|MyBase|MyClass|" +
@"Namespace|Narrowing|New|Next|Not|Nothing|NotInheritable|NotOverridable|Object|Of|On|Operator|Option|Optional|Or|OrElse|Overloads|Overridable|Overrides|ParamArray|Partial|Preserve|Private|Property|" +
@"Protected|Public|RaiseEvent|ReadOnly|ReDim|REM|RemoveHandler|Repeat|Resume|Return|SByte|Select|Set|Shadows|Shared|Short|Single|Static|Step|Stop|Strict|String|Structure|Sub|SyncLock|Then|Throw|To|True|Try|" +
@"TryCast|TypeOf|Variant|Wend|UInteger|ULong|Until|UShort|Using|When|While|Widening|With|WithEvents|#Region|#End Region)\b",
HighlightKewordsColor = Color.Blue,
HighlightComments = @"(^'|'').*?$",
HighlightCommentsColor = Color.Green,
CaseSensitive = false,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.LightGray,
HighlightStrings = "\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"",
HighlightStringsColor = Color.Red
}
},
{
LanguageEditorType.TSql, new Keyword() {
HighlightKewords = @"\b(absolute|action|ada|add|admin|after|aggregate|alias|all|allocate|alter|and|any|are|array|as|asc|asensitive|assertion|asymmetric|at|atomic|authorization|avg|" +
@"backup|before|begin|between|binary|bit|bit_length|blob|boolean|both|breadth|break|browse|bulk|by|call|called|cardinality|cascade|cascaded|case|cast|catalog|char|" +
@"char_length|character|character_length|check|checkpoint|class|clob|close|clustered|coalesce|collate|collation|collect|column|commit|completion|compute|condition|" +
@"connect|connection|constraint|constraints|constructor|contains|containstable|continue|convert|corr|corresponding|count|covar_pop|covar_samp|create|cross|cube|cume_dist|" +
@"current|current_catalog|current_date|current_default_transform_group|current_path|current_role|current_schema|current_time|current_timestamp|current_transform_group_for_type|" +
@"current_user|cursor|cycle|data|database|date|day|dbcc|deallocate|dec|decimal|declare|default|deferrable|deferred|delete|deny|depth|deref|desc|describe|descriptor|destroy|" +
@"destructor|deterministic|diagnostics|dictionary|disconnect|disk|distinct|distributed|domain|double|drop|dump|dynamic|each|element|else|end|end-exec|equals|errlvl|escape|every|" +
@"except|exception|exec|execute|exists|exit|external|extract|false|fetch|file|fillfactor|filter|first|float|for|foreign|fortran|found|free|freetext|freetexttable|from|full|" +
@"fulltexttable|function|fusion|general|get|global|go|goto|grant|group|grouping|having|hold|holdlock|host|hour|identity|identity_insert|identitycol|if|ignore|immediate|in|" +
@"include|index|indicator|initialize|initially|inner|inout|input|insensitive|insert|int|integer|intersect|intersection|interval|into|is|isolation|iterate|join|key|kill|language|" +
@"large|last|lateral|leading|left|less|level|like|like_regex|limit|lineno|ln|load|local|localtime|localtimestamp|locator|lower|map|match|max|member|merge|method|min|minute|mod|" +
@"modifies|modify|module|month|multiset|names|national|natural|nchar|nclob|new|next|no|nocheck|nonclustered|none|normalize|not|null|nullif|numeric|object|occurrences_regex|" +
@"octet_length|of|off|offsets|old|on|only|open|opendatasource|openquery|openrowset|openxml|operation|option|or|order|ordinality|out|outer|output|over|overlaps|overlay|pad|" +
@"parameter|parameters|partial|partition|pascal|path|percent|percent_rank|percentile_cont|percentile_disc|pivot|plan|position|position_regex|postfix|precision|prefix|preorder|" +
@"prepare|preserve|primary|print|prior|privileges|proc|procedure|public|raiserror|range|read|reads|readtext|real|reconfigure|recursive|ref|references|referencing|regr_avgx|" +
@"regr_avgy|regr_count|regr_intercept|regr_r2|regr_slope|regr_sxx|regr_sxy|regr_syy|relative|release|replication|restore|restrict|result|return|returns|revert|revoke|right|" +
@"role|rollback|rollup|routine|row|rowcount|rowguidcol|rows|rule|save|savepoint|schema|scope|scroll|search|second|section|securityaudit|select|sensitive|sequence|session|" +
@"session_user|set|sets|setuser|shutdown|similar|size|smallint|some|space|specific|specifictype|sql|sqlca|sqlcode|sqlerror|sqlexception|sqlstate|sqlwarning|start|state|statement|" +
@"static|statistics|stddev_pop|stddev_samp|structure|submultiset|substring|substring_regex|sum|symmetric|system|system_user|table|tablesample|temporary|terminate|textsize|than|" +
@"then|time|timestamp|timezone_hour|timezone_minute|to|top|trailing|tran|transaction|translate|translate_regex|translation|treat|trigger|trim|true|truncate|tsequal|uescape|under|" +
@"union|unique|unknown|unnest|unpivot|update|updatetext|upper|usage|use|user|using|value|values|var_pop|var_samp|varchar|variable|varying|view|waitfor|when|whenever|where|while|" +
@"width_bucket|window|with|within|without|work|write|writetext|xmlagg|xmlattributes|xmlbinary|xmlcast|xmlcomment|xmlconcat|xmldocument|xmlelement|xmlexists|xmlforest|xmliterate|" +
@"xmlnamespaces|xmlparse|xmlpi|xmlquery|xmlserialize|xmltable|xmltext|xmlvalidate|year|zone)\b",
HighlightKewordsColor = Color.Blue,
HighlightComments = @"(/\*(.|[\r\n])*?\*/)|(--(.*|[\r\n]))",
HighlightCommentsColor = Color.Green,
CaseSensitive = false,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.Gray,
HighlightStrings = "'(?:''|[^']*)*'",
HighlightStringsColor = Color.Red
}
},
{
LanguageEditorType.PlSql, new Keyword() {
HighlightKewords = // Table D-1 PL/SQL Reserved Words
@"\b(ALL|ALTER|AND|ANY|AS|ASC|AT|BEGIN|BETWEEN|BY|CASE|CHECK|CLUSTER|CLUSTERS|COLAUTH|COLUMNS|COMPRESS|CONNECT|CRASH|CREATE|CURRENT|DECLARE|DEFAULT|DELETE|DESC|" +
@"DISTINCT|DROP|ELSE|END|EXCEPTION|EXCLUSIVE|EXISTS|FETCH|FOR|FROM|GOTO|GRANT|GROUP|HAVING|IDENTIFIED|IF|IN|INDEX|INDEXES|INSERT|INTERSECT|INTO|IS|LIKE|LOCK|" +
@"MINUS|MODE|NOCOMPRESS|NOT|NOWAIT|NULL|OF|ON|OPTION|OR|ORDER|OVERLAPS|PRIOR|PROCEDURE|PUBLIC|RESOURCE|REVOKE|SELECT|SHARE|SIZE|SQL|START|TABAUTH|TABLE|THEN|TO|" +
@"UNION|UNIQUE|UPDATE|VALUES|VIEW|VIEWS|WHEN|WHERE|WITH|" +
// Table D-2 PL/SQL Keywords
@"ADD|AGENT|AGGREGATE|ARRAY|ATTRIBUTE|AUTHID|AVG|BFILE_BASE|BINARY|BLOB_BASE|BLOCK|BODY|BOTH|BOUND|BULK|BYTE|CALL|CALLING|CASCADE|CHAR|CHAR_BASE|CHARACTER|CHARSETFORM|" +
@"CHARSETID|CHARSET|CLOB_BASE|CLOSE|COLLECT|COMMENT|COMMIT|COMMITTED|COMPILED|CONSTANT|CONSTRUCTOR|CONTEXT|CONTINUE|CONVERT|COUNT|CURSOR|CUSTOMDATUM|DANGLING|DATA|DATE|" +
@"DATE_BASE|DAY|DEFINE|DETERMINISTIC|DOUBLE|DURATION|ELEMENT|ELSIF|EMPTY|ESCAPE|EXCEPT|EXCEPTIONS|EXECUTE|EXIT|EXTERNAL|FINAL|FIXED|FLOAT|FORALL|FORCE|FUNCTION|GENERAL|" +
@"HASH|HEAP|HIDDEN|HOUR|IMMEDIATE|INCLUDING|INDICATOR|INDICES|INFINITE|INSTANTIABLE|INT|INTERFACE|INTERVAL|INVALIDATE|ISOLATION|JAVA|LANGUAGE|LARGE|LEADING|LENGTH|LEVEL|" +
@"LIBRARY|LIKE2|LIKE4|LIKEC|LIMIT|LIMITED|LOCAL|LONG|LOOP|MAP|MAX|MAXLEN|MEMBER|MERGE|MIN|MINUTE|MOD|MODIFY|MONTH|MULTISET|NAME|NAN|NATIONAL|NATIVE|NCHAR|NEW|NOCOPY|NUMBER_BASE|" +
@"OBJECT|OCICOLL|OCIDATETIME|OCIDATE|OCIDURATION|OCIINTERVAL|OCILOBLOCATOR|OCINUMBER|OCIRAW|OCIREFCURSOR|OCIREF|OCIROWID|OCISTRING|OCITYPE|ONLY|OPAQUE|OPEN|OPERATOR|ORACLE|ORADATA|" +
@"ORGANIZATION|ORLANY|ORLVARY|OTHERS|OUT|OVERRIDING|PACKAGE|PARALLEL_ENABLE|PARAMETER|PARAMETERS|PARTITION|PASCAL|PIPE|PIPELINED|PRAGMA|PRECISION|PRIVATE|RAISE|RANGE|RAW|READ|" +
@"RECORD|REF|REFERENCE|RELIES_ON|REM|REMAINDER|RENAME|RESULT|RESULT_CACHE|RETURN|RETURNING|REVERSE|ROLLBACK|ROW|SAMPLE|SAVE|SAVEPOINT|SB1|SB2|SB4|SECOND|SEGMENT|SELF|SEPARATE|" +
@"SEQUENCE|SERIALIZABLE|SET|SHORT|SIZE_T|SOME|SPARSE|SQLCODE|SQLDATA|SQLNAME|SQLSTATE|STANDARD|STATIC|STDDEV|STORED|STRING|STRUCT|STYLE|SUBMULTISET|SUBPARTITION|SUBSTITUTABLE|" +
@"SUBTYPE|SUM|SYNONYM|TDO|THE|TIME|TIMESTAMP|TIMEZONE_ABBR|TIMEZONE_HOUR|TIMEZONE_MINUTE|TIMEZONE_REGION|TRAILING|TRANSACTION|TRANSACTIONAL|TRUSTED|TYPE|UB1|UB2|UB4|UNDER|UNSIGNED|" +
@"UNTRUSTED|USE|USING|VALIST|VALUE|VARIABLE|VARIANCE|VARRAY|VARYING|VOID|WHILE|WORK|WRAPPED|WRITE|YEAR|ZONE)\b",
HighlightKewordsColor = Color.Chocolate,
HighlightComments = @"(?ms)((? :\s+/\*(?:.(?!\*/))+.\*/)|(?:\s+\-\-[^\r\n]+))*)\s*^\s*([^\-/\s][^;]+;)((? :\s+/\*(?:.(?!\*/))+.\*/)|(?:\s+\-\-[^\r\n]+))*)",
HighlightCommentsColor = Color.Green,
CaseSensitive = false,
HighlightNumbers = "\\b(?:[0-9]*\\.)?[0-9]+\\b",
HighlightNumbersColor = Color.Gray,
HighlightStrings = "'(?:''|[^']*)*'",
HighlightStringsColor = Color.Blue
}
}
};
public LanguageEditorType Language { get; set; }
private static bool m_bPaint = true;
private string m_strLine = "";
private int m_nContentLength = 0;
private int m_nLineLength = 0;
private int m_nLineStart = 0;
private int m_nLineEnd = 0;
private int m_nCurSelection = 0;
///
/// WndProc
///
/// <param name="m" />
protected override void WndProc(ref System.Windows.Forms.Message m)
{
if (m.Msg == 0x00f)
{
if (m_bPaint)
base.WndProc(ref m);
else
m.Result = IntPtr.Zero;
}
else
base.WndProc(ref m);
}
///
/// OnTextChanged
///
/// <param name="e" />
protected override void OnTextChanged(EventArgs e)
{
//base.OnTextChanged(e);
// Calculate sh*t here.
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);
this.ProcessAllLines();
m_bPaint = true;
}
///
/// Process a line.
///
private void ProcessLine()
{
// Save the position and make the whole line black
int nPosition = SelectionStart;
SelectionStart = m_nLineStart;
SelectionLength = m_nLineLength;
SelectionColor = Color.Black;
Keyword keyword = this.m_Keywords[Language];
// Process the keywords
this.ProcessRegex(keyword.HighlightKewords, keyword.HighlightKewordsColor, keyword.CaseSensitive);
// Process numbers
this.ProcessRegex(keyword.HighlightNumbers, keyword.HighlightNumbersColor, false);
// Process strings
this.ProcessRegex(keyword.HighlightStrings, keyword.HighlightStringsColor, false);
// Process comments
this.ProcessRegex(keyword.HighlightComments, keyword.HighlightCommentsColor, false);
SelectionStart = nPosition;
SelectionLength = 0;
SelectionColor = Color.Black;
m_nCurSelection = nPosition;
}
///
/// Process a regular expression.
///
/// <param name="strRegex" />The regular expression.
/// <param name="color" />The color.
private void ProcessRegex(string strRegex, Color color, bool caseSensitive)
{
Regex regKeywords = new Regex(strRegex, RegexOptions.Multiline |
(caseSensitive
? RegexOptions.Compiled
: RegexOptions.IgnoreCase | RegexOptions.Compiled));
Match regMatch;
for (regMatch = regKeywords.Match(m_strLine); regMatch.Success; regMatch = regMatch.NextMatch())
{
// Process the words
int nStart = m_nLineStart + regMatch.Index;
int nLenght = regMatch.Length;
SelectionStart = nStart;
SelectionLength = nLenght;
SelectionColor = color;
}
}
///
/// Process all lines
///
public void ProcessAllLines()
{
m_bPaint = false;
int nStartPos = 0;
int i = 0;
int nOriginalPos = SelectionStart;
while (i < Lines.Length)
{
m_strLine = Lines[i];
m_nLineStart = nStartPos;
m_nLineEnd = m_nLineStart + m_strLine.Length;
this.ProcessLine();
i++;
nStartPos += m_strLine.Length + 1;
}
m_bPaint = true;
}
}
public class Keyword
{
public string HighlightKewords { get; set; }
public Color HighlightKewordsColor { get; set; }
public string HighlightComments { get; set; }
public Color HighlightCommentsColor { get; set; }
public bool CaseSensitive { get; set; }
public string HighlightNumbers { get; set; }
public Color HighlightNumbersColor { get; set; }
public string HighlightStrings { get; set; }
public Color HighlightStringsColor { get; set; }
}
public enum LanguageEditorType
{
CSharp = LanguageType.CSharp,
VB = LanguageType.VB,
TSql,
PlSql
}
}
Ing. Aarón Ibáñez Werthermänn
IBM Certified Specialist for RUP
Microsoft Certified Trainer
MCSD .NET, MCAD
|
|
|
|
|
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 wanted only unformated text Because I have my editor set to courier. I added this code to paste one line at a time from the clipboard to get all lines processed.
private void m_syntaxRichTextBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.V)
{
e.SuppressKeyPress = true;
String textfromclipboard = Clipboard.GetText(System.Windows.Forms.TextDataFormat.Text);
if(textfromclipboard!="")
{
foreach (var myString in textfromclipboard.Split(new string[] { Environment.NewLine }, StringSplitOptions.None))
{
m_syntaxRichTextBox.SelectedText = myString;
m_syntaxRichTextBox.SelectedText = Environment.NewLine;
}
}
}
}
|
|
|
|
|
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();
}
}
}
|
|
|
|
|
Thanks this is very helpful and much better than the original code!
I wondered what you can do by now if you were a bigineer when you wrote this piece of code.
|
|
|
|
|
|
|
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:20am.
|
|
|
|
|
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
|
|
|
|
|
|
I've noticed that most of these "My vote of 1" characters never specify why they voted that way and if you look at their history, this is their only post. Also many of these types of postings occur years after when the article was published and after Windows/.Net/technology has changed significantly.
|
|
|
|
|
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()
[...]
<br />
m_syntaxRichTextBox.LoadFile("../script.lua", RichTextBoxStreamType.PlainText);<br />
<br />
SyntaxHighlighter.RtfColoring.ProcessRtfColoring(m_syntaxRichTextBox);<br />
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(...
<br />
using System;<br />
using System.Text.RegularExpressions;<br />
<br />
namespace SyntaxHighlighter<br />
{<br />
public static class RtfColoring<br />
{<br />
public static void ProcessRtfColoring(SyntaxRichTextBox richTextBox)<br />
{<br />
SyntaxSettings Settings = richTextBox.Settings;<br />
if (Settings.Keywords.Count < 1)<br />
return;<br />
<br />
string strTextToAdd = richTextBox.Text;<br />
richTextBox.Clear();<br />
richTextBox.AppendText(strTextToAdd);<br />
string strRTF = richTextBox.Rtf;<br />
<br />
int iRTFLoc = strRTF.IndexOf("\\rtf");<br />
<br />
int iInsertLoc = strRTF.IndexOf('{', iRTFLoc);<br />
<br />
if (iInsertLoc == -1) iInsertLoc = strRTF.IndexOf('}', iRTFLoc) - 1;<br />
<br />
string strCommentColor = "\\red" + Settings.CommentColor.R.ToString() + <br />
"\\green" + Settings.CommentColor.G.ToString() + <br />
"\\blue" + Settings.CommentColor.B.ToString();<br />
<br />
string strStringColor = "\\red" + Settings.StringColor.R.ToString() +<br />
"\\green" + Settings.StringColor.G.ToString() + <br />
"\\blue" + Settings.StringColor.B.ToString();<br />
<br />
string strKeywordColor = "\\red" + Settings.KeywordColor.R.ToString() +<br />
"\\green" + Settings.KeywordColor.G.ToString() + <br />
"\\blue" + Settings.KeywordColor.B.ToString();<br />
<br />
string strIntegerColor = "\\red" + Settings.IntegerColor.R.ToString() +<br />
"\\green" + Settings.IntegerColor.G.ToString() + <br />
"\\blue" + Settings.IntegerColor.B.ToString();<br />
<br />
strRTF = strRTF.Insert(iInsertLoc, "{\\colortbl ;" + strCommentColor + ";" + strStringColor + ";" + strKeywordColor + ";" + strIntegerColor + ";}");<br />
<br />
string strKeywords = String.Empty;<br />
foreach (string keyword in Settings.Keywords)<br />
{<br />
strKeywords += keyword + ",";<br />
}<br />
strKeywords = strKeywords.Substring(0, strKeywords.Length - 1);<br />
<br />
Regex r = new Regex(@", ?");<br />
strKeywords = @"\b(" + r.Replace(strKeywords, @"|") + @")\b";<br />
<br />
r = new Regex(strKeywords, RegexOptions.Singleline | RegexOptions.IgnoreCase);<br />
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchKeyword));<br />
<br />
r = new Regex("(\\b(?:[0-9]*\\.)?[0-9]+\\b)", RegexOptions.IgnoreCase);<br />
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchInteger));<br />
<br />
r = new Regex("("+Settings.Comment+".*$)", RegexOptions.Multiline | RegexOptions.IgnoreCase);<br />
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchComment));<br />
<br />
r = new Regex("(\"[^\"\\\\\\r\\n]*(?:\\\\.[^\"\\\\\\r\\n]*)*\"|\'[^\'\\\\\\r\\n]*(?:\\\\.[^\'\\\\\\r\\n]*)*\')", RegexOptions.Singleline | RegexOptions.IgnoreCase);<br />
strRTF = r.Replace(strRTF, new MatchEvaluator(MatchString));<br />
<br />
richTextBox.Rtf = strRTF;<br />
}<br />
<br />
private static string MatchKeyword(Match match)<br />
{<br />
if (match.Groups[1].Success)<br />
{<br />
return @"\cf3 " + RemoveRtfColors(match.Value) + @"\cf0 ";<br />
}<br />
<br />
return String.Empty;<br />
}<br />
<br />
private static string MatchString(Match match)<br />
{<br />
if (match.Groups[1].Success)<br />
{<br />
return @"\cf2 " + RemoveRtfColors(match.Value) + @"\cf0 ";<br />
}<br />
<br />
return String.Empty;<br />
}<br />
<br />
private static string MatchComment(Match match)<br />
{<br />
if (match.Groups[1].Success)<br />
{<br />
return @"\cf1 " + RemoveRtfColors(match.Value) + @"\cf0 ";<br />
}<br />
<br />
return String.Empty;<br />
}<br />
<br />
private static string MatchInteger(Match match)<br />
{<br />
if (match.Groups[1].Success)<br />
{<br />
return @"\cf4 " + RemoveRtfColors(match.Value) + @"\cf0 ";<br />
}<br />
<br />
return String.Empty;<br />
}<br />
<br />
private static string RemoveRtfColors(string strText)<br />
{<br />
Regex r = new Regex(@"\\cf[0-9] ");<br />
strText = r.Replace(strText, "");<br />
<br />
return strText;<br />
}<br />
}<br />
<br />
}<br />
<br />
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
|
|
|
|
|