我是 WPF 新手,目前我正在研究创建一个具有语法突出显示的 Sublime Text。我在找出当前插入符号位置的单词 TextRange 时遇到了挑战(不包括符号,例如:for(将返回整个单词而不是仅返回)。此外,因为解决方案已经在检查整个文件,这可能会减少性能显着。有没有解决这个问题的方法谢谢!下面是我的代码
private TextRange getCurrentWordRange()
{
List<string> spaces = new List<string> { " ", "\t" ,";","(", ")", "=" };
List<string> symbols=new List<string>{};
TextPointer current = richTextBox.CaretPosition;
TextPointer start = current, end = current;
//Traverse to get the start of word
while (start.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text)
{
TextRange textRange = new TextRange(start.GetPositionAtOffset(-1), start); // get the textRange of the previous start
if (spaces.Any(token => textRange.Text.Contains(token))) // check if textRange.Text has token that inside spaces
break;
else
start = start.GetPositionAtOffset(-1);
}
//Traverse to get the end of word
while(end.GetPointerContext(LogicalDirection.Forward)==TextPointerContext.Text)
{
TextRange textRange = new TextRange(end,end.GetPositionAtOffset(1)); // get the textRange of the next start
if (spaces.Any(token => textRange.Text.Contains(token)))
break;
else
end = end.GetPositionAtOffset(1);
}
return new TextRange(start,end);
}
编辑 幸运的是,我重新考虑并编写了下面的代码,这可能会成功。希望任何人都可以检查它是否正确。谢谢你。
private TextRange getCurrentWordRange()
{
List<string> spaces = new List<string> { " ", "\t" };
List<string> symbols = new List<string> { ";", "(", ")", "=", "<", ">", "\"", ",", ".", "[", "]", ":" };
TextPointer current = richTextBox.CaretPosition;
TextPointer start = current, end = current;
TextRange backward;
TextRange forward;
// check if start and end are not the Content.Start and Content.End
if (start.GetPositionAtOffset(-1) == null)
backward = new TextRange(start, start);
else
backward = new TextRange(start.GetPositionAtOffset(-1), start);
if (end.GetPositionAtOffset(1) == null)
forward = new TextRange(end, end);
else
forward = new TextRange(end, end.GetPositionAtOffset(1));
while (!spaces.Contains(backward.Text) && start.GetPointerContext(LogicalDirection.Backward) == TextPointerContext.Text && !symbols.Contains(backward.Text))
{
start = start.GetPositionAtOffset(-1);
backward = new TextRange(start, start.GetPositionAtOffset(-1));
}
while (!spaces.Contains(forward.Text) && end.GetPointerContext(LogicalDirection.Forward) == TextPointerContext.Text && !symbols.Contains(forward.Text))
{
end = end.GetPositionAtOffset(1);
forward = new TextRange(end, end.GetPositionAtOffset(1));
}
// if between start and end is "" then consider add a left adjacent or right adjacent symbol for further development
if (new TextRange(start, end).Text == "")
{
if (symbols.Contains(backward.Text))
{
start = start.GetPositionAtOffset(-1);
}
else if (symbols.Contains(forward.Text))
{
end = end.GetPositionAtOffset(-1);
}
}
return new TextRange(start, end);
}
我为 RTB 创建了一个 TextChanged 事件,然后执行一些功能来检查和突出显示关键字它与 @Jackdaw 解决方案配合得很好,但又陷入了这种情况