This repository has been archived by the owner on Sep 28, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathhints.js
336 lines (283 loc) · 12.6 KB
/
hints.js
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
// This defines a hintProvider for robotframework files
//
/*jslint vars: true, plusplus: true, devel: true, nomen: true, indent: 4, maxerr: 50, regexp: true */
/*global define, brackets, $ */
define(function (require, exports, module) {
'use strict';
var PreferencesManager = brackets.getModule("preferences/PreferencesManager");
var StatusBar = brackets.getModule("widgets/StatusBar");
var prefs = PreferencesManager.getExtensionPrefs("robotframework");
var robot = require("./robot");
function HintProvider() {
// these will be set in hasHints, and used in
// getHints and insertHint:
this.hints = [];
this.match = "";
this.cell = null;
this.editor = null;
var $msg = $("<div><~></div>");
StatusBar.addIndicator("rfhub-error", $msg, false, "",
"Robot framework hub is unreachable. Robot autocomplete is unavailable. See https://github.com/boakley/robotframework-hub");
}
HintProvider.prototype.insertHintOnTab = true;
HintProvider.prototype.hasHints = function (editor, implicitChar) {
this.editor = editor;
this.looking_for = null;
var cm = editor._codeMirror;
var pos = editor.getCursorPos();
var tmp;
var cell;
var state = cm.getStateAfter(pos.line);
// FIXME? do I need to compute cell_number when I already
// have state.column?
var cell_number = robot.getCurrentCellNumber(cm, pos);
if (implicitChar === "*") {
// is it a table heading?
tmp = cm.getRange({line: pos.line, ch: 0}, pos);
if (tmp.match(/^\*+/)) {
return true;
}
} else if (implicitChar === "v") {
// If user types "vv" (but not in the middle of a word),
// replace with ${} and treat it as such. This is probably
// the wrong place for such shenanigans, but whatever.
tmp = cm.getRange({line: pos.line, ch: pos.ch - 3},
{line: pos.line, ch: pos.ch - 1});
if (tmp.match(/\bv$/)) {
cm.replaceRange('${}', {line: pos.line, ch: pos.ch - 2}, pos);
cm.setCursor({line: pos.line, ch: pos.ch});
this.looking_for = "variable";
return true;
}
} else if (implicitChar === "{") {
tmp = cm.getRange({line: pos.line, ch: pos.ch - 2}, pos);
if (tmp === "${") {
return true;
}
} else if (implicitChar === "[") {
// only provide metadata hints if the cursor is in the first cell
// of a testcase or keyword
if ((state.isTestCasesTable() || state.isKeywordsTable()) && cell_number === 1) {
return true;
}
} else if (state.isSettingsTable() && cell_number === 0 && pos.ch !== 0) {
// first column of a settings table, we always have hints.
// Note that if the user prefers space-separated format we want
// to NOT do that check on pos.ch; When I get around to finishing
// support for space-separated format I can check for a setting
// or something....
return true;
}
if (implicitChar === null) {
return true;
}
return false;
};
HintProvider.prototype.getHints = function (implicitChar) {
var cm = this.editor._codeMirror;
var pos = this.editor.getCursorPos();
var state = cm.getStateAfter(pos.line);
var cell = robot.getCurrentCell(cm, pos);
var cell_number = robot.getCurrentCellNumber(cm, pos);
var match = "";
var hints;
// replace leading and trailing whitespace
cell.text = cell.text.replace(/^ +| +$/g,'');
// save it; we're gonna need it later.
this.cell = cell;
if (cell.text.match(/^\s*\[/)) {
// metadata
match = cell.text.replace(/^\s*\[|\]\s*$/g, "");
hints = getMetadataHints(match, state);
return {hints: hints, match: match, selectInitial: true};
} else if (cell.text.match(/\s*\$\{/)) {
// variables
// FIXME: either remove the current cell from the list,
// or make it the first item in the list
var matches = getValidVariables(this.editor, pos);
if (matches !== null) {
matches = matches.filter(function (item, index, inputArray) {
// filter the list by only using matches that contain
// the current cell text (minus the ${ and })
var itemname = item.replace(/^\$\{|\}$/g, "");
var match = cell.text.replace(/^\$\{|\}$/g, "");
var result = (itemname.toLowerCase().indexOf(match.toLowerCase()) === 0);
return result;
});
hints = makeOrderedSet(matches);
return {hints: hints, match: match, selectInitial: true};
} else {
return {hints: [], match: "", selectInitial: true};
}
} else if (cell.text.match(/\*+/) && cell.start.ch === 0) {
// table headings
match = cell.text.replace(/^\*+\s*|\*\s*/, '');
hints = getHeadingHints(match);
return {hints: hints, match: match, selectInitial: true};
} else if (state.isSettingsTable() && cell_number === 0) {
// settings
hints = getSettingsHints(cell.text);
return {hints: hints, match: cell.text, selectInitial: true};
} else {
// ok, done with all the special cases. What's left might be a keyword
// FIXME: move fetching keyword data to a function,
// and give the function the ability to add a status
// indicator to the statusbar if the hub is down
var hub_url = prefs.get("hub-url");
var keyword_url = hub_url + "/api/keywords?pattern=^" + cell.text + "*";
var keywords = getLocalKeywords(this.editor, cell.text);
$.ajaxSetup({ "async": false});
// We should be able to catch errors via .fail, but
// we need to work around a bug in jquery.
// See http://bugs.jquery.com/ticket/14683
try {
var response = $.getJSON(keyword_url, function (data) {
var i;
StatusBar.updateIndicator("rfhub-error", false);
for (i = 0; i < data.keywords.length; i++) {
keywords.push(data.keywords[i].name + "<i> (" + data.keywords[i].library + ")</i>");
// keywords.push({library: data.keywords[i].library,
// keyword: data.keywords[i].name})
}
}).fail(function (jqxhr, textStatus, error) {
StatusBar.updateIndicator("rfhub-error", true);
});
} catch (err) {
StatusBar.updateIndicator("rfhub-error", true);
}
$.ajaxSetup({ "async": true});
return {hints: keywords.sort(), match: cell.text, selectInitial: true};
}
};
HintProvider.prototype.insertHint = function (hint) {
// The hint may contain the library name surrounded
// by <i></i>, which needs to be stripped off
hint = hint.replace(/<i>.*<\/i>/, "");
var cm = this.editor._codeMirror;
var state = cm.getStateAfter(this.cell.start.line);
var currentLine = cm.getLine(this.cell.start.line);
// this next piece of magic should probably be configurable
// by the user - let's auto-add a separator. I think it's
// the Right Thing to do more often than not.
if (hint.match(/^\*/)) {
// a heading
hint += "\n";
} else if (this.cell.end.ch === currentLine.length) {
// ie: nothing follows this cell
if (state.separator == "pipes") {
hint += " | ";
}
}
this.editor.document.replaceRange(hint, this.cell.start, this.cell.end);
return false;
};
// this function is supposed to return a list of variables
// visible at the current position. What it actually does
// is return all variables mentioned in the file. Not
// ideal, but it's a good starting place.
function getValidVariables(editor, pos) {
var matches = editor.document.getText().match(/\$\{.*?\}/g);
return matches;
}
function getSettingsHints(prefix) {
// I hate hard-coding these. I wish robot had an API I could use
// to fetch them.
var allowable = [
"...",
"Library", "Resource", "Variables",
"Documentation", "Metadata",
"Suite Setup", "Suite Teardown",
"Suite Precondition", "Suite Postcondition",
"Force Tags", "Default Tags",
"Test Setup", "Test Teardown",
"Test Precondition", "Test Postcondition",
"Test Template", "Test Timeout"].sort();
var i;
var hints = [];
if (prefix.match(/^\s*$/)) {
return allowable;
}
prefix = prefix.toLowerCase().replace(/^\s+/, "");
for (i = 0; i < allowable.length; i++) {
if (allowable[i].toLowerCase().indexOf(prefix) === 0) {
hints.push(allowable[i]);
}
}
return hints;
}
function getMetadataHints(prefix, state) {
var meta = [];
var hints = [];
var i;
if (state.isTestCasesTable()) {
// "..." is also valid in this context even though it's not
// metadata per se.
meta = ["...", "[Documentation]", "[Tags]", "[Setup]", "[Teardown]",
"[Template]", "[Timeout]"];
} else if (state.isKeywordsTable()) {
meta = ["...", "[Documentation]", "[Arguments]", "[Return]",
"[Teardown]", "[Timeout]"];
}
prefix = "[" + prefix.toLowerCase();
for (i = 0; i < meta.length; i++) {
if (meta[i].toLowerCase().indexOf(prefix) === 0) {
hints.push(meta[i]);
}
}
return hints.sort();
}
function escapeRegexChars(str) {
// escape characters special to regex; eg * becomes \*
return (str+'').replace(/[.?*+^$[\]\\(){}|-]/g, "\\$&");
}
function getHeadingHints(prefix) {
// Return all possible table headings matching the prefix
var pattern = new RegExp("^" + escapeRegexChars(prefix), 'i');
var tables = ["Keywords", "Settings", "Test Cases", "Variables"];
var hints = [];
var i;
for (i = 0; i < 4; i++) {
if (tables[i].match(pattern)) {
hints.push("*** " + tables[i] + " ***");
}
}
return hints;
}
// Return a list of local keywords that start with the given pattern
// Performance note: a quick test showed this to take <10 milliseconds
// to scan a file of 6000 lines containing 500 keywords. Not too shabby!
function getLocalKeywords(editor, _pattern) {
// this assumes all of the text has been parsed by codemirror. That
// may not always be true. I need to figure out how to get codemirror
// to tokenize the whole file...
var cm = editor._codeMirror,
line,
state,
keywords = [],
pattern = _pattern.toLowerCase();
cm.eachLine(function (line) {
state = line.stateAfter;
if (state && state.isKeywordsTable() && state.tc_or_kw_name) {
if (state.tc_or_kw_name.toLowerCase().indexOf(pattern) === 0) {
if (keywords.indexOf(state.tc_or_kw_name) === -1) {
keywords.push(state.tc_or_kw_name);
}
}
}
});
return keywords;
}
function makeOrderedSet(array) {
// remove duplicates, and do case-insensitive sort
array = array.filter(function (item, index, inputArray) {
return inputArray.indexOf(item) === index;
});
array = array.sort(function (a, b) {
if (a.toLowerCase() < b.toLowerCase()) { return -1; }
if (a.toLowerCase() > b.toLowerCase()) { return 1; }
return 0;
});
return array;
}
exports.HintProvider = HintProvider;
});