_id
stringlengths 2
6
| title
stringlengths 0
58
| partition
stringclasses 3
values | text
stringlengths 52
373k
| language
stringclasses 1
value | meta_information
dict |
|---|---|---|---|---|---|
q17300
|
_validateBaseUrl
|
train
|
function _validateBaseUrl(url) {
var result = "";
// Empty url means "no server mapping; use file directly"
if (url === "") {
return result;
}
var obj = PathUtils.parseUrl(url);
if (!obj) {
result = Strings.BASEURL_ERROR_UNKNOWN_ERROR;
} else if (obj.href.search(/^(http|https):\/\//i) !== 0) {
result = StringUtils.format(Strings.BASEURL_ERROR_INVALID_PROTOCOL, obj.href.substring(0, obj.href.indexOf("//")));
} else if (obj.search !== "") {
result = StringUtils.format(Strings.BASEURL_ERROR_SEARCH_DISALLOWED, obj.search);
} else if (obj.hash !== "") {
result = StringUtils.format(Strings.BASEURL_ERROR_HASH_DISALLOWED, obj.hash);
} else {
var index = url.search(/[ \^\[\]\{\}<>\\"\?]+/);
if (index !== -1) {
result = StringUtils.format(Strings.BASEURL_ERROR_INVALID_CHAR, url[index]);
}
}
return result;
}
|
javascript
|
{
"resource": ""
}
|
q17301
|
showProjectPreferencesDialog
|
train
|
function showProjectPreferencesDialog(baseUrl, errorMessage) {
var $baseUrlControl,
dialog;
// Title
var projectName = "",
projectRoot = ProjectManager.getProjectRoot(),
title;
if (projectRoot) {
projectName = projectRoot.name;
}
title = StringUtils.format(Strings.PROJECT_SETTINGS_TITLE, projectName);
var templateVars = {
title : title,
baseUrl : baseUrl,
errorMessage : errorMessage,
Strings : Strings
};
dialog = Dialogs.showModalDialogUsingTemplate(Mustache.render(SettingsDialogTemplate, templateVars));
dialog.done(function (id) {
if (id === Dialogs.DIALOG_BTN_OK) {
var baseUrlValue = $baseUrlControl.val();
var result = _validateBaseUrl(baseUrlValue);
if (result === "") {
// Send analytics data when url is set in project settings
HealthLogger.sendAnalyticsData(
"projectSettingsLivepreview",
"usage",
"projectSettings",
"use"
);
ProjectManager.setBaseUrl(baseUrlValue);
} else {
// Re-invoke dialog with result (error message)
showProjectPreferencesDialog(baseUrlValue, result);
}
}
});
// Give focus to first control
$baseUrlControl = dialog.getElement().find(".url");
$baseUrlControl.focus();
return dialog;
}
|
javascript
|
{
"resource": ""
}
|
q17302
|
_validEvent
|
train
|
function _validEvent(event) {
if (window.navigator.platform.substr(0, 3) === "Mac") {
// Mac
return event.metaKey;
} else {
// Windows
return event.ctrlKey;
}
}
|
javascript
|
{
"resource": ""
}
|
q17303
|
_screenOffset
|
train
|
function _screenOffset(element) {
var elemBounds = element.getBoundingClientRect(),
body = window.document.body,
offsetTop,
offsetLeft;
if (window.getComputedStyle(body).position === "static") {
offsetLeft = elemBounds.left + window.pageXOffset;
offsetTop = elemBounds.top + window.pageYOffset;
} else {
var bodyBounds = body.getBoundingClientRect();
offsetLeft = elemBounds.left - bodyBounds.left;
offsetTop = elemBounds.top - bodyBounds.top;
}
return { left: offsetLeft, top: offsetTop };
}
|
javascript
|
{
"resource": ""
}
|
q17304
|
_trigger
|
train
|
function _trigger(element, name, value, autoRemove) {
var key = "data-ld-" + name;
if (value !== undefined && value !== null) {
element.setAttribute(key, value);
if (autoRemove) {
window.setTimeout(element.removeAttribute.bind(element, key));
}
} else {
element.removeAttribute(key);
}
}
|
javascript
|
{
"resource": ""
}
|
q17305
|
isInViewport
|
train
|
function isInViewport(element) {
var rect = element.getBoundingClientRect();
var html = window.document.documentElement;
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <= (window.innerHeight || html.clientHeight) &&
rect.right <= (window.innerWidth || html.clientWidth)
);
}
|
javascript
|
{
"resource": ""
}
|
q17306
|
Menu
|
train
|
function Menu(element) {
this.element = element;
_trigger(this.element, "showgoto", 1, true);
window.setTimeout(window.remoteShowGoto);
this.remove = this.remove.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
q17307
|
highlight
|
train
|
function highlight(node, clear) {
if (!_remoteHighlight) {
_remoteHighlight = new Highlight("#cfc");
}
if (clear) {
_remoteHighlight.clear();
}
_remoteHighlight.add(node, true);
}
|
javascript
|
{
"resource": ""
}
|
q17308
|
highlightRule
|
train
|
function highlightRule(rule) {
hideHighlight();
var i, nodes = window.document.querySelectorAll(rule);
for (i = 0; i < nodes.length; i++) {
highlight(nodes[i]);
}
_remoteHighlight.selector = rule;
}
|
javascript
|
{
"resource": ""
}
|
q17309
|
_scrollHandler
|
train
|
function _scrollHandler(e) {
// Document scrolls can be updated immediately. Any other scrolls
// need to be updated on a timer to ensure the layout is correct.
if (e.target === window.document) {
redrawHighlights();
} else {
if (_remoteHighlight || _localHighlight) {
window.setTimeout(redrawHighlights, 0);
}
}
}
|
javascript
|
{
"resource": ""
}
|
q17310
|
findMatchingSpecial
|
train
|
function findMatchingSpecial() {
// used to loop through the specials
var i;
for (i = specialsCounter; i < specials.length; i++) {
// short circuit this search when we know there are no matches following
if (specials[i] >= deadBranches[queryCounter]) {
break;
}
// First, ensure that we're not comparing specials that
// come earlier in the string than our current search position.
// This can happen when the string position changes elsewhere.
if (specials[i] < strCounter) {
specialsCounter = i;
} else if (query[queryCounter] === str[specials[i]]) {
// we have a match! do the required tracking
strCounter = specials[i];
// Upper case match check:
// If the query and original string matched, but the original string
// and the lower case version did not, that means that the original
// was upper case.
var upper = originalQuery[queryCounter] === originalStr[strCounter] && originalStr[strCounter] !== str[strCounter];
result.push(new SpecialMatch(strCounter, upper));
specialsCounter = i;
queryCounter++;
strCounter++;
return true;
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q17311
|
backtrack
|
train
|
function backtrack() {
// The idea is to pull matches off of our match list, rolling back
// characters from the query. We pay special attention to the special
// characters since they are searched first.
while (result.length > 0) {
var item = result.pop();
// nothing in the list? there's no possible match then.
if (!item) {
return false;
}
// we pulled off a match, which means that we need to put a character
// back into our query. strCounter is going to be set once we've pulled
// off the right special character and know where we're going to restart
// searching from.
queryCounter--;
if (item instanceof SpecialMatch) {
// pulled off a special, which means we need to make that special available
// for matching again
specialsCounter--;
// check to see if we've gone back as far as we need to
if (item.index < deadBranches[queryCounter]) {
// we now know that this part of the query does not match beyond this
// point
deadBranches[queryCounter] = item.index - 1;
// since we failed with the specials along this track, we're
// going to reset to looking for matches consecutively.
state = ANY_MATCH;
// we figure out where to start looking based on the new
// last item in the list. If there isn't anything else
// in the match list, we'll start over at the starting special
// (which is generally the beginning of the string, or the
// beginning of the last segment of the string)
item = result[result.length - 1];
if (!item) {
strCounter = specials[startingSpecial] + 1;
return true;
}
strCounter = item.index + 1;
return true;
}
}
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q17312
|
closeRangeGap
|
train
|
function closeRangeGap(c) {
// Close the current range
if (currentRange) {
currentRange.includesLastSegment = lastMatchIndex >= lastSegmentStart;
if (currentRange.matched && currentRange.includesLastSegment) {
if (DEBUG_SCORES) {
scoreDebug.lastSegment += lastSegmentScore * LAST_SEGMENT_BOOST;
}
score += lastSegmentScore * LAST_SEGMENT_BOOST;
}
if (currentRange.matched && !currentRangeStartedOnSpecial) {
if (DEBUG_SCORES) {
scoreDebug.notStartingOnSpecial -= NOT_STARTING_ON_SPECIAL_PENALTY;
}
score -= NOT_STARTING_ON_SPECIAL_PENALTY;
}
ranges.push(currentRange);
}
// If there was space between the new range and the last,
// add a new unmatched range before the new range can be added.
if (lastMatchIndex + 1 < c) {
ranges.push({
text: str.substring(lastMatchIndex + 1, c),
matched: false,
includesLastSegment: c > lastSegmentStart
});
}
currentRange = null;
lastSegmentScore = 0;
}
|
javascript
|
{
"resource": ""
}
|
q17313
|
addMatch
|
train
|
function addMatch(match) {
// Pull off the character index
var c = match.index;
var newPoints = 0;
// A match means that we need to do some scoring bookkeeping.
// Start with points added for any match
if (DEBUG_SCORES) {
scoreDebug.match += MATCH_POINTS;
}
newPoints += MATCH_POINTS;
if (match.upper) {
if (DEBUG_SCORES) {
scoreDebug.upper += UPPER_CASE_MATCH;
}
newPoints += UPPER_CASE_MATCH;
}
// A bonus is given for characters that match at the beginning
// of the filename
if (c === lastSegmentStart) {
if (DEBUG_SCORES) {
scoreDebug.beginning += BEGINNING_OF_NAME_POINTS;
}
newPoints += BEGINNING_OF_NAME_POINTS;
}
// If the new character immediately follows the last matched character,
// we award the consecutive matches bonus. The check for score > 0
// handles the initial value of lastMatchIndex which is used for
// constructing ranges but we don't yet have a true match.
if (score > 0 && lastMatchIndex + 1 === c) {
// Continue boosting for each additional match at the beginning
// of the name
if (c - numConsecutive === lastSegmentStart) {
if (DEBUG_SCORES) {
scoreDebug.beginning += BEGINNING_OF_NAME_POINTS;
}
newPoints += BEGINNING_OF_NAME_POINTS;
}
numConsecutive++;
var boost = CONSECUTIVE_MATCHES_POINTS * numConsecutive;
// Consecutive matches that started on a special are a
// good indicator of intent, so we award an added bonus there.
if (currentRangeStartedOnSpecial) {
boost = boost * 2;
}
if (DEBUG_SCORES) {
scoreDebug.consecutive += boost;
}
newPoints += boost;
} else {
numConsecutive = 1;
}
// add points for "special" character matches
if (match instanceof SpecialMatch) {
if (DEBUG_SCORES) {
scoreDebug.special += SPECIAL_POINTS;
}
newPoints += SPECIAL_POINTS;
}
score += newPoints;
// points accumulated in the last segment get an extra bonus
if (c >= lastSegmentStart) {
lastSegmentScore += newPoints;
}
// if the last range wasn't a match or there's a gap, we need to close off
// the range to start a new one.
if ((currentRange && !currentRange.matched) || c > lastMatchIndex + 1) {
closeRangeGap(c);
}
lastMatchIndex = c;
// set up a new match range or add to the current one
if (!currentRange) {
currentRange = {
text: str[c],
matched: true
};
// Check to see if this new matched range is starting on a special
// character. We penalize those ranges that don't, because most
// people will search on the logical boundaries of the name
currentRangeStartedOnSpecial = match instanceof SpecialMatch;
} else {
currentRange.text += str[c];
}
}
|
javascript
|
{
"resource": ""
}
|
q17314
|
_syncGutterWidths
|
train
|
function _syncGutterWidths(hostEditor) {
var allHostedEditors = EditorManager.getInlineEditors(hostEditor);
// add the host itself to the list too
allHostedEditors.push(hostEditor);
var maxWidth = 0;
allHostedEditors.forEach(function (editor) {
var $gutter = $(editor._codeMirror.getGutterElement()).find(".CodeMirror-linenumbers");
$gutter.css("min-width", "");
var curWidth = $gutter.width();
if (curWidth > maxWidth) {
maxWidth = curWidth;
}
});
if (allHostedEditors.length === 1) {
//There's only the host, just refresh the gutter
allHostedEditors[0]._codeMirror.setOption("gutters", allHostedEditors[0]._codeMirror.getOption("gutters"));
return;
}
maxWidth = maxWidth + "px";
allHostedEditors.forEach(function (editor) {
$(editor._codeMirror.getGutterElement()).find(".CodeMirror-linenumbers").css("min-width", maxWidth);
// Force CodeMirror to refresh the gutter
editor._codeMirror.setOption("gutters", editor._codeMirror.getOption("gutters"));
});
}
|
javascript
|
{
"resource": ""
}
|
q17315
|
init
|
train
|
function init(domainManager) {
_domainManager = domainManager;
if (!domainManager.hasDomain("staticServer")) {
domainManager.registerDomain("staticServer", {major: 0, minor: 1});
}
_domainManager.registerCommand(
"staticServer",
"_setRequestFilterTimeout",
_cmdSetRequestFilterTimeout,
false,
"Unit tests only. Set timeout value for filtered requests.",
[{
name: "timeout",
type: "number",
description: "Duration to wait before passing a filtered request to the static file server."
}],
[]
);
_domainManager.registerCommand(
"staticServer",
"getServer",
_cmdGetServer,
true,
"Starts or returns an existing server for the given path.",
[
{
name: "path",
type: "string",
description: "Absolute filesystem path for root of server."
},
{
name: "port",
type: "number",
description: "Port number to use for HTTP server. Pass zero to assign a random port."
}
],
[{
name: "address",
type: "{address: string, family: string, port: number}",
description: "hostname (stored in 'address' parameter), port, and socket type (stored in 'family' parameter) for the server. Currently, 'family' will always be 'IPv4'."
}]
);
_domainManager.registerCommand(
"staticServer",
"closeServer",
_cmdCloseServer,
false,
"Closes the server for the given path.",
[{
name: "path",
type: "string",
description: "absolute filesystem path for root of server"
}],
[{
name: "result",
type: "boolean",
description: "indicates whether a server was found for the specific path then closed"
}]
);
_domainManager.registerCommand(
"staticServer",
"setRequestFilterPaths",
_cmdSetRequestFilterPaths,
false,
"Defines a set of paths from a server's root path to watch and fire 'requestFilter' events for.",
[
{
name: "root",
type: "string",
description: "absolute filesystem path for root of server"
},
{
name: "paths",
type: "Array",
description: "path to notify"
}
],
[]
);
_domainManager.registerCommand(
"staticServer",
"writeFilteredResponse",
_cmdWriteFilteredResponse,
false,
"Overrides the server response from static middleware with the provided response data. This should be called only in response to a filtered request.",
[
{
name: "root",
type: "string",
description: "absolute filesystem path for root of server"
},
{
name: "path",
type: "string",
description: "path to rewrite"
},
{
name: "resData",
type: "{body: string, headers: Array}",
description: "TODO"
}
],
[]
);
_domainManager.registerEvent(
"staticServer",
"requestFilter",
[{
name: "location",
type: "{hostname: string, pathname: string, port: number, root: string: id: number}",
description: "request path"
}]
);
}
|
javascript
|
{
"resource": ""
}
|
q17316
|
_doReplaceInDocument
|
train
|
function _doReplaceInDocument(doc, matchInfo, replaceText, isRegexp) {
// Double-check that the open document's timestamp matches the one we recorded. This
// should normally never go out of sync, because if it did we wouldn't start the
// replace in the first place (due to the fact that we immediately close the search
// results panel whenever we detect a filesystem change that affects the results),
// but we want to double-check in case we don't happen to get the change in time.
// This will *not* handle cases where the document has been edited in memory since
// the matchInfo was generated.
if (doc.diskTimestamp.getTime() !== matchInfo.timestamp.getTime()) {
return new $.Deferred().reject(exports.ERROR_FILE_CHANGED).promise();
}
// Do the replacements in reverse document order so the offsets continue to be correct.
doc.batchOperation(function () {
matchInfo.matches.reverse().forEach(function (match) {
if (match.isChecked) {
doc.replaceRange(isRegexp ? parseDollars(replaceText, match.result) : replaceText, match.start, match.end);
}
});
});
return new $.Deferred().resolve().promise();
}
|
javascript
|
{
"resource": ""
}
|
q17317
|
_doReplaceOnDisk
|
train
|
function _doReplaceOnDisk(fullPath, matchInfo, replaceText, isRegexp) {
var file = FileSystem.getFileForPath(fullPath);
return DocumentManager.getDocumentText(file, true).then(function (contents, timestamp, lineEndings) {
if (timestamp.getTime() !== matchInfo.timestamp.getTime()) {
// Return a promise that we'll reject immediately. (We can't just return the
// error since this is the success handler.)
return new $.Deferred().reject(exports.ERROR_FILE_CHANGED).promise();
}
// Note that this assumes that the matches are sorted.
// TODO: is there a more efficient way to do this in a large string?
var result = [],
lastIndex = 0;
matchInfo.matches.forEach(function (match) {
if (match.isChecked) {
result.push(contents.slice(lastIndex, match.startOffset));
result.push(isRegexp ? parseDollars(replaceText, match.result) : replaceText);
lastIndex = match.endOffset;
}
});
result.push(contents.slice(lastIndex));
var newContents = result.join("");
// TODO: duplicated logic from Document - should refactor this?
if (lineEndings === FileUtils.LINE_ENDINGS_CRLF) {
newContents = newContents.replace(/\n/g, "\r\n");
}
return Async.promisify(file, "write", newContents);
});
}
|
javascript
|
{
"resource": ""
}
|
q17318
|
_doReplaceInOneFile
|
train
|
function _doReplaceInOneFile(fullPath, matchInfo, replaceText, options) {
var doc = DocumentManager.getOpenDocumentForPath(fullPath);
options = options || {};
// If we're forcing files open, or if the document is in the working set but not actually open
// yet, we want to open the file and do the replacement in memory.
if (!doc && (options.forceFilesOpen || MainViewManager.findInWorkingSet(MainViewManager.ALL_PANES, fullPath) !== -1)) {
return DocumentManager.getDocumentForPath(fullPath).then(function (newDoc) {
return _doReplaceInDocument(newDoc, matchInfo, replaceText, options.isRegexp);
});
} else if (doc) {
return _doReplaceInDocument(doc, matchInfo, replaceText, options.isRegexp);
} else {
return _doReplaceOnDisk(fullPath, matchInfo, replaceText, options.isRegexp);
}
}
|
javascript
|
{
"resource": ""
}
|
q17319
|
labelForScope
|
train
|
function labelForScope(scope) {
if (scope) {
return StringUtils.format(
Strings.FIND_IN_FILES_SCOPED,
StringUtils.breakableUrl(
ProjectManager.makeProjectRelativeIfPossible(scope.fullPath)
)
);
} else {
return Strings.FIND_IN_FILES_NO_SCOPE;
}
}
|
javascript
|
{
"resource": ""
}
|
q17320
|
parseQueryInfo
|
train
|
function parseQueryInfo(queryInfo) {
var queryExpr;
if (!queryInfo || !queryInfo.query) {
return {empty: true};
}
// For now, treat all matches as multiline (i.e. ^/$ match on every line, not the whole
// document). This is consistent with how single-file find works. Eventually we should add
// an option for this.
var flags = "gm";
if (!queryInfo.isCaseSensitive) {
flags += "i";
}
// Is it a (non-blank) regex?
if (queryInfo.isRegexp) {
try {
queryExpr = new RegExp(queryInfo.query, flags);
} catch (e) {
return {valid: false, error: e.message};
}
} else {
// Query is a plain string. Turn it into a regexp
queryExpr = new RegExp(StringUtils.regexEscape(queryInfo.query), flags);
}
return {valid: true, queryExpr: queryExpr};
}
|
javascript
|
{
"resource": ""
}
|
q17321
|
prioritizeOpenFile
|
train
|
function prioritizeOpenFile(files, firstFile) {
var workingSetFiles = MainViewManager.getWorkingSet(MainViewManager.ALL_PANES),
workingSetFileFound = {},
fileSetWithoutWorkingSet = [],
startingWorkingFileSet = [],
propertyName = "",
i = 0;
firstFile = firstFile || "";
// Create a working set path map which indicates if a file in working set is found in file list
for (i = 0; i < workingSetFiles.length; i++) {
workingSetFileFound[workingSetFiles[i].fullPath] = false;
}
// Remove all the working set files from the filtration list
fileSetWithoutWorkingSet = files.filter(function (key) {
if (workingSetFileFound[key] !== undefined) {
workingSetFileFound[key] = true;
return false;
}
return true;
});
//push in the first file
if (workingSetFileFound[firstFile] === true) {
startingWorkingFileSet.push(firstFile);
workingSetFileFound[firstFile] = false;
}
//push in the rest of working set files already present in file list
for (propertyName in workingSetFileFound) {
if (workingSetFileFound.hasOwnProperty(propertyName) && workingSetFileFound[propertyName]) {
startingWorkingFileSet.push(propertyName);
}
}
return startingWorkingFileSet.concat(fileSetWithoutWorkingSet);
}
|
javascript
|
{
"resource": ""
}
|
q17322
|
_trimStack
|
train
|
function _trimStack(stack) {
var indexOfFirstRequireJSline;
// Remove everything in the stack up to the end of the line that shows this module file path
stack = stack.substr(stack.indexOf(")\n") + 2);
// Find the very first line of require.js in the stack if the call is from an extension.
// Remove all those lines from the call stack.
indexOfFirstRequireJSline = stack.indexOf("requirejs/require.js");
if (indexOfFirstRequireJSline !== -1) {
indexOfFirstRequireJSline = stack.lastIndexOf(")", indexOfFirstRequireJSline) + 1;
stack = stack.substr(0, indexOfFirstRequireJSline);
}
return stack;
}
|
javascript
|
{
"resource": ""
}
|
q17323
|
deprecationWarning
|
train
|
function deprecationWarning(message, oncePerCaller, callerStackPos) {
// If oncePerCaller isn't set, then only show the message once no matter who calls it.
if (!message || (!oncePerCaller && displayedWarnings[message])) {
return;
}
// Don't show the warning again if we've already gotten it from the current caller.
// The true caller location is the fourth line in the stack trace:
// * 0 is the word "Error"
// * 1 is this function
// * 2 is the caller of this function (the one throwing the deprecation warning)
// * 3 is the actual caller of the deprecated function.
var stack = new Error().stack,
callerLocation = stack.split("\n")[callerStackPos || 3];
if (oncePerCaller && displayedWarnings[message] && displayedWarnings[message][callerLocation]) {
return;
}
console.warn(message + "\n" + _trimStack(stack));
if (!displayedWarnings[message]) {
displayedWarnings[message] = {};
}
displayedWarnings[message][callerLocation] = true;
}
|
javascript
|
{
"resource": ""
}
|
q17324
|
deprecateEvent
|
train
|
function deprecateEvent(outbound, inbound, oldEventName, newEventName, canonicalOutboundName, canonicalInboundName) {
// Mark deprecated so EventDispatcher.on() will emit warnings
EventDispatcher.markDeprecated(outbound, oldEventName, canonicalInboundName);
// create an event handler for the new event to listen for
inbound.on(newEventName, function () {
// Dispatch the event in case anyone is still listening
EventDispatcher.triggerWithArray(outbound, oldEventName, Array.prototype.slice.call(arguments, 1));
});
}
|
javascript
|
{
"resource": ""
}
|
q17325
|
deprecateConstant
|
train
|
function deprecateConstant(obj, oldId, newId) {
var warning = "Use Menus." + newId + " instead of Menus." + oldId,
newValue = obj[newId];
Object.defineProperty(obj, oldId, {
get: function () {
deprecationWarning(warning, true);
return newValue;
}
});
}
|
javascript
|
{
"resource": ""
}
|
q17326
|
setViewState
|
train
|
function setViewState(id, value, context, doNotSave) {
PreferencesImpl.stateManager.set(id, value, context);
if (!doNotSave) {
PreferencesImpl.stateManager.save();
}
}
|
javascript
|
{
"resource": ""
}
|
q17327
|
movePrevToken
|
train
|
function movePrevToken(ctx, precise) {
if (precise === undefined) {
precise = true;
}
if (ctx.pos.ch <= 0 || ctx.token.start <= 0) {
//move up a line
if (ctx.pos.line <= 0) {
return false; //at the top already
}
ctx.pos.line--;
ctx.pos.ch = ctx.editor.getLine(ctx.pos.line).length;
} else {
ctx.pos.ch = ctx.token.start;
}
ctx.token = getTokenAt(ctx.editor, ctx.pos, precise);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q17328
|
moveNextToken
|
train
|
function moveNextToken(ctx, precise) {
var eol = ctx.editor.getLine(ctx.pos.line).length;
if (precise === undefined) {
precise = true;
}
if (ctx.pos.ch >= eol || ctx.token.end >= eol) {
//move down a line
if (ctx.pos.line >= ctx.editor.lineCount() - 1) {
return false; //at the bottom
}
ctx.pos.line++;
ctx.pos.ch = 0;
} else {
ctx.pos.ch = ctx.token.end + 1;
}
ctx.token = getTokenAt(ctx.editor, ctx.pos, precise);
return true;
}
|
javascript
|
{
"resource": ""
}
|
q17329
|
moveSkippingWhitespace
|
train
|
function moveSkippingWhitespace(moveFxn, ctx) {
if (!moveFxn(ctx)) {
return false;
}
while (!ctx.token.type && !/\S/.test(ctx.token.string)) {
if (!moveFxn(ctx)) {
return false;
}
}
return true;
}
|
javascript
|
{
"resource": ""
}
|
q17330
|
offsetInToken
|
train
|
function offsetInToken(ctx) {
var offset = ctx.pos.ch - ctx.token.start;
if (offset < 0) {
console.log("CodeHintUtils: _offsetInToken - Invalid context: pos not in the current token!");
}
return offset;
}
|
javascript
|
{
"resource": ""
}
|
q17331
|
getModeAt
|
train
|
function getModeAt(cm, pos, precise) {
precise = precise || true;
var modeData = cm.getMode(),
name;
if (modeData.innerMode) {
modeData = CodeMirror.innerMode(modeData, getTokenAt(cm, pos, precise).state).mode;
}
name = (modeData.name === "xml") ?
modeData.configuration : modeData.name;
return {mode: modeData, name: name};
}
|
javascript
|
{
"resource": ""
}
|
q17332
|
node
|
train
|
function node(n) {
if (!LiveDevelopment.config.experimental) {
return;
}
if (!Inspector.config.highlight) {
return;
}
// go to the parent of a text node
if (n && n.type === 3) {
n = n.parent;
}
// node cannot be highlighted
if (!n || !n.nodeId || n.type !== 1) {
return hide();
}
// node is already highlighted
if (_highlight.type === "node" && _highlight.ref === n.nodeId) {
return;
}
// highlight the node
_highlight = {type: "node", ref: n.nodeId};
Inspector.DOM.highlightNode(n.nodeId, Inspector.config.highlightConfig);
}
|
javascript
|
{
"resource": ""
}
|
q17333
|
rule
|
train
|
function rule(name) {
if (_highlight.ref === name) {
return;
}
hide();
_highlight = {type: "css", ref: name};
RemoteAgent.call("highlightRule", name);
}
|
javascript
|
{
"resource": ""
}
|
q17334
|
domElement
|
train
|
function domElement(ids) {
var selector = "";
if (!Array.isArray(ids)) {
ids = [ids];
}
_.each(ids, function (id) {
if (selector !== "") {
selector += ",";
}
selector += "[data-brackets-id='" + id + "']";
});
rule(selector);
}
|
javascript
|
{
"resource": ""
}
|
q17335
|
openAndSelectDocument
|
train
|
function openAndSelectDocument(fullPath, fileSelectionFocus, paneId) {
var result,
curDocChangedDueToMe = _curDocChangedDueToMe;
function _getDerivedPaneContext() {
function _secondPaneContext() {
return (window.event.ctrlKey || window.event.metaKey) && window.event.altKey ? MainViewManager.SECOND_PANE : null;
}
function _firstPaneContext() {
return (window.event.ctrlKey || window.event.metaKey) ? MainViewManager.FIRST_PANE : null;
}
return window.event && (_secondPaneContext() || _firstPaneContext());
}
if (fileSelectionFocus !== PROJECT_MANAGER && fileSelectionFocus !== WORKING_SET_VIEW) {
console.error("Bad parameter passed to FileViewController.openAndSelectDocument");
return;
}
// Opening files are asynchronous and we want to know when this function caused a file
// to open so that _fileSelectionFocus is set appropriatly. _curDocChangedDueToMe is set here
// and checked in the currentFileChange handler
_curDocChangedDueToMe = true;
_fileSelectionFocus = fileSelectionFocus;
paneId = (paneId || _getDerivedPaneContext() || MainViewManager.ACTIVE_PANE);
// If fullPath corresonds to the current doc being viewed then opening the file won't
// trigger a currentFileChange event, so we need to trigger a documentSelectionFocusChange
// in this case to signify the selection focus has changed even though the current document has not.
var currentPath = MainViewManager.getCurrentlyViewedPath(paneId);
if (currentPath === fullPath) {
_activatePane(paneId);
result = (new $.Deferred()).resolve().promise();
} else {
result = CommandManager.execute(Commands.FILE_OPEN, {fullPath: fullPath,
paneId: paneId});
}
// clear after notification is done
result.always(function () {
_curDocChangedDueToMe = curDocChangedDueToMe;
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q17336
|
generateJsonForMustache
|
train
|
function generateJsonForMustache(msgObj) {
var msgJsonObj = {};
if (msgObj.type) {
msgJsonObj.type = "'" + msgObj.type + "'";
}
msgJsonObj.title = msgObj.title;
msgJsonObj.description = msgObj.description;
if (msgObj.needButtons) {
msgJsonObj.buttons = [{
"id": "restart",
"value": Strings.RESTART_BUTTON,
"tIndex": "'0'"
}, {
"id": "later",
"value": Strings.LATER_BUTTON,
"tIndex": "'0'"
}];
msgJsonObj.needButtons = msgObj.needButtons;
}
return msgJsonObj;
}
|
javascript
|
{
"resource": ""
}
|
q17337
|
train
|
function () {
if($updateContent.length > 0 && $contentContainer.length > 0 && $updateBar.length > 0) {
var newWidth = $updateBar.outerWidth() - 38;
if($buttonContainer.length > 0) {
newWidth = newWidth- $buttonContainer.outerWidth();
}
if($iconContainer.length > 0) {
newWidth = newWidth - $iconContainer.outerWidth();
}
if($closeIconContainer.length > 0) {
newWidth = newWidth - $closeIconContainer.outerWidth();
}
$contentContainer.css({
"maxWidth": newWidth
});
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17338
|
train
|
function (href) {
var self = this;
// Inspect CSSRules for @imports:
// styleSheet obejct is required to scan CSSImportRules but
// browsers differ on the implementation of MutationObserver interface.
// Webkit triggers notifications before stylesheets are loaded,
// Firefox does it after loading.
// There are also differences on when 'load' event is triggered for
// the 'link' nodes. Webkit triggers it before stylesheet is loaded.
// Some references to check:
// http://www.phpied.com/when-is-a-stylesheet-really-loaded/
// http://stackoverflow.com/questions/17747616/webkit-dynamically-created-stylesheet-when-does-it-really-load
// http://stackoverflow.com/questions/11425209/are-dom-mutation-observers-slower-than-dom-mutation-events
//
// TODO: This is just a temporary 'cross-browser' solution, it needs optimization.
var loadInterval = setInterval(function () {
var i;
for (i = 0; i < window.document.styleSheets.length; i++) {
if (window.document.styleSheets[i].href === href) {
//clear interval
clearInterval(loadInterval);
// notify stylesheets added
self.notifyStylesheetAdded(href);
break;
}
}
}, 50);
}
|
javascript
|
{
"resource": ""
}
|
|
q17339
|
train
|
function () {
var added = {},
current,
newStatus;
current = this.stylesheets;
newStatus = related().stylesheets;
Object.keys(newStatus).forEach(function (v, i) {
if (!current[v]) {
added[v] = newStatus[v];
}
});
Object.keys(added).forEach(function (v, i) {
_transport.send(JSON.stringify({
method: "StylesheetAdded",
href: v,
roots: [added[v]]
}));
});
this.stylesheets = newStatus;
}
|
javascript
|
{
"resource": ""
}
|
|
q17340
|
train
|
function () {
var self = this;
var removed = {},
newStatus,
current;
current = self.stylesheets;
newStatus = related().stylesheets;
Object.keys(current).forEach(function (v, i) {
if (!newStatus[v]) {
removed[v] = current[v];
// remove node created by setStylesheetText if any
self.onStylesheetRemoved(current[v]);
}
});
Object.keys(removed).forEach(function (v, i) {
_transport.send(JSON.stringify({
method: "StylesheetRemoved",
href: v,
roots: [removed[v]]
}));
});
self.stylesheets = newStatus;
}
|
javascript
|
{
"resource": ""
}
|
|
q17341
|
start
|
train
|
function start(document, transport) {
_transport = transport;
_document = document;
// start listening to node changes
_enableListeners();
var rel = related();
// send the current status of related docs.
_transport.send(JSON.stringify({
method: "DocumentRelated",
related: rel
}));
// initialize stylesheets with current status for further notifications.
CSS.stylesheets = rel.stylesheets;
}
|
javascript
|
{
"resource": ""
}
|
q17342
|
openLiveBrowser
|
train
|
function openLiveBrowser(url, enableRemoteDebugging) {
var result = new $.Deferred();
brackets.app.openLiveBrowser(url, !!enableRemoteDebugging, function onRun(err, pid) {
if (!err) {
// Undefined ids never get removed from list, so don't push them on
if (pid !== undefined) {
liveBrowserOpenedPIDs.push(pid);
}
result.resolve(pid);
} else {
result.reject(_browserErrToFileError(err));
}
});
return result.promise();
}
|
javascript
|
{
"resource": ""
}
|
q17343
|
BaseServer
|
train
|
function BaseServer(config) {
this._baseUrl = config.baseUrl;
this._root = config.root; // ProjectManager.getProjectRoot().fullPath
this._pathResolver = config.pathResolver; // ProjectManager.makeProjectRelativeIfPossible(doc.file.fullPath)
this._liveDocuments = {};
}
|
javascript
|
{
"resource": ""
}
|
q17344
|
getUserInstalledExtensions
|
train
|
function getUserInstalledExtensions() {
var result = new $.Deferred();
if (!ExtensionManager.hasDownloadedRegistry) {
ExtensionManager.downloadRegistry().done(function () {
result.resolve(getUserExtensionsPresentInRegistry(ExtensionManager.extensions));
})
.fail(function () {
result.resolve([]);
});
} else {
result.resolve(getUserExtensionsPresentInRegistry(ExtensionManager.extensions));
}
return result.promise();
}
|
javascript
|
{
"resource": ""
}
|
q17345
|
getUserInstalledTheme
|
train
|
function getUserInstalledTheme() {
var result = new $.Deferred();
var installedTheme = themesPref.get("theme"),
bracketsTheme;
if (installedTheme === "light-theme" || installedTheme === "dark-theme") {
return result.resolve(installedTheme);
}
if (!ExtensionManager.hasDownloadedRegistry) {
ExtensionManager.downloadRegistry().done(function () {
bracketsTheme = ExtensionManager.extensions[installedTheme];
if (bracketsTheme && bracketsTheme.installInfo && bracketsTheme.installInfo.locationType === ExtensionManager.LOCATION_USER && bracketsTheme.registryInfo) {
result.resolve(installedTheme);
} else {
result.reject();
}
})
.fail(function () {
result.reject();
});
} else {
bracketsTheme = ExtensionManager.extensions[installedTheme];
if (bracketsTheme && bracketsTheme.installInfo && bracketsTheme.installInfo.locationType === ExtensionManager.LOCATION_USER && bracketsTheme.registryInfo) {
result.resolve(installedTheme);
} else {
result.reject();
}
}
return result.promise();
}
|
javascript
|
{
"resource": ""
}
|
q17346
|
normalizeKeyDescriptorString
|
train
|
function normalizeKeyDescriptorString(origDescriptor) {
var hasMacCtrl = false,
hasCtrl = false,
hasAlt = false,
hasShift = false,
key = "",
error = false;
function _compareModifierString(left, right) {
if (!left || !right) {
return false;
}
left = left.trim().toLowerCase();
right = right.trim().toLowerCase();
return (left.length > 0 && left === right);
}
origDescriptor.split("-").forEach(function parseDescriptor(ele, i, arr) {
if (_compareModifierString("ctrl", ele)) {
if (brackets.platform === "mac") {
hasMacCtrl = true;
} else {
hasCtrl = true;
}
} else if (_compareModifierString("cmd", ele)) {
if (brackets.platform === "mac") {
hasCtrl = true;
} else {
error = true;
}
} else if (_compareModifierString("alt", ele)) {
hasAlt = true;
} else if (_compareModifierString("opt", ele)) {
if (brackets.platform === "mac") {
hasAlt = true;
} else {
error = true;
}
} else if (_compareModifierString("shift", ele)) {
hasShift = true;
} else if (key.length > 0) {
console.log("KeyBindingManager normalizeKeyDescriptorString() - Multiple keys defined. Using key: " + key + " from: " + origDescriptor);
error = true;
} else {
key = ele;
}
});
if (error) {
return null;
}
// Check to see if the binding is for "-".
if (key === "" && origDescriptor.search(/^.+--$/) !== -1) {
key = "-";
}
// '+' char is valid if it's the only key. Keyboard shortcut strings should use
// unicode characters (unescaped). Keyboard shortcut display strings may use
// unicode escape sequences (e.g. \u20AC euro sign)
if ((key.indexOf("+")) >= 0 && (key.length > 1)) {
return null;
}
// Ensure that the first letter of the key name is in upper case and the rest are
// in lower case. i.e. 'a' => 'A' and 'up' => 'Up'
if (/^[a-z]/i.test(key)) {
key = _.capitalize(key.toLowerCase());
}
// Also make sure that the second word of PageUp/PageDown has the first letter in upper case.
if (/^Page/.test(key)) {
key = key.replace(/(up|down)$/, function (match, p1) {
return _.capitalize(p1);
});
}
// No restriction on single character key yet, but other key names are restricted to either
// Function keys or those listed in _keyNames array.
if (key.length > 1 && !/F\d+/.test(key) &&
_keyNames.indexOf(key) === -1) {
return null;
}
return _buildKeyDescriptor(hasMacCtrl, hasCtrl, hasAlt, hasShift, key);
}
|
javascript
|
{
"resource": ""
}
|
q17347
|
_translateKeyboardEvent
|
train
|
function _translateKeyboardEvent(event) {
var hasMacCtrl = (brackets.platform === "mac") ? (event.ctrlKey) : false,
hasCtrl = (brackets.platform !== "mac") ? (event.ctrlKey) : (event.metaKey),
hasAlt = (event.altKey),
hasShift = (event.shiftKey),
key = String.fromCharCode(event.keyCode);
//From the W3C, if we can get the KeyboardEvent.keyIdentifier then look here
//As that will let us use keys like then function keys "F5" for commands. The
//full set of values we can use is here
//http://www.w3.org/TR/2007/WD-DOM-Level-3-Events-20071221/keyset.html#KeySet-Set
var ident = event.keyIdentifier;
if (ident) {
if (ident.charAt(0) === "U" && ident.charAt(1) === "+") {
//This is a unicode code point like "U+002A", get the 002A and use that
key = String.fromCharCode(parseInt(ident.substring(2), 16));
} else {
//This is some non-character key, just use the raw identifier
key = ident;
}
}
// Translate some keys to their common names
if (key === "\t") {
key = "Tab";
} else if (key === " ") {
key = "Space";
} else if (key === "\b") {
key = "Backspace";
} else if (key === "Help") {
key = "Insert";
} else if (event.keyCode === KeyEvent.DOM_VK_DELETE) {
key = "Delete";
} else {
key = _mapKeycodeToKey(event.keyCode, key);
}
return _buildKeyDescriptor(hasMacCtrl, hasCtrl, hasAlt, hasShift, key);
}
|
javascript
|
{
"resource": ""
}
|
q17348
|
formatKeyDescriptor
|
train
|
function formatKeyDescriptor(descriptor) {
var displayStr;
if (brackets.platform === "mac") {
displayStr = descriptor.replace(/-(?!$)/g, ""); // remove dashes
displayStr = displayStr.replace("Ctrl", "\u2303"); // Ctrl > control symbol
displayStr = displayStr.replace("Cmd", "\u2318"); // Cmd > command symbol
displayStr = displayStr.replace("Shift", "\u21E7"); // Shift > shift symbol
displayStr = displayStr.replace("Alt", "\u2325"); // Alt > option symbol
} else {
displayStr = descriptor.replace("Ctrl", Strings.KEYBOARD_CTRL);
displayStr = displayStr.replace("Shift", Strings.KEYBOARD_SHIFT);
displayStr = displayStr.replace(/-(?!$)/g, "+");
}
displayStr = displayStr.replace("Space", Strings.KEYBOARD_SPACE);
displayStr = displayStr.replace("PageUp", Strings.KEYBOARD_PAGE_UP);
displayStr = displayStr.replace("PageDown", Strings.KEYBOARD_PAGE_DOWN);
displayStr = displayStr.replace("Home", Strings.KEYBOARD_HOME);
displayStr = displayStr.replace("End", Strings.KEYBOARD_END);
displayStr = displayStr.replace("Ins", Strings.KEYBOARD_INSERT);
displayStr = displayStr.replace("Del", Strings.KEYBOARD_DELETE);
return displayStr;
}
|
javascript
|
{
"resource": ""
}
|
q17349
|
removeBinding
|
train
|
function removeBinding(key, platform) {
if (!key || ((platform !== null) && (platform !== undefined) && (platform !== brackets.platform))) {
return;
}
var normalizedKey = normalizeKeyDescriptorString(key);
if (!normalizedKey) {
console.log("Failed to normalize " + key);
} else if (_isKeyAssigned(normalizedKey)) {
var binding = _keyMap[normalizedKey],
command = CommandManager.get(binding.commandID),
bindings = _commandMap[binding.commandID];
// delete key binding record
delete _keyMap[normalizedKey];
if (bindings) {
// delete mapping from command to key binding
_commandMap[binding.commandID] = bindings.filter(function (b) {
return (b.key !== normalizedKey);
});
if (command) {
command.trigger("keyBindingRemoved", {key: normalizedKey, displayKey: binding.displayKey});
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q17350
|
_handleKey
|
train
|
function _handleKey(key) {
if (_enabled && _keyMap[key]) {
// The execute() function returns a promise because some commands are async.
// Generally, commands decide whether they can run or not synchronously,
// and reject immediately, so we can test for that synchronously.
var promise = CommandManager.execute(_keyMap[key].commandID);
return (promise.state() !== "rejected");
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
q17351
|
addBinding
|
train
|
function addBinding(command, keyBindings, platform) {
var commandID = "",
results;
if (!command) {
console.error("addBinding(): missing required parameter: command");
return;
}
if (!keyBindings) { return; }
if (typeof (command) === "string") {
commandID = command;
} else {
commandID = command.getID();
}
if (Array.isArray(keyBindings)) {
var keyBinding;
results = [];
// process platform-specific bindings first
keyBindings.sort(_sortByPlatform);
keyBindings.forEach(function addSingleBinding(keyBindingRequest) {
// attempt to add keybinding
keyBinding = _addBinding(commandID, keyBindingRequest, keyBindingRequest.platform);
if (keyBinding) {
results.push(keyBinding);
}
});
} else {
results = _addBinding(commandID, keyBindings, platform);
}
return results;
}
|
javascript
|
{
"resource": ""
}
|
q17352
|
getKeyBindings
|
train
|
function getKeyBindings(command) {
var bindings = [],
commandID = "";
if (!command) {
console.error("getKeyBindings(): missing required parameter: command");
return [];
}
if (typeof (command) === "string") {
commandID = command;
} else {
commandID = command.getID();
}
bindings = _commandMap[commandID];
return bindings || [];
}
|
javascript
|
{
"resource": ""
}
|
q17353
|
_handleCommandRegistered
|
train
|
function _handleCommandRegistered(event, command) {
var commandId = command.getID(),
defaults = KeyboardPrefs[commandId];
if (defaults) {
addBinding(commandId, defaults);
}
}
|
javascript
|
{
"resource": ""
}
|
q17354
|
removeGlobalKeydownHook
|
train
|
function removeGlobalKeydownHook(hook) {
var index = _globalKeydownHooks.indexOf(hook);
if (index !== -1) {
_globalKeydownHooks.splice(index, 1);
}
}
|
javascript
|
{
"resource": ""
}
|
q17355
|
_handleKeyEvent
|
train
|
function _handleKeyEvent(event) {
var i, handled = false;
for (i = _globalKeydownHooks.length - 1; i >= 0; i--) {
if (_globalKeydownHooks[i](event)) {
handled = true;
break;
}
}
_detectAltGrKeyDown(event);
if (!handled && _handleKey(_translateKeyboardEvent(event))) {
event.stopPropagation();
event.preventDefault();
}
}
|
javascript
|
{
"resource": ""
}
|
q17356
|
register
|
train
|
function register(name, id, commandFn) {
if (_commands[id]) {
console.log("Attempting to register an already-registered command: " + id);
return null;
}
if (!name || !id || !commandFn) {
console.error("Attempting to register a command with a missing name, id, or command function:" + name + " " + id);
return null;
}
var command = new Command(name, id, commandFn);
_commands[id] = command;
exports.trigger("commandRegistered", command);
return command;
}
|
javascript
|
{
"resource": ""
}
|
q17357
|
registerInternal
|
train
|
function registerInternal(id, commandFn) {
if (_commands[id]) {
console.log("Attempting to register an already-registered command: " + id);
return null;
}
if (!id || !commandFn) {
console.error("Attempting to register an internal command with a missing id, or command function: " + id);
return null;
}
var command = new Command(null, id, commandFn);
_commands[id] = command;
exports.trigger("commandRegistered", command);
return command;
}
|
javascript
|
{
"resource": ""
}
|
q17358
|
execute
|
train
|
function execute(id) {
var command = _commands[id];
if (command) {
try {
exports.trigger("beforeExecuteCommand", id);
} catch (err) {
console.error(err);
}
return command.execute.apply(command, Array.prototype.slice.call(arguments, 1));
} else {
return (new $.Deferred()).reject().promise();
}
}
|
javascript
|
{
"resource": ""
}
|
q17359
|
addMeasurement
|
train
|
function addMeasurement(id) {
if (!enabled) {
return;
}
if (!(id instanceof PerfMeasurement)) {
id = new PerfMeasurement(id, id);
}
var elapsedTime = brackets.app.getElapsedMilliseconds();
if (activeTests[id.id]) {
elapsedTime -= activeTests[id.id].startTime;
delete activeTests[id.id];
}
if (perfData[id]) {
// We have existing data, add to it
if (Array.isArray(perfData[id])) {
perfData[id].push(elapsedTime);
} else {
// Current data is a number, convert to Array
perfData[id] = [perfData[id], elapsedTime];
}
} else {
perfData[id] = elapsedTime;
}
if (id.reent !== undefined) {
if (_reentTests[id] === 0) {
delete _reentTests[id];
} else {
_reentTests[id]--;
}
}
}
|
javascript
|
{
"resource": ""
}
|
q17360
|
finalizeMeasurement
|
train
|
function finalizeMeasurement(id) {
if (activeTests[id.id]) {
delete activeTests[id.id];
}
if (updatableTests[id.id]) {
delete updatableTests[id.id];
}
}
|
javascript
|
{
"resource": ""
}
|
q17361
|
getDelimitedPerfData
|
train
|
function getDelimitedPerfData() {
var result = "";
_.forEach(perfData, function (entry, testName) {
result += getValueAsString(entry) + "\t" + testName + "\n";
});
return result;
}
|
javascript
|
{
"resource": ""
}
|
q17362
|
getHealthReport
|
train
|
function getHealthReport() {
var healthReport = {
projectLoadTimes : "",
fileOpenTimes : ""
};
_.forEach(perfData, function (entry, testName) {
if (StringUtils.startsWith(testName, "Application Startup")) {
healthReport.AppStartupTime = getValueAsString(entry);
} else if (StringUtils.startsWith(testName, "brackets module dependencies resolved")) {
healthReport.ModuleDepsResolved = getValueAsString(entry);
} else if (StringUtils.startsWith(testName, "Load Project")) {
healthReport.projectLoadTimes += ":" + getValueAsString(entry, true);
} else if (StringUtils.startsWith(testName, "Open File")) {
healthReport.fileOpenTimes += ":" + getValueAsString(entry, true);
}
});
return healthReport;
}
|
javascript
|
{
"resource": ""
}
|
q17363
|
getTagAttributes
|
train
|
function getTagAttributes(editor, pos) {
var attrs = [],
backwardCtx = TokenUtils.getInitialContext(editor._codeMirror, pos),
forwardCtx = $.extend({}, backwardCtx);
if (editor.getModeForSelection() === "html") {
if (backwardCtx.token && !tagPrefixedRegExp.test(backwardCtx.token.type)) {
while (TokenUtils.movePrevToken(backwardCtx) && !tagPrefixedRegExp.test(backwardCtx.token.type)) {
if (backwardCtx.token.type === "error" && backwardCtx.token.string.indexOf("<") === 0) {
break;
}
if (backwardCtx.token.type === "attribute") {
attrs.push(backwardCtx.token.string);
}
}
while (TokenUtils.moveNextToken(forwardCtx) && !tagPrefixedRegExp.test(forwardCtx.token.type)) {
if (forwardCtx.token.type === "attribute") {
// If the current tag is not closed, codemirror may return the next opening
// tag as an attribute. Stop the search loop in that case.
if (forwardCtx.token.string.indexOf("<") === 0) {
break;
}
attrs.push(forwardCtx.token.string);
} else if (forwardCtx.token.type === "error") {
if (forwardCtx.token.string.indexOf("<") === 0 || forwardCtx.token.string.indexOf(">") === 0) {
break;
}
// If we type the first letter of the next attribute, it comes as an error
// token. We need to double check for possible invalidated attributes.
if (/\S/.test(forwardCtx.token.string) &&
forwardCtx.token.string.indexOf("\"") === -1 &&
forwardCtx.token.string.indexOf("'") === -1 &&
forwardCtx.token.string.indexOf("=") === -1) {
attrs.push(forwardCtx.token.string);
}
}
}
}
}
return attrs;
}
|
javascript
|
{
"resource": ""
}
|
q17364
|
createTagInfo
|
train
|
function createTagInfo(tokenType, offset, tagName, attrName, attrValue, valueAssigned, quoteChar, hasEndQuote) {
return { tagName: tagName || "",
attr:
{ name: attrName || "",
value: attrValue || "",
valueAssigned: valueAssigned || false,
quoteChar: quoteChar || "",
hasEndQuote: hasEndQuote || false },
position:
{ tokenType: tokenType || "",
offset: offset || 0 } };
}
|
javascript
|
{
"resource": ""
}
|
q17365
|
scanTextUntil
|
train
|
function scanTextUntil(cm, startCh, startLine, condition) {
var line = cm.getLine(startLine),
seen = "",
characterIndex = startCh,
currentLine = startLine,
range;
while (currentLine <= cm.lastLine()) {
if (line.length === 0) {
characterIndex = 0;
line = cm.getLine(++currentLine);
} else {
seen = seen.concat(line[characterIndex] || "");
if (condition(seen)) {
range = {
from: {ch: startCh, line: startLine},
to: {ch: characterIndex, line: currentLine},
string: seen
};
return range;
} else if (characterIndex >= line.length) {
seen = seen.concat(cm.lineSeparator());
if (condition(seen)) {
range = {
from: {ch: startCh, line: startLine},
to: {ch: characterIndex, line: currentLine},
string: seen
};
return range;
}
characterIndex = 0;
line = cm.getLine(++currentLine);
} else {
++characterIndex;
}
}
}
}
|
javascript
|
{
"resource": ""
}
|
q17366
|
styleForURL
|
train
|
function styleForURL(url) {
var styleSheetId, styles = {};
url = _canonicalize(url);
for (styleSheetId in _styleSheetDetails) {
if (_styleSheetDetails[styleSheetId].canonicalizedURL === url) {
styles[styleSheetId] = _styleSheetDetails[styleSheetId];
}
}
return styles;
}
|
javascript
|
{
"resource": ""
}
|
q17367
|
reloadCSSForDocument
|
train
|
function reloadCSSForDocument(doc, newContent) {
var styles = styleForURL(doc.url),
styleSheetId,
deferreds = [];
if (newContent === undefined) {
newContent = doc.getText();
}
for (styleSheetId in styles) {
deferreds.push(Inspector.CSS.setStyleSheetText(styles[styleSheetId].styleSheetId, newContent));
}
if (!deferreds.length) {
console.error("Style Sheet for document not loaded: " + doc.url);
return new $.Deferred().reject().promise();
}
// return master deferred
return $.when.apply($, deferreds);
}
|
javascript
|
{
"resource": ""
}
|
q17368
|
_removeListeners
|
train
|
function _removeListeners() {
DocumentModule.off("documentChange", _documentChangeHandler);
FileSystem.off("change", _debouncedFileSystemChangeHandler);
DocumentManager.off("fileNameChange", _fileNameChangeHandler);
}
|
javascript
|
{
"resource": ""
}
|
q17369
|
_addListeners
|
train
|
function _addListeners() {
// Avoid adding duplicate listeners - e.g. if a 2nd search is run without closing the old results panel first
_removeListeners();
DocumentModule.on("documentChange", _documentChangeHandler);
FileSystem.on("change", _debouncedFileSystemChangeHandler);
DocumentManager.on("fileNameChange", _fileNameChangeHandler);
}
|
javascript
|
{
"resource": ""
}
|
q17370
|
getCandidateFiles
|
train
|
function getCandidateFiles(scope) {
function filter(file) {
return _subtreeFilter(file, scope) && _isReadableText(file.fullPath);
}
// If the scope is a single file, just check if the file passes the filter directly rather than
// trying to use ProjectManager.getAllFiles(), both for performance and because an individual
// in-memory file might be an untitled document that doesn't show up in getAllFiles().
if (scope && scope.isFile) {
return new $.Deferred().resolve(filter(scope) ? [scope] : []).promise();
} else {
return ProjectManager.getAllFiles(filter, true, true);
}
}
|
javascript
|
{
"resource": ""
}
|
q17371
|
doSearchInScope
|
train
|
function doSearchInScope(queryInfo, scope, filter, replaceText, candidateFilesPromise) {
clearSearch();
searchModel.scope = scope;
if (replaceText !== undefined) {
searchModel.isReplace = true;
searchModel.replaceText = replaceText;
}
candidateFilesPromise = candidateFilesPromise || getCandidateFiles(scope);
return _doSearch(queryInfo, candidateFilesPromise, filter);
}
|
javascript
|
{
"resource": ""
}
|
q17372
|
doReplace
|
train
|
function doReplace(results, replaceText, options) {
return FindUtils.performReplacements(results, replaceText, options).always(function () {
// For UI integration testing only
exports._replaceDone = true;
});
}
|
javascript
|
{
"resource": ""
}
|
q17373
|
filesChanged
|
train
|
function filesChanged(fileList) {
if (FindUtils.isNodeSearchDisabled() || !fileList || fileList.length === 0) {
return;
}
var updateObject = {
"fileList": fileList
};
if (searchModel.filter) {
updateObject.filesInSearchScope = FileFilters.getPathsMatchingFilter(searchModel.filter, fileList);
_searchScopeChanged();
}
searchDomain.exec("filesChanged", updateObject);
}
|
javascript
|
{
"resource": ""
}
|
q17374
|
train
|
function (child) {
// Replicate filtering that getAllFiles() does
if (ProjectManager.shouldShow(child)) {
if (child.isFile && _isReadableText(child.name)) {
// Re-check the filtering that the initial search applied
if (_inSearchScope(child)) {
addedFiles.push(child);
addedFilePaths.push(child.fullPath);
}
}
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q17375
|
train
|
function () {
function filter(file) {
return _subtreeFilter(file, null) && _isReadableText(file.fullPath);
}
FindUtils.setInstantSearchDisabled(true);
//we always listen for filesytem changes.
_addListeners();
if (!PreferencesManager.get("findInFiles.nodeSearch")) {
return;
}
ProjectManager.getAllFiles(filter, true, true)
.done(function (fileListResult) {
var files = fileListResult,
filter = FileFilters.getActiveFilter();
if (filter && filter.patterns.length > 0) {
files = FileFilters.filterFileList(FileFilters.compile(filter.patterns), files);
}
files = files.filter(function (entry) {
return entry.isFile && _isReadableText(entry.fullPath);
}).map(function (entry) {
return entry.fullPath;
});
FindUtils.notifyIndexingStarted();
searchDomain.exec("initCache", files);
});
_searchScopeChanged();
}
|
javascript
|
{
"resource": ""
}
|
|
q17376
|
getNextPageofSearchResults
|
train
|
function getNextPageofSearchResults() {
var searchDeferred = $.Deferred();
if (searchModel.allResultsAvailable) {
return searchDeferred.resolve().promise();
}
_updateChangedDocs();
FindUtils.notifyNodeSearchStarted();
searchDomain.exec("nextPage")
.done(function (rcvd_object) {
FindUtils.notifyNodeSearchFinished();
if (searchModel.results) {
var resultEntry;
for (resultEntry in rcvd_object.results ) {
if (rcvd_object.results.hasOwnProperty(resultEntry)) {
searchModel.results[resultEntry.toString()] = rcvd_object.results[resultEntry];
}
}
} else {
searchModel.results = rcvd_object.results;
}
searchModel.fireChanged();
searchDeferred.resolve();
})
.fail(function () {
FindUtils.notifyNodeSearchFinished();
console.log('node fails');
FindUtils.setNodeSearchDisabled(true);
searchDeferred.reject();
});
return searchDeferred.promise();
}
|
javascript
|
{
"resource": ""
}
|
q17377
|
train
|
function (beforeID, isBeingDeleted) {
newEdits.forEach(function (edit) {
// elementDeletes don't need any positioning information
if (edit.type !== "elementDelete") {
edit.beforeID = beforeID;
}
});
edits.push.apply(edits, newEdits);
newEdits = [];
// If the item we made this set of edits relative to
// is being deleted, we can't use it as the afterID for future
// edits. It's okay to just keep the previous afterID, since
// this node will no longer be in the tree by the time we get
// to any future edit that needs an afterID.
if (!isBeingDeleted) {
textAfterID = beforeID;
}
}
|
javascript
|
{
"resource": ""
}
|
|
q17378
|
train
|
function () {
if (!oldNodeMap[newChild.tagID]) {
newEdit = {
type: "elementInsert",
tag: newChild.tag,
tagID: newChild.tagID,
parentID: newChild.parent.tagID,
attributes: newChild.attributes
};
newEdits.push(newEdit);
// This newly inserted node needs to have edits generated for its
// children, so we add it to the queue.
newElements.push(newChild);
// A textInsert edit that follows this elementInsert should use
// this element's ID.
textAfterID = newChild.tagID;
// new element means we need to move on to compare the next
// of the current tree with the one from the old tree that we
// just compared
newIndex++;
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q17379
|
train
|
function () {
if (!newNodeMap[oldChild.tagID]) {
// We can finalize existing edits relative to this node *before* it's
// deleted.
finalizeNewEdits(oldChild.tagID, true);
newEdit = {
type: "elementDelete",
tagID: oldChild.tagID
};
newEdits.push(newEdit);
// deleted element means we need to move on to compare the next
// of the old tree with the one from the current tree that we
// just compared
oldIndex++;
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q17380
|
train
|
function () {
newEdit = {
type: "textInsert",
content: newChild.content,
parentID: newChild.parent.tagID
};
// text changes will generally have afterID and beforeID, but we make
// special note if it's the first child.
if (textAfterID) {
newEdit.afterID = textAfterID;
} else {
newEdit.firstChild = true;
}
newEdits.push(newEdit);
// The text node is in the new tree, so we move to the next new tree item
newIndex++;
}
|
javascript
|
{
"resource": ""
}
|
|
q17381
|
train
|
function () {
var prev = prevNode();
if (prev && !prev.children) {
newEdit = {
type: "textReplace",
content: prev.content
};
} else {
newEdit = {
type: "textDelete"
};
}
// When elements are deleted or moved from the old set of children, you
// can end up with multiple text nodes in a row. A single textReplace edit
// will take care of those (and will contain all of the right content since
// the text nodes between elements in the new DOM are merged together).
// The check below looks to see if we're already in the process of adding
// a textReplace edit following the same element.
var previousEdit = newEdits.length > 0 && newEdits[newEdits.length - 1];
if (previousEdit && previousEdit.type === "textReplace" &&
previousEdit.afterID === textAfterID) {
oldIndex++;
return;
}
newEdit.parentID = oldChild.parent.tagID;
// If there was only one child previously, we just pass along
// textDelete/textReplace with the parentID and the browser will
// clear all of the children
if (oldChild.parent.children.length === 1) {
newEdits.push(newEdit);
} else {
if (textAfterID) {
newEdit.afterID = textAfterID;
}
newEdits.push(newEdit);
}
// This text appeared in the old tree but not the new one, so we
// increment the old children counter.
oldIndex++;
}
|
javascript
|
{
"resource": ""
}
|
|
q17382
|
train
|
function () {
// This check looks a little strange, but it suits what we're trying
// to do: as we're walking through the children, a child node that has moved
// from one parent to another will be found but would look like some kind
// of insert. The check that we're doing here is looking up the current
// child's ID in the *old* map and seeing if this child used to have a
// different parent.
var possiblyMovedElement = oldNodeMap[newChild.tagID];
if (possiblyMovedElement &&
newParent.tagID !== getParentID(possiblyMovedElement)) {
newEdit = {
type: "elementMove",
tagID: newChild.tagID,
parentID: newChild.parent.tagID
};
moves.push(newEdit.tagID);
newEdits.push(newEdit);
// this element in the new tree was a move to this spot, so we can move
// on to the next child in the new tree.
newIndex++;
return true;
}
return false;
}
|
javascript
|
{
"resource": ""
}
|
|
q17383
|
train
|
function (oldChild) {
var oldChildInNewTree = newNodeMap[oldChild.tagID];
return oldChild.children && oldChildInNewTree && getParentID(oldChild) !== getParentID(oldChildInNewTree);
}
|
javascript
|
{
"resource": ""
}
|
|
q17384
|
train
|
function (delta) {
edits.push.apply(edits, delta.edits);
moves.push.apply(moves, delta.moves);
queue.push.apply(queue, delta.newElements);
}
|
javascript
|
{
"resource": ""
}
|
|
q17385
|
_handleFileSystemChange
|
train
|
function _handleFileSystemChange(event, entry, added, removed) {
// this may have been called because files were added
// or removed to the file system. We don't care about those
if (!entry || entry.isDirectory) {
return;
}
// Look for a viewer for the changed file
var viewer = _viewers[entry.fullPath];
// viewer found, call its refresh method
if (viewer) {
viewer.refresh();
}
}
|
javascript
|
{
"resource": ""
}
|
q17386
|
setFontSize
|
train
|
function setFontSize(fontSize) {
if (currFontSize === fontSize) {
return;
}
_removeDynamicFontSize();
if (fontSize) {
_addDynamicFontSize(fontSize);
}
// Update scroll metrics in viewed editors
_.forEach(MainViewManager.getPaneIdList(), function (paneId) {
var currentPath = MainViewManager.getCurrentlyViewedPath(paneId),
doc = currentPath && DocumentManager.getOpenDocumentForPath(currentPath);
if (doc && doc._masterEditor) {
_updateScroll(doc._masterEditor, fontSize);
}
});
exports.trigger("fontSizeChange", fontSize, currFontSize);
currFontSize = fontSize;
prefs.set("fontSize", fontSize);
}
|
javascript
|
{
"resource": ""
}
|
q17387
|
setFontFamily
|
train
|
function setFontFamily(fontFamily) {
var editor = EditorManager.getCurrentFullEditor();
if (currFontFamily === fontFamily) {
return;
}
_removeDynamicFontFamily();
if (fontFamily) {
_addDynamicFontFamily(fontFamily);
}
exports.trigger("fontFamilyChange", fontFamily, currFontFamily);
currFontFamily = fontFamily;
prefs.set("fontFamily", fontFamily);
if (editor) {
editor.refreshAll();
}
}
|
javascript
|
{
"resource": ""
}
|
q17388
|
init
|
train
|
function init() {
currFontFamily = prefs.get("fontFamily");
_addDynamicFontFamily(currFontFamily);
currFontSize = prefs.get("fontSize");
_addDynamicFontSize(currFontSize);
_updateUI();
}
|
javascript
|
{
"resource": ""
}
|
q17389
|
restoreFontSize
|
train
|
function restoreFontSize() {
var fsStyle = prefs.get("fontSize"),
fsAdjustment = PreferencesManager.getViewState("fontSizeAdjustment");
if (fsAdjustment) {
// Always remove the old view state even if we also have the new view state.
PreferencesManager.setViewState("fontSizeAdjustment");
if (!fsStyle) {
// Migrate the old view state to the new one.
fsStyle = (DEFAULT_FONT_SIZE + fsAdjustment) + "px";
prefs.set("fontSize", fsStyle);
}
}
if (fsStyle) {
_removeDynamicFontSize();
_addDynamicFontSize(fsStyle);
}
}
|
javascript
|
{
"resource": ""
}
|
q17390
|
CubicBezier
|
train
|
function CubicBezier(coordinates) {
if (typeof coordinates === "string") {
this.coordinates = coordinates.split(",");
} else {
this.coordinates = coordinates;
}
if (!this.coordinates) {
throw "No offsets were defined";
}
this.coordinates = this.coordinates.map(function (n) { return +n; });
var i;
for (i = 3; i >= 0; i--) {
var xy = this.coordinates[i];
if (isNaN(xy) || (((i % 2) === 0) && (xy < 0 || xy > 1))) {
throw "Wrong coordinate at " + i + "(" + xy + ")";
}
}
}
|
javascript
|
{
"resource": ""
}
|
q17391
|
BezierCanvas
|
train
|
function BezierCanvas(canvas, bezier, padding) {
this.canvas = canvas;
this.bezier = bezier;
this.padding = this.getPadding(padding);
// Convert to a cartesian coordinate system with axes from 0 to 1
var ctx = this.canvas.getContext("2d"),
p = this.padding;
ctx.scale(canvas.width * (1 - p[1] - p[3]), -canvas.height * 0.5 * (1 - p[0] - p[2]));
ctx.translate(p[3] / (1 - p[1] - p[3]), (-1 - p[0] / (1 - p[0] - p[2])) - 0.5);
}
|
javascript
|
{
"resource": ""
}
|
q17392
|
train
|
function (element) {
var p = this.padding,
w = this.canvas.width,
h = this.canvas.height * 0.5;
// Convert padding percentage to actual padding
p = p.map(function (a, i) {
return a * ((i % 2) ? w : h);
});
return [
this.prettify((parseInt($(element).css("left"), 10) - p[3]) / (w + p[1] + p[3])),
this.prettify((h - parseInt($(element).css("top"), 10) - p[2]) / (h - p[0] - p[2]))
];
}
|
javascript
|
{
"resource": ""
}
|
|
q17393
|
train
|
function (padding) {
var p = (typeof padding === "number") ? [padding] : padding;
if (p.length === 1) {
p[1] = p[0];
}
if (p.length === 2) {
p[2] = p[0];
}
if (p.length === 3) {
p[3] = p[1];
}
return p;
}
|
javascript
|
{
"resource": ""
}
|
|
q17394
|
handlePointMove
|
train
|
function handlePointMove(e, x, y) {
var self = e.target,
bezierEditor = self.bezierEditor;
// Helper function to redraw curve
function mouseMoveRedraw() {
if (!bezierEditor.dragElement) {
animationRequest = null;
return;
}
// Update code
bezierEditor._commitTimingFunction();
bezierEditor._updateCanvas();
animationRequest = window.requestAnimationFrame(mouseMoveRedraw);
}
// This is a dragging state, but left button is no longer down, so mouse
// exited element, was released, and re-entered element. Treat like a drop.
if (bezierEditor.dragElement && (e.which !== 1)) {
bezierEditor.dragElement = null;
bezierEditor._commitTimingFunction();
bezierEditor._updateCanvas();
bezierEditor = null;
return;
}
// Constrain time (x-axis) to 0 to 1 range. Progression (y-axis) is
// theoretically not constrained, although canvas to drawing curve is
// arbitrarily constrained to -0.5 to 1.5 range.
x = Math.min(Math.max(0, x), WIDTH_MAIN);
if (bezierEditor.dragElement) {
$(bezierEditor.dragElement).css({
left: x + "px",
top: y + "px"
});
}
// update coords
bezierEditor._cubicBezierCoords = bezierEditor.bezierCanvas
.offsetsToCoordinates(bezierEditor.P1)
.concat(bezierEditor.bezierCanvas.offsetsToCoordinates(bezierEditor.P2));
if (!animationRequest) {
animationRequest = window.requestAnimationFrame(mouseMoveRedraw);
}
}
|
javascript
|
{
"resource": ""
}
|
q17395
|
mouseMoveRedraw
|
train
|
function mouseMoveRedraw() {
if (!bezierEditor.dragElement) {
animationRequest = null;
return;
}
// Update code
bezierEditor._commitTimingFunction();
bezierEditor._updateCanvas();
animationRequest = window.requestAnimationFrame(mouseMoveRedraw);
}
|
javascript
|
{
"resource": ""
}
|
q17396
|
BezierCurveEditor
|
train
|
function BezierCurveEditor($parent, bezierCurve, callback) {
// Create the DOM structure, filling in localized strings via Mustache
this.$element = $(Mustache.render(BezierCurveEditorTemplate, Strings));
$parent.append(this.$element);
this._callback = callback;
this.dragElement = null;
// current cubic-bezier() function params
this._cubicBezierCoords = this._getCubicBezierCoords(bezierCurve);
this.hint = {};
this.hint.elem = $(".hint", this.$element);
// If function was auto-corrected, then originalString holds the original function,
// and an informational message needs to be shown
if (bezierCurve.originalString) {
TimingFunctionUtils.showHideHint(this.hint, true, bezierCurve.originalString, "cubic-bezier(" + this._cubicBezierCoords.join(", ") + ")");
} else {
TimingFunctionUtils.showHideHint(this.hint, false);
}
this.P1 = this.$element.find(".P1")[0];
this.P2 = this.$element.find(".P2")[0];
this.curve = this.$element.find(".curve")[0];
this.P1.bezierEditor = this.P2.bezierEditor = this.curve.bezierEditor = this;
this.bezierCanvas = new BezierCanvas(this.curve, null, [0, 0]);
// redraw canvas
this._updateCanvas();
$(this.curve)
.on("click", _curveClick)
.on("mousemove", _curveMouseMove);
$(this.P1)
.on("mousemove", _pointMouseMove)
.on("mousedown", _pointMouseDown)
.on("mouseup", _pointMouseUp)
.on("keydown", _pointKeyDown);
$(this.P2)
.on("mousemove", _pointMouseMove)
.on("mousedown", _pointMouseDown)
.on("mouseup", _pointMouseUp)
.on("keydown", _pointKeyDown);
}
|
javascript
|
{
"resource": ""
}
|
q17397
|
StepCanvas
|
train
|
function StepCanvas(canvas, stepParams, padding) {
this.canvas = canvas;
this.stepParams = stepParams;
this.padding = this.getPadding(padding);
// Convert to a cartesian coordinate system with axes from 0 to 1
var ctx = this.canvas.getContext("2d"),
p = this.padding;
ctx.scale(canvas.width * (1 - p[1] - p[3]), -canvas.height * (1 - p[0] - p[2]));
ctx.translate(p[3] / (1 - p[1] - p[3]), (-1 - p[0] / (1 - p[0] - p[2])));
}
|
javascript
|
{
"resource": ""
}
|
q17398
|
StepEditor
|
train
|
function StepEditor($parent, stepMatch, callback) {
// Create the DOM structure, filling in localized strings via Mustache
this.$element = $(Mustache.render(StepEditorTemplate, Strings));
$parent.append(this.$element);
this._callback = callback;
// current step function params
this._stepParams = this._getStepParams(stepMatch);
this.hint = {};
this.hint.elem = $(".hint", this.$element);
// If function was auto-corrected, then originalString holds the original function,
// and an informational message needs to be shown
if (stepMatch.originalString) {
TimingFunctionUtils.showHideHint(this.hint, true, stepMatch.originalString, "steps(" + this._stepParams.count.toString() + ", " + this._stepParams.timing + ")");
} else {
TimingFunctionUtils.showHideHint(this.hint, false);
}
this.canvas = this.$element.find(".steps")[0];
this.canvas.stepEditor = this;
// Padding (3rd param)is scaled, so 0.1 translates to 15px
// Note that this is rendered inside canvas CSS "content"
// (i.e. this does not map to CSS padding)
this.stepCanvas = new StepCanvas(this.canvas, null, [0.1]);
// redraw canvas
this._updateCanvas();
$(this.canvas).on("keydown", _canvasKeyDown);
}
|
javascript
|
{
"resource": ""
}
|
q17399
|
CodeHintList
|
train
|
function CodeHintList(editor, insertHintOnTab, maxResults) {
/**
* The list of hints to display
*
* @type {Array.<string|jQueryObject>}
*/
this.hints = [];
/**
* The selected position in the list; otherwise -1.
*
* @type {number}
*/
this.selectedIndex = -1;
/**
* The maximum number of hints to display. Can be overriden via maxCodeHints pref
*
* @type {number}
*/
this.maxResults = ValidationUtils.isIntegerInRange(maxResults, 1, 1000) ? maxResults : 50;
/**
* Is the list currently open?
*
* @type {boolean}
*/
this.opened = false;
/**
* The editor context
*
* @type {Editor}
*/
this.editor = editor;
/**
* Whether the currently selected hint should be inserted on a tab key event
*
* @type {boolean}
*/
this.insertHintOnTab = insertHintOnTab;
/**
* Pending text insertion
*
* @type {string}
*/
this.pendingText = "";
/**
* The hint selection callback function
*
* @type {Function}
*/
this.handleSelect = null;
/**
* The hint list closure callback function
*
* @type {Function}
*/
this.handleClose = null;
/**
* The hint list menu object
*
* @type {jQuery.Object}
*/
this.$hintMenu =
$("<li class='dropdown codehint-menu'></li>")
.append($("<a href='#' class='dropdown-toggle' data-toggle='dropdown'></a>")
.hide())
.append("<ul class='dropdown-menu'></ul>");
this._keydownHook = this._keydownHook.bind(this);
}
|
javascript
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.