需要引用的DLL

DevExpress.CodeParser

DevExpress.Office

DevExpress.RichEdit

DevExpress.XtraRichEdit

 

MySyntaxHighlightServiceCSharp类

/// <summary>
/// This class implements the Execute method of the ISyntaxHighlightService interface to parse and colorize the text.
/// </summary>
public class MySyntaxHighlightServiceCSharp : ISyntaxHighlightService
{
readonly RichEditControl syntaxEditor;
SyntaxColors syntaxColors;
SyntaxHighlightProperties commentProperties;
SyntaxHighlightProperties keywordProperties;
SyntaxHighlightProperties stringProperties;
SyntaxHighlightProperties xmlCommentProperties;
SyntaxHighlightProperties textProperties; public MySyntaxHighlightServiceCSharp(RichEditControl syntaxEditor)
{
this.syntaxEditor = syntaxEditor;
syntaxColors = new SyntaxColors(UserLookAndFeel.Default);
} void HighlightSyntax(TokenCollection tokens)
{
commentProperties = new SyntaxHighlightProperties();
commentProperties.ForeColor = syntaxColors.CommentColor; keywordProperties = new SyntaxHighlightProperties();
keywordProperties.ForeColor = syntaxColors.KeywordColor; stringProperties = new SyntaxHighlightProperties();
stringProperties.ForeColor = syntaxColors.StringColor; xmlCommentProperties = new SyntaxHighlightProperties();
xmlCommentProperties.ForeColor = syntaxColors.XmlCommentColor; textProperties = new SyntaxHighlightProperties();
textProperties.ForeColor = syntaxColors.TextColor; if (tokens == null || tokens.Count == 0)
return; Document document = syntaxEditor.Document;
//CharacterProperties cp = document.BeginUpdateCharacters(0, 1);
List<SyntaxHighlightToken> syntaxTokens = new List<SyntaxHighlightToken>(tokens.Count);
foreach (Token token in tokens)
{
HighlightCategorizedToken((CategorizedToken)token, syntaxTokens);
}
document.ApplySyntaxHighlight(syntaxTokens);
//document.EndUpdateCharacters(cp);
}
void HighlightCategorizedToken(CategorizedToken token, List<SyntaxHighlightToken> syntaxTokens)
{
Color backColor = syntaxEditor.ActiveView.BackColor;
TokenCategory category = token.Category;
if (category == TokenCategory.Comment)
syntaxTokens.Add(SetTokenColor(token, commentProperties, backColor));
else if (category == TokenCategory.Keyword)
syntaxTokens.Add(SetTokenColor(token, keywordProperties, backColor));
else if (category == TokenCategory.String)
syntaxTokens.Add(SetTokenColor(token, stringProperties, backColor));
else if (category == TokenCategory.XmlComment)
syntaxTokens.Add(SetTokenColor(token, xmlCommentProperties, backColor));
else
syntaxTokens.Add(SetTokenColor(token, textProperties, backColor));
}
SyntaxHighlightToken SetTokenColor(Token token, SyntaxHighlightProperties foreColor, Color backColor)
{
int paragraphStart = DocumentHelper.GetParagraphStart(syntaxEditor.Document.Paragraphs[token.Range.Start.Line - 1]);
int tokenStart = paragraphStart + token.Range.Start.Offset - 1;
if (token.Range.End.Line != token.Range.Start.Line)
paragraphStart = DocumentHelper.GetParagraphStart(syntaxEditor.Document.Paragraphs[token.Range.End.Line - 1]); int tokenEnd = paragraphStart + token.Range.End.Offset - 1;
Debug.Assert(tokenEnd > tokenStart);
return new SyntaxHighlightToken(tokenStart, tokenEnd - tokenStart, foreColor);
} #region #ISyntaxHighlightServiceMembers
public void Execute()
{
string newText = syntaxEditor.Text;
// Determine language by file extension.
string ext = System.IO.Path.GetExtension(syntaxEditor.Options.DocumentSaveOptions.CurrentFileName);
//ParserLanguageID lang_ID = ParserLanguage.FromFileExtension(ext);
//// Do not parse HTML or XML.
//if (lang_ID == ParserLanguageID.Html ||
// lang_ID == ParserLanguageID.Xml ||
// lang_ID == ParserLanguageID.None) return;
ParserLanguageID lang_ID = ParserLanguageID.CSharp;
// Use DevExpress.CodeParser to parse text into tokens.
ITokenCategoryHelper tokenHelper = TokenCategoryHelperFactory.CreateHelper(lang_ID);
TokenCollection highlightTokens;
highlightTokens = tokenHelper.GetTokens(newText);
HighlightSyntax(highlightTokens);
} public void ForceExecute()
{
Execute();
}
#endregion #ISyntaxHighlightServiceMembers
}
/// <summary>
/// This class provides colors to highlight the tokens.
/// </summary>
public class SyntaxColors
{
static Color DefaultCommentColor { get { return Color.Green; } }
static Color DefaultKeywordColor { get { return Color.Blue; } }
static Color DefaultStringColor { get { return Color.Brown; } }
static Color DefaultXmlCommentColor { get { return Color.Gray; } }
static Color DefaultTextColor { get { return Color.Black; } }
UserLookAndFeel lookAndFeel; public Color CommentColor { get { return GetCommonColorByName(CommonSkins.SkinInformationColor, DefaultCommentColor); } }
public Color KeywordColor { get { return GetCommonColorByName(CommonSkins.SkinQuestionColor, DefaultKeywordColor); } }
public Color TextColor { get { return GetCommonColorByName(CommonColors.WindowText, DefaultTextColor); } }
public Color XmlCommentColor { get { return GetCommonColorByName(CommonColors.DisabledText, DefaultXmlCommentColor); } }
public Color StringColor { get { return GetCommonColorByName(CommonSkins.SkinWarningColor, DefaultStringColor); } } public SyntaxColors(UserLookAndFeel lookAndFeel)
{
this.lookAndFeel = lookAndFeel;
} Color GetCommonColorByName(string colorName, Color defaultColor)
{
Skin skin = CommonSkins.GetSkin(lookAndFeel);
if (skin == null)
return defaultColor;
return skin.Colors[colorName];
}
}

使用:

richEditControl1.ReplaceService<ISyntaxHighlightService>(new MySyntaxHighlightServiceCSharp(richEditControl1));

效果:

第二种,自定义:

public class CustomSyntaxHighlightService : ISyntaxHighlightService {
#region #parsetokens
readonly Document document;
SyntaxHighlightProperties defaultSettings = new SyntaxHighlightProperties() { ForeColor = Color.Black };
SyntaxHighlightProperties keywordSettings = new SyntaxHighlightProperties() { ForeColor = Color.Blue };
SyntaxHighlightProperties stringSettings = new SyntaxHighlightProperties() { ForeColor = Color.Green }; string[] keywords = new string[] {
"INSERT", "SELECT", "CREATE", "TABLE", "USE", "IDENTITY", "ON", "OFF", "NOT", "NULL", "WITH", "SET" }; public CustomSyntaxHighlightService(Document document) {
this.document = document;
} private List<SyntaxHighlightToken> ParseTokens() {
List<SyntaxHighlightToken> tokens = new List<SyntaxHighlightToken>();
DocumentRange[] ranges = null;
// search for quotation marks
ranges = document.FindAll("'", SearchOptions.None);
for (int i = 0; i < ranges.Length / 2; i++) {
tokens.Add(new SyntaxHighlightToken(ranges[i * 2].Start.ToInt(),
ranges[i * 2 + 1].Start.ToInt() - ranges[i * 2].Start.ToInt() + 1, stringSettings));
}
// search for keywords
for (int i = 0; i < keywords.Length; i++) {
ranges = document.FindAll(keywords[i], SearchOptions.CaseSensitive | SearchOptions.WholeWord); for (int j = 0; j < ranges.Length; j++) {
if (!IsRangeInTokens(ranges[j], tokens))
tokens.Add(new SyntaxHighlightToken(ranges[j].Start.ToInt(), ranges[j].Length, keywordSettings));
}
}
// order tokens by their start position
tokens.Sort(new SyntaxHighlightTokenComparer());
// fill in gaps in document coverage
AddPlainTextTokens(tokens);
return tokens;
} private void AddPlainTextTokens(List<SyntaxHighlightToken> tokens) {
int count = tokens.Count;
if (count == 0) {
tokens.Add(new SyntaxHighlightToken(0, document.Range.End.ToInt(), defaultSettings));
return;
}
tokens.Insert(0, new SyntaxHighlightToken(0, tokens[0].Start, defaultSettings));
for (int i = 1; i < count; i++) {
tokens.Insert(i * 2, new SyntaxHighlightToken(tokens[i * 2 - 1].End,
tokens[i * 2].Start - tokens[i * 2 - 1].End, defaultSettings));
}
tokens.Add(new SyntaxHighlightToken(tokens[count * 2 - 1].End,
document.Range.End.ToInt() - tokens[count * 2 - 1].End, defaultSettings));
} private bool IsRangeInTokens(DocumentRange range, List<SyntaxHighlightToken> tokens) {
for (int i = 0; i < tokens.Count; i++) {
if (range.Start.ToInt() >= tokens[i].Start && range.End.ToInt() <= tokens[i].End)
return true;
}
return false;
}
#endregion #parsetokens #region #ISyntaxHighlightServiceMembers
public void ForceExecute() {
Execute();
}
public void Execute() {
document.ApplySyntaxHighlight(ParseTokens());
}
#endregion #ISyntaxHighlightServiceMembers
}
#region #SyntaxHighlightTokenComparer
public class SyntaxHighlightTokenComparer : IComparer<SyntaxHighlightToken> {
public int Compare(SyntaxHighlightToken x, SyntaxHighlightToken y) {
return x.Start - y.Start;
}
}
#endregion #SyntaxHighlightTokenComparer

使用:

richEditControl1.ReplaceService<ISyntaxHighlightService>(new CustomSyntaxHighlightService(richEditControl1.Document));

效果:

dev RichText高亮的更多相关文章

  1. RichText实现动态输入关键字高亮颜色显示

    int a = 0; string[] kc = new string[40] { "private","protected","public&quo ...

  2. 12款最佳的 WordPress 语法高亮插件推荐

    语法高亮工具增强了代码的可读性,美化了代码,让程序员更容易维护.语法高亮提供各种方式由以提高可读性和文本语境,尤其是对于其中可以结束跨越多个页面的代码,以及让开发者自己的程序中查找错误.在这篇文章中, ...

  3. chrome dev tools

    chrome dev tools介绍一下Chrome dev tools 的基本使用和一些意想不到的小技巧.\\Chrome Developer Tools 是Chrome内嵌的一系列编辑和调试的工具 ...

  4. vue-11-路由嵌套-参数传递-路由高亮

    1, 新建vue-router 项目 vue init webpack vue-router-test 是否创建路由: 是 2, 添加路由列表页 在 component下创建 NavList 页面 & ...

  5. 微信小程序--搜索关键词高亮

    代码地址如下:http://www.demodashi.com/demo/14249.html 一.前期准备工作 软件环境:微信开发者工具 官方下载地址:https://mp.weixin.qq.co ...

  6. 【rich-text】 富文本组件说明

    [rich-text] 富文本组件可以显示HTML代码样式. 1)支持事件:tap.touchstart.touchmove.touchcancel.touchend和longtap 2)信任的HTM ...

  7. 2016.1.19 DEV Express控件GirdControl使用

    103.GridControl中添加Button RunDesigner,添加一列,设置对应字段FiledName,ColumnEdit选择ButtonEdit,此时默认风格像下拉框,需调整属性: 在 ...

  8. Elasticsearch实现复合查询,高亮结果等技巧

    一.Es的配置 实现es的全文检索功能的第一步,首先从与es进行连接开始,这里我使用的是es的5.x java api语法. public TransportClient esClient() thr ...

  9. 代码语法高亮踩坑-原理,问题, PRE元素及htmlentity

    语法高亮库基础原理 在研究使用能够在web页面上代码语法高显的解决方案时,发现有很多现成的开源库.比较中意的有prism.js,highlightjs.他们的原理基本上核心就两点: 1. 利用html ...

随机推荐

  1. linux添加字体的过程

    只说一下过程, 至于具体的原理还没搞明白. 1. 首先你要有字体文件,ttf或者ttc格式的均可以 我们可以从windows的 C:\WINDOWS\Fonts\ 这个目录下的字体文件复制出来,例如我 ...

  2. 【crunch bang】字体美化

    中文字体美化是个很讨厌的事情,无数初学者在这里面浪费了无数时间,做了无数没有意义的事情.但这也是不得不做的,我把 Debian/Ubuntu 所需要的中文字体美化操作步骤详细记录在这里,希望能节约大家 ...

  3. 下拉框分组显示optgroup

    <select> <optgroup label="语言"> <option>中文</option> <option>英 ...

  4. copyallwaterdata

    if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[copyallwaterdata]') and OBJECT ...

  5. 获取元素CSS值之getComputedStyle方法熟悉

    by zhangxinxu from http://www.zhangxinxu.com本文地址:http://www.zhangxinxu.com/wordpress/?p=2378 一.碎碎念~前 ...

  6. hashMap底层put和get方法逻辑

    1.hashmap put方法的实现: public V put(K key, V value) { if (key == null) return putForNullKey(value); int ...

  7. JSONArray传值的使用小结

    今天使用了SpringMVC+mybatis传值.从controller中传到service中.可是由于版本问题参数中不能有大写和下划线,在service中只能用String 来接受json字符串.接 ...

  8. Self Numbers 分类: POJ 2015-06-12 20:07 14人阅读 评论(0) 收藏

    Self Numbers Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 22101   Accepted: 12429 De ...

  9. Unity-Animator深入系列---剪辑播放后位置预判(Animator.Target)

    回到 Animator深入系列总目录 animator.SetTarget(...);可以在播放前预判剪辑播放后的位置,但只限于人形动画 参数1是预判的关节,参数2是映射的剪辑时间 调用后通过targ ...

  10. java 导入自定义类

    eclipse导入很容易,昨天上课学了一下用记事本写java,导入自定义类,这就麻烦了. 代码贴一下,方便操作: package tom.jiafei; public class SquareEqua ...