-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSyntaxHighlightEditText.java
85 lines (68 loc) · 2.45 KB
/
SyntaxHighlightEditText.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
package com.ibquezada.android.FastCode;
import android.content.Context;
import android.graphics.Color;
import android.text.Editable;
import android.text.Spanned;
import android.text.TextWatcher;
import android.text.style.ForegroundColorSpan;
import android.util.AttributeSet;
import android.widget.EditText;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class SyntaxHighlightEditText extends EditText {
private TextWatcher myWatcher = null;
private ForegroundColorSpan red = new ForegroundColorSpan(Color.rgb(255, 0, 0));
final SyntaxHighlightEditText that = this;
private List<String> reservedWords;
private void createWatcherForEditor() {
myWatcher = new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
String actualCode = that.getText().toString();
highlight(s, actualCode);
}
};
}
public SyntaxHighlightEditText(Context context) {
super(context);
init();
}
public SyntaxHighlightEditText(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public SyntaxHighlightEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
this.createWatcherForEditor();
this.addTextChangedListener(this.myWatcher);
this.reservedWords = Arrays.asList("int", "bool", "float", "string", "function", "class", "new", "this", "private", "public", "protected");
}
private void highlight(Editable s, String text) {
String regex = "(";
int counter = 0;
for(String word : reservedWords) {
counter += 1;
regex += "\\b" + word;
if(counter < reservedWords.size()) {
regex += "|";
}
}
regex += "\\s)";
Pattern p = Pattern.compile("\\b" + regex + "\\s");
Matcher m = p.matcher(text);
while(m.find()) {
s.setSpan(new ForegroundColorSpan(Color.rgb(255, 0, 0)), m.start(), m.end(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
}
}
}