使用Eclipse SWT StyledText小部件,如何使用制表符或shift + tab键缩进/取消缩进选定的文本块?
答案 0 :(得分:1)
这似乎可以解决问题......
protected Control createContents(Composite parent){
......
//add the listeners...
text_code_impl.addVerifyKeyListener(new VerifyKeyListener() {
public void verifyKey(VerifyEvent e) {
if (e.keyCode == SWT.TAB) {
if ((e.stateMask & SWT.SHIFT) != 0){
e.doit = text_code_impl_shift_tab_pressed();
} else {
e.doit = text_code_impl_tab_pressed();
}
}
}
});
text_code_impl.addTraverseListener(new TraverseListener() {
public void keyTraversed(TraverseEvent e) {
if (e.detail == SWT.TRAVERSE_TAB_PREVIOUS) {
e.doit = false; //allows verifyKey listener to fire
}
}
});
}
boolean text_code_impl_tab_pressed()
{
if (text_code_impl.getSelectionText().equals("")){
return true;
}
Point range = text_code_impl.getSelectionRange();
int start = range.x;
int length = text_code_impl.getSelectionCount();
String txt = text_code_impl.getText();
while (start > 0 && txt.charAt(start-1) != '\n') {
start--;
length++;
}
int replace_length = length;
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
String sel_text = text_code_impl.getSelectionText();
String[] lines = sel_text.split("\n");
String new_text = "";
for (int x=0; x < lines.length; x++){
if (x > 0){
new_text += '\n';
}
new_text += '\t';
length++;
new_text += lines[x];
}
text_code_impl.replaceTextRange(start, replace_length, new_text);
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
return false;
}
boolean text_code_impl_shift_tab_pressed()
{
if (text_code_impl.getSelectionText().equals("")){
return true;
}
Point range = text_code_impl.getSelectionRange();
int start = range.x;
int length = text_code_impl.getSelectionCount();
String txt = text_code_impl.getText();
while (start > 0 && txt.charAt(start-1) != '\n') {
--start;
++length;
}
int replace_length = length;
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
String sel_text = text_code_impl.getSelectionText();
String[] lines = sel_text.split("\n");
String new_text = "";
for (int x=0; x < lines.length; x++){
if (x > 0){
new_text += '\n';
}
if (lines[x].charAt(0) == '\t'){
new_text += lines[x].substring(1);
length--;
} else if (lines[x].startsWith(" ")){
new_text += lines[x].substring(1);
length--;
} else {
new_text += lines[x];
}
}
text_code_impl.replaceTextRange(start, replace_length, new_text);
text_code_impl.setSelectionRange(start, length);
text_code_impl.showSelection();
return false;
}