Add guesses to code hints

This commit is contained in:
dloverin authored and Erik Tierney committed 2013-04-05 13:00:25 -04:00
1 parent c887e8760f
commit dac2002e04
5 files changed
+253 -232

No files matched your search

@@ -35,7 +35,7 @@ define(function (require, exports, module) {
TERN_COMPLETIONS_MSG = "Completions",
TERN_GET_FILE_MSG = "GetFile",
TERN_GET_PROPERTIES_MSG = "Properties",
TERN_CALLED_FUNC_TYPE_MSG = "FunctionType";
TERN_CALLED_FUNC_TYPE_MSG = "FunctionType";
/**
* Create a hint token with name value that occurs at the given list of
@@ -204,5 +204,5 @@ define(function (require, exports, module) {
exports.TERN_INIT_MSG = TERN_INIT_MSG;
exports.TERN_GET_FILE_MSG = TERN_GET_FILE_MSG;
exports.TERN_GET_PROPERTIES_MSG = TERN_GET_PROPERTIES_MSG;
exports.TERN_CALLED_FUNC_TYPE_MSG = TERN_CALLED_FUNC_TYPE_MSG;
exports.TERN_CALLED_FUNC_TYPE_MSG = TERN_CALLED_FUNC_TYPE_MSG;
});
@@ -79,10 +79,10 @@ define(function (require, exports, module) {
var dirEntry = new NativeFileSystem.DirectoryEntry(path),
reader = dirEntry.createReader();
files.forEach(function(i) {
DocumentManager.getDocumentForPath(path + i).done(function(document){
files.forEach(function (i) {
DocumentManager.getDocumentForPath(path + i).done(function (document) {
ternEnvironment.push(JSON.parse(document.getText()));
}).fail(function(error){
}).fail(function (error) {
console.log("failed to read tern config file " + i);
});
});
@@ -162,10 +162,19 @@ define(function (require, exports, module) {
var $deferredHints = $.Deferred(),
hintPromise,
fnTypePromise;
fnTypePromise,
propsPromise;
hintPromise = getTernHints(dir, file, offset, document.getText());
var sessionType = session.getType();
if (sessionType.property) {
propsPromise = getTernProperties(dir, file, document.getText());
} else {
var $propsDeferred = $.Deferred();
propsPromise = $propsDeferred.promise();
$propsDeferred.resolveWith(null);
}
if( sessionType.showFunctionType ) {
// Show function sig
fnTypePromise = getTernFunctionType(dir, file, sessionType.functionCallPos, document.getText());
@@ -173,11 +182,12 @@ define(function (require, exports, module) {
var $fnTypeDeferred = $.Deferred();
fnTypePromise = $fnTypeDeferred.promise();
$fnTypeDeferred.resolveWith(null);
}
$.when(hintPromise, fnTypePromise).done(
function(completions, fnType){
}
$.when(hintPromise, fnTypePromise, propsPromise).done(
function(completions, fnType, properties){
session.setTernHints(completions);
session.setFnType(fnType);
session.setFnType(fnType);
session.setTernProperties(properties);
$deferredHints.resolveWith(null);
});
@@ -215,15 +225,15 @@ define(function (require, exports, module) {
var path = document.file.fullPath,
split = HintUtils.splitPath(path),
dir = split.dir,
file = split.file;
var $deferredHints = $.Deferred(),
propertiesPromise,
fnTypePromise;
propertiesPromise;
propertiesPromise = getTernProperties(dir, file, document.getText());
$.when(hintPromise).done(
function(properties){
$.when(propertiesPromise).done(
function (properties) {
session.setTernProperties(properties);
$deferredHints.resolveWith(null);
});
@@ -241,11 +251,12 @@ define(function (require, exports, module) {
ternWorker.postMessage({
type: HintUtils.TERN_GET_PROPERTIES_MSG,
dir:dir,
file:file
file:file,
text:text
});
var $deferredHints = $.Deferred();
addPendingRequest(file, HintUtils.TERN_PROPERTIES_MSG, $deferredHints);
addPendingRequest(file, HintUtils.TERN_GET_PROPERTIES_MSG, $deferredHints);
return $deferredHints.promise();
}
@@ -310,6 +321,7 @@ define(function (require, exports, module) {
file = response.file,
offset = response.offset,
completions = response.completions,
properties = response.properties,
fnType = response.fnType,
type = response.type,
$deferredHints = getPendingRequest(file, type);
@@ -317,8 +329,10 @@ define(function (require, exports, module) {
if( $deferredHints ) {
if( completions ) {
$deferredHints.resolveWith(null, [completions]);
} else if ( properties ) {
$deferredHints.resolveWith(null, [properties])
} else if ( fnType ) {
$deferredHints.resolveWith(null, [fnType]);
$deferredHints.resolveWith(null, [fnType]);
}
}
}
@@ -429,9 +443,12 @@ define(function (require, exports, module) {
ternWorker.addEventListener("message", function (e) {
var response = e.data,
type = response.type;
console.log("ternWorker event listener: message =" + type);
if( type === HintUtils.TERN_COMPLETIONS_MSG ||
type === HintUtils.TERN_CALLED_FUNC_TYPE_MSG) {
type === HintUtils.TERN_CALLED_FUNC_TYPE_MSG ||
type === HintUtils.TERN_GET_PROPERTIES_MSG) {
// handle any completions the worker calculated
handleTernCompletions(response);
} else if ( type === HintUtils.TERN_GET_FILE_MSG ) {
@@ -41,8 +41,8 @@ define(function (require, exports, module) {
this.editor = editor;
this.path = editor.document.file.fullPath;
this.ternHints = [];
this.ternProperies = [];
this.fnType = null;
this.ternProperties = [];
this.fnType = null;
}
/**
@@ -71,7 +71,7 @@ define(function (require, exports, module) {
* @return {string} - the text of the line
*/
Session.prototype.getLine = function (line) {
var doc = this.editor.document;
var doc = this.editor.document;
return doc.getLine(line);
};
@@ -230,26 +230,29 @@ define(function (require, exports, module) {
* function being called
*/
Session.prototype.getType = function () {
var propertyLookup = false,
inFunctionCall = false,
showFunctionType= false,
context = null,
cursor = this.getCursor(),
functionCallPos,
token = this.getToken(cursor);
var propertyLookup = false,
inFunctionCall = false,
showFunctionType = false,
context = null,
cursor = this.getCursor(),
functionCallPos,
token = this.getToken(cursor);
if (token) {
if( token.state.lexical.info === "call" ) {
if (token.state.lexical.info === "call") {
inFunctionCall = true;
if( this.getQuery().length > 0 ) {
if (this.getQuery().length > 0) {
inFunctionCall = false;
showFunctionType = false;
} else {
showFunctionType = true;
var col = token.state.lexical.column;
for (var line = this.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
showFunctionType = false;
} else {
showFunctionType = true;
var col = token.state.lexical.column,
line,
e,
found;
for (line = this.getCursor().line, e = Math.max(0, line - 9), found = false; line >= e; --line) {
if (this.getLine(line).charAt(col) === "(") {
found = true;
found = true;
break;
}
}
@@ -287,12 +290,110 @@ define(function (require, exports, module) {
/**
* Get a list of hints for the current session using the current scope
* information.
*
*
* @param {string} query - the query prefix (optional)
* @return {Array.<Object>} - the sorted list of hints for the current
* session.
*/
Session.prototype.getHints = function () {
Session.prototype.getHints = function (query) {
if (query === undefined) {
query = "";
}
var MAX_DISPLAYED_HINTS = 500,
QUERY_PREFIX_LENGTH = 1; // Any query of this size or less is matched as a prefix of a hint.
/*
* Filter a list of tokens using the query string in the closure.
*
* @param {Array.<Object>} tokens - list of hints to filter
* @param {number} limit - maximum numberof tokens to return
* @return {Array.<Object>} - filtered list of hints
*/
function filterWithQuery(tokens, limit) {
/*
* Filter arr using test, returning at most limit results from the
* front of the array.
*
* @param {Array} arr - array to filter
* @param {Function} test - test to determine if an element should
* be included in the results
* @param {number} limit - the maximum number of elements to return
* @return {Array.<Object>} - new array of filtered elements
*/
function filterArrayPrefix(arr, test, limit) {
var i = 0,
results = [],
elem;
for (i; i < arr.length && results.length <= limit; i++) {
elem = arr[i];
if (test(elem)) {
results.push(elem);
}
}
return results;
}
if (query.length > 0) {
return filterArrayPrefix(tokens, function (token) {
if (token.literal && token.kind === "string") {
return false;
} else {
if (query.length > QUERY_PREFIX_LENGTH) {
return (token.value.toLowerCase().indexOf(query.toLowerCase()) !== -1);
} else {
return (token.value.toLowerCase().indexOf(query.toLowerCase()) === 0);
}
}
}, limit);
} else {
return tokens.slice(0, limit);
}
}
/**
* Sort the better matching items to the top.
* Prefix matches are considered the best and all others are equal.
* @param a
* @param b
*/
function compareByBestMatch(a, b) {
var index1 = a.value.toLowerCase().indexOf(query.toLowerCase()),
index2 = b.value.toLowerCase().indexOf(query.toLowerCase());
if (index1 === 0 && index2 !== 0) {
return -1;
} else if (index1 !== 0 && index2 === 0) {
return 1;
}
return 0;
}
/*
* Comparator for sorting tokens by name
*
* @param {Object} a - a token
* @param {Object} b - another token
* @return {number} - comparator value that indicates whether the name
* of token a is lexicographically lower than the name of token b
*/
function compareByName(a, b) {
var aLowerCase = a.value.toLowerCase();
var bLowerCase = b.value.toLowerCase();
if (aLowerCase === bLowerCase) {
return 0;
} else if (aLowerCase < bLowerCase) {
return -1;
} else {
return 1;
}
}
/**
* sort by scope depth.
*
@@ -317,27 +418,6 @@ define(function (require, exports, module) {
}
}
/*
* Comparator for sorting tokens by name
*
* @param {Object} a - a token
* @param {Object} b - another token
* @return {number} - comparator value that indicates whether the name
* of token a is lexicographically lower than the name of token b
*/
function compareByName(a, b) {
var aLowerCase = a.value.toLowerCase();
var bLowerCase = b.value.toLowerCase();
if (aLowerCase === bLowerCase) {
return 0;
} else if (aLowerCase < bLowerCase) {
return -1;
} else {
return 1;
}
}
/*
* Forms the lexicographical composition of comparators, i.e.,
* "a lex(c1,c2) b" iff "a c1 b or (a = b and a c2 b)"
@@ -358,6 +438,18 @@ define(function (require, exports, module) {
};
}
/*
* A comparator for identifiers: the lexicographic combination of
* scope and name.
*
* @return {Function} - the comparator function
*/
function compareProperties() {
return (query.length > QUERY_PREFIX_LENGTH) ?
lexicographic(compareByBestMatch, compareByName) :
compareByName;
}
/*
* A comparator for identifiers: the lexicographic combination of
* scope and name.
@@ -365,7 +457,39 @@ define(function (require, exports, module) {
* @return {Function} - the comparator function
*/
function compareIdentifiers() {
return lexicographic(compareByScopeDepth, compareByName);
return (query.length > QUERY_PREFIX_LENGTH) ?
lexicographic(compareByBestMatch,
lexicographic(compareByScopeDepth, compareByName)) :
lexicographic(compareByScopeDepth, compareByName);
}
/*
* Determine if guesses should be added to the hints.
*
* @param {Array} hints - current filtered hints
* @return true if guesses should be added, false otherwise.
*/
function shouldAddGuesses(hints) {
return (hints.length === 0);
}
/*
* Remove the special "<i>" property from the hints.
*
* @param {Array} hints - sorted hints
*/
function removeArrayIndexProperty(hints) {
var n = hints.length,
i;
for (i = 0; i < n; i++) {
var value = hints[i].value;
if (value === "<i>") {
hints.splice(i, 1);
return;
} else if (value > "<i>") {
return;
}
}
}
var cursor = this.editor.getCursorPos(),
@@ -376,32 +500,44 @@ define(function (require, exports, module) {
var ternHints = this.ternHints;
if (type.property) {
if( ternHints && ternHints.length > 0 ) {
if (ternHints && ternHints.length > 0) {
hints = ternHints;
hints.sort(compareByName);
}
else {
hints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
} else {
hints = [];
}
hints.sort(compareProperties());
// Add guesses if appropriate. If guesses and hints are
// mixed guesses are kept below the hints.
if (shouldAddGuesses(hints)) {
var guesses = filterWithQuery(this.ternProperties, MAX_DISPLAYED_HINTS - hints.length);
guesses.sort(compareProperties());
removeArrayIndexProperty(guesses);
hints = hints.concat(guesses);
}
} else if ( type.showFunctionType ) {
hints = this.fnType ? [{value:this.fnType, positions:[]}] : [];
} else {
hints = ternHints ? ternHints : [];
hints = ternHints || [];
hints.sort(compareIdentifiers());
hints = hints.concat(HintUtils.LITERALS);
hints = hints.concat(HintUtils.KEYWORDS);
hints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
}
return hints;
};
Session.prototype.setTernHints = function(newHints) {
Session.prototype.setTernHints = function (newHints) {
this.ternHints = newHints;
};
Session.prototype.setTernProperties = function(newProperties) {
this.ternProperies = newProperties;
}
Session.prototype.setFnType = function(newFnType) {
Session.prototype.setTernProperties = function (newProperties) {
this.ternProperties = newProperties;
};
Session.prototype.setFnType = function (newFnType) {
this.fnType = newFnType;
};
module.exports = Session;
@@ -41,9 +41,6 @@ define(function (require, exports, module) {
cachedType = null, // describes the lookup type and the object context
cachedLine = null; // the line number for the cached scope
var MAX_DISPLAYED_HINTS = 100,
QUERY_PREFIX_LENGTH = 1; // Any query of this size or less is matched as a prefix of a hint.
/**
* Creates a hint response object. Filters the hint list using the query
* string, formats the hints for display, and returns a hint response
@@ -57,99 +54,8 @@ define(function (require, exports, module) {
function getHintResponse(hints, query, type) {
var trimmedQuery,
filteredHints,
formattedHints;
/*
* Filter a list of tokens using the query string in the closure.
*
* @param {Array.<Object>} tokens - list of hints to filter
* @param {number} limit - maximum numberof tokens to return
* @return {Array.<Object>} - filtered list of hints
*/
function filterWithQuery(tokens, limit) {
/*
* Filter arr using test, returning at most limit results from the
* front of the array.
*
* @param {Array} arr - array to filter
* @param {Function} test - test to determine if an element should
* be included in the results
* @param {number} limit - the maximum number of elements to return
* @return {Array.<Object>} - new array of filtered elements
*/
function filterArrayPrefix(arr, test, limit) {
var i = 0,
results = [],
elem;
for (i; i < arr.length && results.length <= limit; i++) {
elem = arr[i];
if (test(elem)) {
results.push(elem);
}
}
return results;
}
// If the query is a string literal (i.e., if it starts with a
// string literal delimiter, and hence if trimmedQuery !== query)
// then only string literal hints should be returned, and matching
// should be performed w.r.t. trimmedQuery. If the query is
// otherwise non-empty, no string literals should match. If the
// query is empty then no hints are filtered.
if (trimmedQuery !== query) {
return filterArrayPrefix(tokens, function (token) {
if (token.literal && token.kind === "string") {
if (query.length > (QUERY_PREFIX_LENGTH + 1)) {
return (token.value.toLowerCase().indexOf(trimmedQuery.toLowerCase()) !== -1);
} else {
return (token.value.toLowerCase().indexOf(trimmedQuery.toLowerCase()) === 0);
}
} else {
return false;
}
}, limit);
} else if (query.length > 0) {
return filterArrayPrefix(tokens, function (token) {
if (token.literal && token.kind === "string") {
return false;
} else {
if (query.length > QUERY_PREFIX_LENGTH) {
return (token.value.toLowerCase().indexOf(query.toLowerCase()) !== -1);
} else {
return (token.value.toLowerCase().indexOf(query.toLowerCase()) === 0);
}
}
}, limit);
} else {
return tokens.slice(0, limit);
}
}
/*
* Comparator for sorting tokens by name
*
* @param {Object} a - a token
* @param {Object} b - another token
* @return {number} - comparator value that indicates whether the name
* of token a is lexicographically lower than the name of token b
*/
function compareByName(a, b) {
var aLowerCase = a.value.toLowerCase();
var bLowerCase = b.value.toLowerCase();
if (aLowerCase === bLowerCase) {
return 0;
} else if (aLowerCase < bLowerCase) {
return -1;
} else {
return 1;
}
}
/*
* Returns a formatted list of hints with the query substring
* highlighted.
@@ -161,28 +67,10 @@ define(function (require, exports, module) {
* objects
*/
function formatHints(hints, query) {
if (query.length > QUERY_PREFIX_LENGTH) {
// raise the hints that match on prefix to the top of the list.
hints.sort(function (hint1, hint2) {
var index1 = hint1.value.toLowerCase().indexOf(query.toLowerCase()),
index2 = hint2.value.toLowerCase().indexOf(query.toLowerCase());
if (index1 === 0 && index2 !== 0) {
return -1;
} else if (index1 !== 0 && index2 === 0) {
return 1;
}
return compareByName(hint1, hint2);
});
}
return hints.map(function (token) {
var hint = token.value,
index = hint.toLowerCase().indexOf(query.toLowerCase()),
$hintObj = $("<span>").addClass("brackets-js-hints"),
delimiter = "";
$hintObj = $("<span>").addClass("brackets-js-hints");
// level indicates either variable scope or property confidence
if (!type.property && token.depth !== undefined) {
@@ -211,32 +99,24 @@ define(function (require, exports, module) {
$hintObj.addClass("global-hint");
}
// is the token a literal?
if (token.literal) {
$hintObj.addClass("literal-hint");
if (token.kind === "string") {
delimiter = HintUtils.DOUBLE_QUOTE;
}
}
// is the token a keyword?
if (token.keyword) {
$hintObj.addClass("keyword-hint");
}
// higlight the matched portion of each hint
if (index >= 0) {
var prefix = StringUtils.htmlEscape(hint.slice(0, index)),
match = StringUtils.htmlEscape(hint.slice(index, index + query.length)),
suffix = StringUtils.htmlEscape(hint.slice(index + query.length));
if (query.length > 0 && index >= 0) {
var prefix = hint.slice(0, index),
match = hint.slice(index, index + query.length),
suffix = hint.slice(index + query.length);
$hintObj.append(delimiter + prefix)
$hintObj.append(prefix)
.append($("<span>")
.append(match)
.addClass("matched-hint"))
.append(suffix + delimiter);
.append(suffix);
} else {
$hintObj.text(delimiter + hint + delimiter);
$hintObj.text(hint);
}
$hintObj.data("token", token);
@@ -257,10 +137,8 @@ define(function (require, exports, module) {
}
if (hints) {
filteredHints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
formattedHints = formatHints(filteredHints, trimmedQuery);
}
else {
formattedHints = formatHints(hints, trimmedQuery);
} else {
formattedHints = [];
}
@@ -329,14 +207,13 @@ define(function (require, exports, module) {
if (token) {
var type = session.getType(),
query = session.getQuery();
// Compute fresh hints if none exist, or if the session
// type has changed since the last hint computation
if (!cachedHints ||
type.property !== cachedType.property ||
type.context !== cachedType.context ||
type.showFunctionType !== cachedType.showFunctionType ||
query.length == 0) {
type.property !== cachedType.property ||
type.context !== cachedType.context ||
type.showFunctionType !== cachedType.showFunctionType || query.length === 0) {
var offset = session.getOffset(),
scopeResponse = ScopeManager.requestHints(session, session.editor.document, offset),
self = this;
@@ -346,13 +223,13 @@ define(function (require, exports, module) {
scopeResponse.promise.done(function () {
cachedLine = cursor.line;
cachedType = session.getType();
cachedHints = session.getHints();
cachedHints = session.getHints(query);
$(self).triggerHandler("resolvedResponse", [cachedHints, cachedType]);
if ($deferredHints.state() === "pending") {
var query = session.getQuery(),
hintResponse = getHintResponse(cachedHints, query, type);
query = session.getQuery();
var hintResponse = getHintResponse(cachedHints, query, type);
$deferredHints.resolveWith(null, [hintResponse]);
$(self).triggerHandler("hintResponse", [query]);
@@ -371,17 +248,7 @@ define(function (require, exports, module) {
}
if (cachedHints) {
type = session.getType(),
query = session.getQuery();
// Compute fresh hints if none exist, or if the session
// type has changed since the last hint computation
if (type.property !== cachedType.property ||
type.context !== cachedType.context ||
type.showFunctionType !== cachedType.showFunctionType) {
cachedType = type;
cachedHints = session.getHints();
}
cachedHints = session.getHints(session.getQuery());
return getHintResponse(cachedHints, query, type);
}
}
@@ -434,11 +301,11 @@ define(function (require, exports, module) {
completion = delimeter + completion + delimeter;
}
if( session.getType().showFunctionType ) {
if (session.getType().showFunctionType) {
// function types show up as hints, so don't insert anything
// if we were displaying a function type
return false;
}
}
// Replace the current token with the completion
session.editor.document.replaceRange(completion, start, end);
@@ -151,15 +151,15 @@ importScripts("thirdparty/requirejs/require.js");
for (var i = 0; i < data.completions.length; ++i) {
var property = data.completions[i];//, className = typeToIcon(completion.type);
//if (data.guess) className += " Tern-completion-guess";
properties.push({value: completion.name, type: completion.type, guess: true /*, className: className*/});
properties.push({value: property, guess: true});
}
// Post a message back to the main thread with the completions
// Post a message back to the main thread with the completions
self.postMessage({type: HintUtils.TERN_GET_PROPERTIES_MSG,
dir: dir,
file: file,
completions: properties
});
dir: dir,
file: file,
properties: properties
});
});
}
@@ -220,7 +220,8 @@ importScripts("thirdparty/requirejs/require.js");
} else if ( type === HintUtils.TERN_GET_PROPERTIES_MSG) {
var file = request.file,
dir = request.dir;
handleGetProperties(file, dir);
text = request.text;
handleGetProperties(dir, file, text);
} else if ( type === HintUtils.TERN_GET_FILE_MSG ) {
file = request.file,
text = request.text;