-
Notifications
You must be signed in to change notification settings - Fork 61
Expand file tree
/
Copy pathTemplateCompletion.java
More file actions
418 lines (339 loc) · 11.5 KB
/
TemplateCompletion.java
File metadata and controls
418 lines (339 loc) · 11.5 KB
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
/*
* 05/26/2012
*
* TemplateCompletion.java - A completion used to insert boilerplate code
* snippets that have arbitrary sections the user will want to change, such as
* for-loops.
*
* This library is distributed under a modified BSD license. See the included
* RSyntaxTextArea.License.txt file for details.
*/
package org.fife.ui.autocomplete;
import java.util.ArrayList;
import java.util.List;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import javax.swing.text.Position;
import org.fife.ui.autocomplete.TemplatePiece.Param;
import org.fife.ui.autocomplete.TemplatePiece.ParamCopy;
import org.fife.ui.autocomplete.TemplatePiece.Text;
import org.fife.ui.rsyntaxtextarea.RSyntaxUtilities;
/**
* A completion made up of a template with arbitrary parameters that the user
* can tab through and fill in. This completion type is useful for inserting
* common boilerplate code, such as for-loops.<p>
*
* The format of a template is similar to those in Eclipse. The following
* example would be the format for a for-loop template:
*
* <pre>
* for (int ${i} = 0; ${i} < ${array}.length; ${i}++) {
* ${cursor}
* }
* </pre>
*
* In the above example, the first <code>${i}</code> is a parameter for the
* user to type into; all the other <code>${i}</code> instances are
* automatically changed to what the user types in the first one. The parameter
* named <code>${cursor}</code> is the "ending position" of the template. It's
* where the caret moves after it cycles through all other parameters. If the
* user types into it, template mode terminates. If more than one
* <code>${cursor}</code> parameter is specified, behavior is undefined.<p>
*
* Two dollar signs in a row ("<code>$$</code>") will be evaluated as a single
* dollar sign. Otherwise, the template parsing is pretty straightforward and
* fault-tolerant.<p>
*
* Leading whitespace is automatically added to lines if the template spans
* more than one line, and if used with a text component using a
* <code>PlainDocument</code>, tabs will be converted to spaces if requested.
*
* @author Robert Futrell
* @version 1.0
*/
public class TemplateCompletion extends AbstractCompletion
implements ParameterizedCompletion {
private List<TemplatePiece> pieces;
private String inputText;
private String definitionString;
private String shortDescription;
private String summary;
/**
* The template's parameters.
*/
private List<Parameter> params;
public TemplateCompletion(CompletionProvider provider,
String inputText, String definitionString, String template) {
this(provider, inputText, definitionString, template, null, null);
}
public TemplateCompletion(CompletionProvider provider,
String inputText, String definitionString, String template,
String shortDescription, String summary) {
super(provider);
this.inputText = inputText;
this.definitionString = definitionString;
this.shortDescription = shortDescription;
this.summary = summary;
pieces = new ArrayList<TemplatePiece>(3);
params = new ArrayList<Parameter>(3);
parse(template);
}
private void addTemplatePiece(TemplatePiece piece) {
pieces.add(piece);
if (piece instanceof Param && !"cursor".equals(piece.getText())) {
final String type = null; // TODO
Parameter param = new Parameter(type, piece.getText());
params.add(param);
}
}
@Override
public String getInputText() {
return inputText;
}
private String getPieceText(int index, String leadingWS) {
TemplatePiece piece = pieces.get(index);
String text = piece.getText();
if (text.indexOf('\n')>-1) {
text = text.replaceAll("\n", "\n" + leadingWS);
}
return text;
}
/**
* Returns <code>null</code>; template completions insert all of their
* text via <code>getInsertionInfo()</code>.
*
* @return <code>null</code> always.
*/
public String getReplacementText() {
return null;
}
public String getSummary() {
return summary;
}
public String getDefinitionString() {
return definitionString;
}
public String getShortDescription() {
return shortDescription;
}
/**
* {@inheritDoc}
*/
public boolean getShowParameterToolTip() {
return false;
}
public ParameterizedCompletionInsertionInfo getInsertionInfo(
JTextComponent tc, boolean replaceTabsWithSpaces) {
ParameterizedCompletionInsertionInfo info =
new ParameterizedCompletionInsertionInfo();
StringBuilder sb = new StringBuilder();
int dot = tc.getCaretPosition();
// Get the range in which the caret can move before we hide
// this tool tip.
int minPos = dot;
Position maxPos = null;
int defaultEndOffs = -1;
try {
maxPos = tc.getDocument().createPosition(dot);
} catch (BadLocationException ble) {
ble.printStackTrace(); // Never happens
}
info.setCaretRange(minPos, maxPos);
int selStart = dot; // Default value
int selEnd = selStart;
Document doc = tc.getDocument();
String leadingWS = null;
try {
leadingWS = RSyntaxUtilities.getLeadingWhitespace(doc, dot);
} catch (BadLocationException ble) { // Never happens
ble.printStackTrace();
leadingWS = "";
}
// Create the text to insert (keep it one completion for
// performance and simplicity of undo/redo).
int start = dot;
for (int i=0; i<pieces.size(); i++) {
TemplatePiece piece = pieces.get(i);
String text = getPieceText(i, leadingWS);
if (piece instanceof Text) {
if (replaceTabsWithSpaces) {
start = possiblyReplaceTabsWithSpaces(sb, text, tc, start);
}
else {
sb.append(text);
start += text.length();
}
}
else if (piece instanceof Param && "cursor".equals(text)) {
defaultEndOffs = start;
}
else {
int end = start + text.length();
sb.append(text);
if (piece instanceof Param) {
info.addReplacementLocation(start, end);
if (selStart==dot) {
selStart = start;
selEnd = selStart + text.length();
}
}
else if (piece instanceof ParamCopy) {
info.addReplacementCopy(piece.getText(), start, end);
}
start = end;
}
}
// Highlight the first parameter. If no params were specified, move
// the caret to the ${cursor} location, if specified
if (selStart==minPos && selStart==selEnd && getParamCount()==0) {
if (defaultEndOffs>-1) { // ${cursor} specified
selStart = selEnd = defaultEndOffs;
}
}
info.setInitialSelection(selStart, selEnd);
if (defaultEndOffs>-1) {
// Keep this location "after" all others when tabbing
info.addReplacementLocation(defaultEndOffs, defaultEndOffs);
}
info.setDefaultEndOffs(defaultEndOffs);
info.setTextToInsert(sb.toString());
return info;
}
/**
* {@inheritDoc}
*/
public Parameter getParam(int index) {
return params.get(index);
}
/**
* {@inheritDoc}
*/
public int getParamCount() {
return params==null ? 0 : params.size();
}
/**
* Returns whether a parameter is already defined with a specific name.
*
* @param name The name.
* @return Whether a parameter is defined with that name.
*/
private boolean isParamDefined(String name) {
for (int i=0; i<getParamCount(); i++) {
Parameter param = getParam(i);
if (name.equals(param.getName())) {
return true;
}
}
return false;
}
/**
* Parses a template string into logical pieces used by this class.
*
* @param template The template to parse.
*/
private void parse(String template) {
int offs = 0;
int lastOffs = 0;
while ((offs=template.indexOf('$', lastOffs))>-1 && offs<template.length()-1) {
char next = template.charAt(offs+1);
switch (next) {
case '$': // "$$" => escaped single dollar sign
addTemplatePiece(new TemplatePiece.Text(template.substring(lastOffs, offs+1)));
lastOffs = offs + 2;
break;
case '{': // "${...}" => variable
int closingCurly = -2;
// Allow an escaped closing brace character in the 'varname' part of the template
// Here we check that a closing brace is not prefixed by a backslash
// NOTE :: It doesn't deal with \\ as a prefix to a non escaped '}' currently.
int scanStart = offs+2;
while (closingCurly == -2) {
closingCurly = template.indexOf('}', scanStart);
if (closingCurly != -1) {
if (template.charAt(closingCurly-1) == '\\') {
scanStart = closingCurly+1;
closingCurly = -2;
}
}
}
if (closingCurly > -1) {
final String textPriorToTemplateBlock = template.substring(lastOffs, offs);
final TemplatePiece.Text piece = new TemplatePiece.Text(textPriorToTemplateBlock);
addTemplatePiece(piece);
// Replace escaped rbrace (backslash rbrace) with just rbrace (in varname)
String varName = template.substring(offs+2, closingCurly).replace("\\}", "}");
// Use a colon as a signifier that the varname is a non-unified 'varname', so we
// can use the same initial text in autocomplete without unifying the text input
// based on the same initial key. Any varname which starts with colon is essentially
// marked as 'not a variable', and it means that we can substitute freeform text
// without the autocompleter linking user input based on the values matching (which
// is the current behaviour).
boolean isTabStopNotVarname = varName.startsWith(":");
varName = isTabStopNotVarname ? varName.substring(1) : varName;
if ( (!"cursor".equals(varName)) && isParamDefined(varName) && (!isTabStopNotVarname)) {
final TemplatePiece.ParamCopy piece2 = new TemplatePiece.ParamCopy(varName);
addTemplatePiece(piece2);
}
else {
final TemplatePiece.Param piece2 = new TemplatePiece.Param(varName);
addTemplatePiece(piece2);
}
lastOffs = closingCurly + 1;
}
break;
}
}
if (lastOffs<template.length()) {
String text = template.substring(lastOffs);
final TemplatePiece.Text piece = new TemplatePiece.Text(text);
addTemplatePiece(piece);
}
}
private int possiblyReplaceTabsWithSpaces(StringBuilder sb, String text,
JTextComponent tc, int start) {
int tab = text.indexOf('\t');
if (tab>-1) {
int startLen = sb.length();
int size = 4;
Document doc = tc.getDocument();
if (doc != null) {
Integer i = (Integer) doc.getProperty(PlainDocument.tabSizeAttribute);
if (i != null) {
size = i.intValue();
}
}
String tabStr = "";
for (int i=0; i<size; i++) {
tabStr += " ";
}
int lastOffs = 0;
do {
sb.append(text.substring(lastOffs, tab));
sb.append(tabStr);
lastOffs = tab + 1;
} while ((tab=text.indexOf('\t', lastOffs))>-1);
sb.append(text.substring(lastOffs));
start += sb.length() - startLen;
}
else {
sb.append(text);
start += text.length();
}
return start;
}
/**
* Sets the short description of this template completion.
*
* @param shortDesc The new short description.
* @see #getShortDescription()
*/
public void setShortDescription(String shortDesc) {
this.shortDescription = shortDesc;
}
@Override
public String toString() {
return getDefinitionString();
}
}