需要引用的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. OpenStack collectd的从零安装客户端

    1.查看是否需要增加yum 源 1 2 3 4 5 6 7 8 9 10 11 12 13 14 [root@node-12 ~]# yum search collectd Loaded plugin ...

  2. SQL UNION 操作符

    转由http://www.w3school.com.cn/sql/sql_union.asp 这个网址的数据库知识,个人推荐,因为有实例,理解更透彻一些.非广告啊,个人感觉好啊 SQL UNION 操 ...

  3. nginx负载均衡的实现

    将一台nginx主机当作前端负载均衡服务器,后面通过交换机链接多台web服务器,提供html和php的web界面服务.通过配置前端负载均衡服务器,可以实现将html界面和php界面的分开访问,即htm ...

  4. 强制类型转换(const_cast)

    [1] const_cast的作用 一.常量指针被转化成非常量指针,并且仍然指向原来的对象: 二.常量引用被转换成非常量引用,并且仍然指向原来的对象: 三.常量对象被转换成非常量对象. [2] 实例代 ...

  5. android 应用架构随笔一(架构搭建)

    1.拷贝积累utils以及PagerTab类 2.定义BaseApplication类 3.定义BaseActivity类 4.改写MainActivity 5.定义布局文件 6.定义BaseFrag ...

  6. struts2 笔记03 异常支持、防止页面刷新和后退、方法验证

    Struts2对异常支持(声明式异常.自动的异常处理), 异常处理(运行期异常事务自动回滚) 1. 自定义异常类,继承RuntimeException或Exception实现构造方法. 2. 配置异常 ...

  7. PHP使用PHPExcel删除Excel单元格指定列的方法是怎样

    有一个系统仅公司内部和外部经销商使用,在一个导出功能中公司内部员工跟外部经销商导出的列是不一样的(某些数据是不能提供给经销商的)因为导出的数据都是一样的(某些列外数据外部没有)因此并没有单独处理,而是 ...

  8. Communication System(dp)

    Communication System Time Limit: 1000MS Memory Limit: 10000K Total Submissions: 25006 Accepted: 8925 ...

  9. Collection的toArray()使用上需要注意的地方

    转载:http://llade.iteye.com/blog/199818 Collection在很多情况下需要转换为数组来处理(很多接口方法都使用array作为参数). Collection的toA ...

  10. 灰色预测模型 c# 算法实现

     public class GrayModel    {        private double a0, a1, a2;        private int size;        priva ...