Skip to content

Commit

Permalink
changed the error message so that the ^ is always pointing to the right
Browse files Browse the repository at this point in the history
character
  • Loading branch information
jannisCode committed Oct 22, 2024
1 parent 3ffdfe3 commit 439ae05
Showing 1 changed file with 26 additions and 8 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,13 @@

package org.eclipse.ui.internal;


import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;

import org.eclipse.jface.fieldassist.ControlDecoration;
import org.eclipse.jface.fieldassist.FieldDecorationRegistry;
import org.eclipse.swt.graphics.GC;
import org.eclipse.swt.graphics.Image;

/**
Expand All @@ -41,7 +43,9 @@ private SearchDecoration() {
* the validation.
*/
public static boolean validateRegex(String regex, ControlDecoration targetDecoration) {
String errorMessage = getValidationError(regex);
GC gc = new GC(targetDecoration.getControl());

String errorMessage = getValidationError(regex, gc);
if (errorMessage.isEmpty()) {
targetDecoration.hide();
return true;
Expand All @@ -53,6 +57,7 @@ public static boolean validateRegex(String regex, ControlDecoration targetDecora
targetDecoration.setImage(decorationImage);
targetDecoration.setDescriptionText(errorMessage);
targetDecoration.show();
gc.dispose();
return false;
}

Expand All @@ -62,20 +67,33 @@ public static boolean validateRegex(String regex, ControlDecoration targetDecora
* @return The appropriate error message if the regex is invalid or an empty
* string if the regex is valid.
*/
private static String getValidationError(String regex) {
private static String getValidationError(String regex, GC gc) {
try {
Pattern.compile(regex);
return ""; //$NON-NLS-1$
} catch (PatternSyntaxException e) {
String message = e.getLocalizedMessage();
String description = e.getDescription();
int errorIndex = e.getIndex();
String pattern = e.getPattern();

StringBuilder sBuilder = new StringBuilder();

sBuilder.append(description + " at index " + errorIndex); //$NON-NLS-1$
sBuilder.append(System.lineSeparator());
sBuilder.append(pattern);
sBuilder.append(System.lineSeparator());

String stringToIndexString = pattern.substring(0, errorIndex);
String buildString = ""; //$NON-NLS-1$
String thinSpace = "\u2009"; //$NON-NLS-1$

// Only preserve the first line of the original error message.
int i = 0;
while (i < message.length() && "\n\r".indexOf(message.charAt(i)) == -1) { //$NON-NLS-1$
i++;
while (gc.stringExtent(buildString).x < gc.stringExtent(stringToIndexString).x - 1) {
buildString += thinSpace; // $NON-NLS-1$
}
sBuilder.append(buildString);

return message.substring(0, i);
sBuilder.append("^"); //$NON-NLS-1$
return sBuilder.toString();
}
}

Expand Down

0 comments on commit 439ae05

Please sign in to comment.