Search code examples
javaeclipseeditorxtext

Xtext - AutoEdits with backspace


Assume following situation: We have a document, which contains spaces
( for example denoted as _ ) And we have caret behind those (4)spaces

_ _ _ _|

I want editor to delete all 4 spaces instead of one when user presses backspace.

I am extending DefaultIndentLineAutoEditStrategy where I override following method

public void customizeDocumentCommand(IDocument d, DocumentCommand c)

I am facing two problems:

  1. How to detect backspace have been used from DocumentCommand? If you use newline c.text contains "\n" or "\r\n" but if you use backspace it equals to "".
  2. How do I insert 3 more backspaces? Appending "\b" to c.text does not work.

Solution

  • Ok I managed to implement it.

    1. if (c.text.equals("") && c.length == 1) condition detects usage of backspace/delete
    2. Deleting 3 more characters can be done as following:
      c.offset-=3; c.length=4;

    whole implementation can look like this:

    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();
            }
        }