Xtext - 带退格键的自动编辑
Xtext - AutoEdits with backspace
假设以下情况:
我们有一个文档,其中包含空格
( 例如表示为 _ )
我们在那些 (4) 个空格后面有插入符号[=18=]
_ _ _ _|
我希望编辑器在用户按下退格键时删除所有 4 个空格而不是一个。
我正在扩展 DefaultIndentLineAutoEditStrategy,在其中覆盖以下方法
public void customizeDocumentCommand(IDocument d, DocumentCommand c)
我面临两个问题:
- 如何检测 DocumentCommand 是否使用了退格键?如果你使用换行符
c.text
包含 "\n"
或 "\r\n"
但如果你使用退格键它等于 ""
.
- 如何再插入 3 个退格键?将
"\b"
附加到 c.text
不起作用。
好的,我成功实现了。
if (c.text.equals("") && c.length == 1)
条件检测 backspace/delete 的用法
- 再删除3个字符可按如下方式完成:
c.offset-=3;
c.length=4;
整个实现看起来像这样:
private void handleBackspace(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
IRegion info;
try {
info = d.getLineInformationOfOffset(p);
String line = d.get(info.getOffset(), info.getLength());
int lineoffset = info.getOffset();
/*Make sure unindent is made only if user is indented and has caret in correct position */
if ((p-lineoffset+1)%4==0&&((line.startsWith(" ") && !line.startsWith(" ")) || (line.startsWith(" ") && !line.startsWith(" ")))){ //1 or 2 level fixed indent
c.offset-=3;
c.length=4;
}
}catch (org.eclipse.jface.text.BadLocationException e) {
e.printStackTrace();
}
}
假设以下情况:
我们有一个文档,其中包含空格
( 例如表示为 _ )
我们在那些 (4) 个空格后面有插入符号[=18=]
_ _ _ _|
我希望编辑器在用户按下退格键时删除所有 4 个空格而不是一个。
我正在扩展 DefaultIndentLineAutoEditStrategy,在其中覆盖以下方法
public void customizeDocumentCommand(IDocument d, DocumentCommand c)
我面临两个问题:
- 如何检测 DocumentCommand 是否使用了退格键?如果你使用换行符
c.text
包含"\n"
或"\r\n"
但如果你使用退格键它等于""
. - 如何再插入 3 个退格键?将
"\b"
附加到c.text
不起作用。
好的,我成功实现了。
if (c.text.equals("") && c.length == 1)
条件检测 backspace/delete 的用法
- 再删除3个字符可按如下方式完成:
c.offset-=3; c.length=4;
整个实现看起来像这样:
private void handleBackspace(IDocument d, DocumentCommand c) {
if (c.offset == -1 || d.getLength() == 0)
return;
int p = (c.offset == d.getLength() ? c.offset - 1 : c.offset);
IRegion info;
try {
info = d.getLineInformationOfOffset(p);
String line = d.get(info.getOffset(), info.getLength());
int lineoffset = info.getOffset();
/*Make sure unindent is made only if user is indented and has caret in correct position */
if ((p-lineoffset+1)%4==0&&((line.startsWith(" ") && !line.startsWith(" ")) || (line.startsWith(" ") && !line.startsWith(" ")))){ //1 or 2 level fixed indent
c.offset-=3;
c.length=4;
}
}catch (org.eclipse.jface.text.BadLocationException e) {
e.printStackTrace();
}
}