How to show non-printable characters in SWT a text widget

409 views Asked by At

How is it possible to display non-printable characters in an SWT StyledText widget in a way it's done by Swing with an empty square?

To replace all occurrences with a symbol via regex in the source string can't be the solution because copy & paste with the original codepoint won't be possible anymore.

The best way might be to intercept the text rendering and replace them there, but that seems to open Pandora's box...

Edit 1:

The control characters, it's all about, are characters that are normally just skipped and not shown by the editor like HOP (U+0081)

1

There are 1 answers

1
J Robes On

For an E4 RCP application I have attached some code to start with.

Basically is uses the IEventBroker to add/remove the painter of the TextViewer by means of a button.

The StyledText can be obtained from

styledText = tv.getTextWidget();

as commented above

import org.eclipse.jface.text.WhitespaceCharacterPainter;
public class TheEditor{
    @Inject MPart thePart;
    private WhitespaceCharacterPainter whitespaceCharacterPainter;

    @PostConstruct
    public void postConstruct(Composite parent) {
            TextViewer tv = new TextViewer(parent, SWT.MULTI | SWT.V_SCROLL |SWT.H_SCROLL);
            whitespaceCharacterPainter = new  WhitespaceCharacterPainter(tv);
            tv.addPainter(whitespaceCharacterPainter);
            whitespaceCharacterPainter.deactivate(true);
    }

    @Inject
    @Optional
    public void updatePartByWSButton(@UIEventTopic(EventConstants.WHITE_CHARACTERS_STATUS) boolean newButtonStatus) {
        final MElementContainer<MUIElement>container = thePart.getParent();
        if (thePart.equals((MPart)container.getSelectedElement())){
            wsToolBarButtonStatus = newButtonStatus;
            if(wsToolBarButtonStatus){
              this.whitespaceCharacterPainter.paint(IPainter.CONFIGURATION);
            }
            else{
                whitespaceCharacterPainter.deactivate(true);
                tv.removePainter(whitespaceCharacterPainter);
            }
        }
    }
}

Handler Class

public class WhitespaceCharactersHandler {
    boolean status;
    @Execute
    public void execute(final MToolItem item, IEventBroker broker) {
        if (item.isSelected()){
            status = true;
        }
        else{
            status = false;
        }
        broker.post(EventConstants.WHITE_CHARACTERS_STATUS, status);
    }
}

Contants interface:

public interface EventConstants {
    String WHITE_CHARACTERS_STATUS = "WHITE-CHARACTERS-STATUS";
}