需要引用的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. 【crunch bang】文件管理器-thunar

    Thunar拥有的实用功能: 缩略图查看 批量重命名 安装: $ sudo apt-get install thunar 加速thunar启动速度 sudo leafpad /usr/share/gv ...

  2. Hadoop :map+shuffle+reduce和YARN笔记分享

    今天做了一个hadoop分享,总结下来,包括mapreduce,及shuffle深度讲解,还有YARN框架的详细说明等. v\:* {behavior:url(#default#VML);} o\:* ...

  3. android 项目学习随笔十四(WebView)

    1.布局文件 <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:andro ...

  4. UTF8转码, 考虑利用app转好再传, CC2541转太麻烦了...

  5. 各种数据库连接代码(java)

    SqlServer2000 Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver"); URL = "j ...

  6. javaWeb 使用cookie显示商品浏览记录

    package de.bvb.cookie; import java.io.IOException; import java.io.PrintWriter; import java.util.Date ...

  7. java继承关系中成员变量,构造方法,成员方法的关系

    Java继承中的成员关系 A:成员变量 a:子类的成员变量名称和父类中的成员变量名称不一样,这个太简单写那个名字就访问那个名字! b:子类的成员变量名称和父类中的成员变量名称一样,这个怎么访问呢? 子 ...

  8. [转]Rotate a table in reporting services

    转自:http://stackoverflow.com/questions/9002796/rotate-a-table-in-reporting-services 12down voteaccept ...

  9. Android 仿美团网,大众点评购买框悬浮效果之修改版

    转帖请注明本文出自xiaanming的博客(http://blog.csdn.net/xiaanming/article/details/17761431),请尊重他人的辛勤劳动成果,谢谢! 我之前写 ...

  10. SQLITE3 使用总结

    转自: http://blog.chinaunix.net/uid-8447633-id-3321394.html 前序: Sqlite3 的确很好用.小巧.速度快.但是因为非微软的产品,帮助文档总觉 ...