use StringMatch class to sort hints

This commit is contained in:
dloverin committed 2013-04-12 20:54:51 -04:00
1 parent d7adb07f3f
commit aba25e2705
2 files changed
+69 -215

No files matched your search

@@ -27,7 +27,8 @@
define(function (require, exports, module) {
"use strict";
var HintUtils = require("HintUtils");
var StringMatch = brackets.getModule("utils/StringMatch"),
HintUtils = require("HintUtils");
/**
* Session objects encapsulate state associated with a hinting session
@@ -290,187 +291,18 @@ 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)
* @param {string} query - the query prefix
* @param {StringMatcher} matcher - the class to find query matches and sort the results
* @return {Array.<Object>} - the sorted list of hints for the current
* session.
*/
Session.prototype.getHints = function (query) {
Session.prototype.getHints = function (query, matcher) {
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.
*
* @param a
* @param b
* @return {*}
*/
function compareByScopeDepth(a, b) {
var adepth = a.depth;
var bdepth = b.depth;
if (adepth >= 0) {
if (bdepth >= 0) {
return adepth - bdepth;
} else {
return -1;
}
} else if (bdepth >= 0) {
return 1;
} else {
return 0;
}
}
/*
* Forms the lexicographical composition of comparators, i.e.,
* "a lex(c1,c2) b" iff "a c1 b or (a = b and a c2 b)"
*
* @param {Function} compare1 - a comparator
* @param {Function} compare2 - another comparator
* @return {Function} - the lexicographic composition of comparator1
* and comparator2
*/
function lexicographic(compare1, compare2) {
return function (a, b) {
var result = compare1(a, b);
if (result === 0) {
return compare2(a, b);
} else {
return result;
}
};
}
/*
* 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.
*
* @return {Function} - the comparator function
*/
function compareIdentifiers() {
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);
}
var MAX_DISPLAYED_HINTS = 500;
/*
* Remove the special "<i>" property from the hints.
@@ -481,7 +313,7 @@ define(function (require, exports, module) {
var n = hints.length,
i;
for (i = 0; i < n; i++) {
var value = hints[i].value;
var value = hints[i].label;
if (value === "<i>") {
hints.splice(i, 1);
return;
@@ -491,39 +323,59 @@ define(function (require, exports, module) {
}
}
/**
* Filter an array hints using a given query and matcher.
* The hints are returned in the format of the matcher.
* The matcher returns the value in the "label" property,
* the match score in "matchGoodness" property.
*
* @param {Array} hints - array of hints
* @param {StringMatcher} matcher
* @returns {Array} - array of matching hints.
*/
function filterWithQueryAndMatcher(hints, matcher) {
var matchResults = $.map(hints, function (hint) {
var searchResult = matcher.match(hint.value, query);
if (searchResult) {
searchResult.guess = hint.guess;
if (hint.depth !== undefined) {
searchResult.depth = hint.depth;
}
}
return searchResult;
});
return matchResults;
}
var type = this.getType(),
hints;
var ternHints = this.ternHints;
if (type.property) {
if (ternHints && ternHints.length > 0) {
hints = ternHints;
hints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
} else {
hints = [];
}
hints = this.ternHints || [];
hints = filterWithQueryAndMatcher(hints, matcher);
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);
// If there are no hints then switch over to guesses.
if (hints.length === 0) {
hints = filterWithQueryAndMatcher(this.ternProperties, matcher);
}
StringMatch.multiFieldSort(hints, { matchGoodness: 0, label: 1 });
removeArrayIndexProperty(hints);
} else if ( type.showFunctionType ) {
hints = this.getFunctionTypeHint();
} else {
hints = ternHints || [];
hints.sort(compareIdentifiers());
} else { // identifiers, literals, and keywords
hints = this.ternHints || [];
hints = hints.concat(HintUtils.LITERALS);
hints = hints.concat(HintUtils.KEYWORDS);
hints = filterWithQuery(hints, MAX_DISPLAYED_HINTS);
hints = filterWithQueryAndMatcher(hints, matcher);
StringMatch.multiFieldSort(hints, { matchGoodness: 0, depth: 1, label: 2 });
}
if (hints.length > MAX_DISPLAYED_HINTS) {
hints = hints.slice(0, MAX_DISPLAYED_HINTS);
}
return hints;
};
@@ -556,7 +408,7 @@ define(function (require, exports, module) {
fnHint = varName + fnHint.substr(2);
}
}
hints[0] = {value:fnHint, positions:[]};
hints[0] = {label:fnHint, positions:[]};
}
return hints;
};
@@ -37,6 +37,7 @@ define(function (require, exports, module) {
AppInit = brackets.getModule("utils/AppInit"),
ExtensionUtils = brackets.getModule("utils/ExtensionUtils"),
StringUtils = brackets.getModule("utils/StringUtils"),
StringMatch = brackets.getModule("utils/StringMatch"),
HintUtils = require("HintUtils"),
ScopeManager = require("ScopeManager"),
Session = require("Session");
@@ -48,7 +49,8 @@ define(function (require, exports, module) {
var session = null, // object that encapsulates the current session state
cachedHints = null, // sorted hints for the current hinting session
cachedType = null, // describes the lookup type and the object context
cachedLine = null; // the line number for the cached scope
cachedLine = null, // the line number for the cached scope
matcher = null; // string matcher for hints
/**
* Creates a hint response object. Filters the hint list using the query
@@ -77,9 +79,7 @@ define(function (require, exports, module) {
*/
function formatHints(hints, query) {
return hints.map(function (token) {
var hint = token.value,
index = hint.toLowerCase().indexOf(query.toLowerCase()),
$hintObj = $("<span>").addClass("brackets-js-hints");
var $hintObj = $("<span>").addClass("brackets-js-hints");
// level indicates either variable scope or property confidence
if (!type.property && token.depth !== undefined) {
@@ -113,19 +113,19 @@ define(function (require, exports, module) {
$hintObj.addClass("keyword-hint");
}
// higlight the matched portion of each hint
if (query.length > 0 && 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));
$hintObj.append(prefix)
.append($("<span>")
.append(match)
.addClass("matched-hint"))
.append(suffix);
// highlight the matched portion of each hint
if (token.stringRanges) {
token.stringRanges.forEach(function (item) {
if (item.matched) {
$hintObj.append($("<span>")
.append(StringUtils.htmlEscape(item.text))
.addClass("matched-hint"));
} else {
$hintObj.append(StringUtils.htmlEscape(item.text));
}
});
} else {
$hintObj.text(hint);
$hintObj.text(token.label);
}
$hintObj.data("token", token);
@@ -194,6 +194,7 @@ define(function (require, exports, module) {
//console.log("clear hints");
cachedLine = null;
cachedHints = null;
matcher = null;
}
return true;
}
@@ -232,7 +233,8 @@ define(function (require, exports, module) {
scopeResponse.promise.done(function () {
cachedLine = cursor.line;
cachedType = session.getType();
cachedHints = session.getHints(query);
matcher = new StringMatch.StringMatcher();
cachedHints = session.getHints(query, matcher);
$(self).triggerHandler("resolvedResponse", [cachedHints, cachedType]);
@@ -257,7 +259,7 @@ define(function (require, exports, module) {
}
if (cachedHints) {
cachedHints = session.getHints(session.getQuery());
cachedHints = session.getHints(session.getQuery(), matcher);
return getHintResponse(cachedHints, query, type);
}
}
@@ -275,7 +277,7 @@ define(function (require, exports, module) {
*/
JSHints.prototype.insertHint = function ($hintObj) {
var hint = $hintObj.data("token"),
completion = hint.value,
completion = hint.label,
cursor = session.getCursor(),
token = session.getToken(cursor),
query = session.getQuery(),