_id
stringlengths
2
6
title
stringlengths
0
58
partition
stringclasses
3 values
text
stringlengths
52
373k
language
stringclasses
1 value
meta_information
dict
q16900
sendHealthDataToServer
train
function sendHealthDataToServer() { var result = new $.Deferred(); getHealthData().done(function (healthData) { var url = brackets.config.healthDataServerURL, data = JSON.stringify(healthData); $.ajax({ url: url, type: "POST", data: data, dataType: "text", contentType: "text/plain" }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Health Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); }) .fail(function () { result.reject(); }); return result.promise(); }
javascript
{ "resource": "" }
q16901
sendAnalyticsDataToServer
train
function sendAnalyticsDataToServer(eventParams) { var result = new $.Deferred(); var analyticsData = getAnalyticsData(eventParams); $.ajax({ url: brackets.config.analyticsDataServerURL, type: "POST", data: JSON.stringify({events: [analyticsData]}), headers: { "Content-Type": "application/json", "x-api-key": brackets.config.serviceKey } }) .done(function () { result.resolve(); }) .fail(function (jqXHR, status, errorThrown) { console.error("Error in sending Adobe Analytics Data. Response : " + jqXHR.responseText + ". Status : " + status + ". Error : " + errorThrown); result.reject(); }); return result.promise(); }
javascript
{ "resource": "" }
q16902
_setStatus
train
function _setStatus(status, closeReason) { // Don't send a notification when the status didn't actually change if (status === exports.status) { return; } exports.status = status; var reason = status === STATUS_INACTIVE ? closeReason : null; exports.trigger("statusChange", status, reason); }
javascript
{ "resource": "" }
q16903
_docIsOutOfSync
train
function _docIsOutOfSync(doc) { var liveDoc = _server && _server.get(doc.file.fullPath), isLiveEditingEnabled = liveDoc && liveDoc.isLiveEditingEnabled(); return doc.isDirty && !isLiveEditingEnabled; }
javascript
{ "resource": "" }
q16904
_styleSheetAdded
train
function _styleSheetAdded(event, url, roots) { var path = _server && _server.urlToPath(url), alreadyAdded = !!_relatedDocuments[url]; // path may be null if loading an external stylesheet. // Also, the stylesheet may already exist and be reported as added twice // due to Chrome reporting added/removed events after incremental changes // are pushed to the browser if (!path || alreadyAdded) { return; } var docPromise = DocumentManager.getDocumentForPath(path); docPromise.done(function (doc) { if ((_classForDocument(doc) === LiveCSSDocument) && (!_liveDocument || (doc !== _liveDocument.doc))) { var liveDoc = _createLiveDocument(doc, doc._masterEditor, roots); if (liveDoc) { _server.add(liveDoc); _relatedDocuments[doc.url] = liveDoc; liveDoc.on("updateDoc", function (event, url) { var path = _server.urlToPath(url), doc = getLiveDocForPath(path); doc._updateBrowser(); }); } } }); }
javascript
{ "resource": "" }
q16905
open
train
function open() { // TODO: need to run _onDocumentChange() after load if doc != currentDocument here? Maybe not, since activeEditorChange // doesn't trigger it, while inline editors can still cause edits in doc other than currentDoc... _getInitialDocFromCurrent().done(function (doc) { var prepareServerPromise = (doc && _prepareServer(doc)) || new $.Deferred().reject(), otherDocumentsInWorkingFiles; if (doc && !doc._masterEditor) { otherDocumentsInWorkingFiles = MainViewManager.getWorkingSetSize(MainViewManager.ALL_PANES); MainViewManager.addToWorkingSet(MainViewManager.ACTIVE_PANE, doc.file); if (!otherDocumentsInWorkingFiles) { CommandManager.execute(Commands.CMD_OPEN, { fullPath: doc.file.fullPath }); } } // wait for server (StaticServer, Base URL or file:) prepareServerPromise .done(function () { _setStatus(STATUS_CONNECTING); _doLaunchAfterServerReady(doc); }) .fail(function () { _showWrongDocError(); }); }); }
javascript
{ "resource": "" }
q16906
init
train
function init(config) { exports.config = config; MainViewManager .on("currentFileChange", _onFileChange); DocumentManager .on("documentSaved", _onDocumentSaved) .on("dirtyFlagChange", _onDirtyFlagChange); ProjectManager .on("beforeProjectClose beforeAppClose", close); // Default transport for live connection messages - can be changed setTransport(NodeSocketTransport); // Default launcher for preview browser - can be changed setLauncher(DefaultLauncher); // Initialize exports.status _setStatus(STATUS_INACTIVE); }
javascript
{ "resource": "" }
q16907
getCurrentProjectServerConfig
train
function getCurrentProjectServerConfig() { return { baseUrl: ProjectManager.getBaseUrl(), pathResolver: ProjectManager.makeProjectRelativeIfPossible, root: ProjectManager.getProjectRoot().fullPath }; }
javascript
{ "resource": "" }
q16908
logNodeState
train
function logNodeState() { if (brackets.app && brackets.app.getNodeState) { brackets.app.getNodeState(function (err, port) { if (err) { console.log("[NodeDebugUtils] Node is in error state " + err); } else { console.log("[NodeDebugUtils] Node is listening on port " + port); } }); } else { console.error("[NodeDebugUtils] No brackets.app.getNodeState function. Maybe you're running the wrong shell?"); } }
javascript
{ "resource": "" }
q16909
restartNode
train
function restartNode() { try { _nodeConnection.domains.base.restartNode(); } catch (e) { window.alert("Failed trying to restart Node: " + e.message); } }
javascript
{ "resource": "" }
q16910
enableDebugger
train
function enableDebugger() { try { _nodeConnection.domains.base.enableDebugger(); } catch (e) { window.alert("Failed trying to enable Node debugger: " + e.message); } }
javascript
{ "resource": "" }
q16911
formatHints
train
function formatHints(hints, query) { var hasColorSwatch = hints.some(function (token) { return token.color; }); StringMatch.basicMatchSort(hints); return hints.map(function (token) { var $hintObj = $("<span>").addClass("brackets-css-hints"); // highlight the matched portion of each hint if (token.stringRanges) { token.stringRanges.forEach(function (item) { if (item.matched) { $hintObj.append($("<span>") .text(item.text) .addClass("matched-hint")); } else { $hintObj.append(item.text); } }); } else { $hintObj.text(token.value); } if (hasColorSwatch) { $hintObj = ColorUtils.formatColorHint($hintObj, token.color); } return $hintObj; }); }
javascript
{ "resource": "" }
q16912
compareFilesWithIndices
train
function compareFilesWithIndices(index1, index2) { return entries[index1]._name.toLocaleLowerCase().localeCompare(entries[index2]._name.toLocaleLowerCase()); }
javascript
{ "resource": "" }
q16913
offsetToLineNum
train
function offsetToLineNum(textOrLines, offset) { if (Array.isArray(textOrLines)) { var lines = textOrLines, total = 0, line; for (line = 0; line < lines.length; line++) { if (total < offset) { // add 1 per line since /n were removed by splitting, but they needed to // contribute to the total offset count total += lines[line].length + 1; } else if (total === offset) { return line; } else { return line - 1; } } // if offset is NOT over the total then offset is in the last line if (offset <= total) { return line - 1; } else { return undefined; } } else { return textOrLines.substr(0, offset).split("\n").length - 1; } }
javascript
{ "resource": "" }
q16914
getSearchMatches
train
function getSearchMatches(contents, queryExpr) { if (!contents) { return; } // Quick exit if not found or if we hit the limit if (foundMaximum || contents.search(queryExpr) === -1) { return []; } var match, lineNum, line, ch, totalMatchLength, matchedLines, numMatchedLines, lastLineLength, endCh, padding, leftPadding, rightPadding, highlightOffset, highlightEndCh, lines = contents.split("\n"), matches = []; while ((match = queryExpr.exec(contents)) !== null) { lineNum = offsetToLineNum(lines, match.index); line = lines[lineNum]; ch = match.index - contents.lastIndexOf("\n", match.index) - 1; // 0-based index matchedLines = match[0].split("\n"); numMatchedLines = matchedLines.length; totalMatchLength = match[0].length; lastLineLength = matchedLines[matchedLines.length - 1].length; endCh = (numMatchedLines === 1 ? ch + totalMatchLength : lastLineLength); highlightEndCh = (numMatchedLines === 1 ? endCh : line.length); highlightOffset = 0; if (highlightEndCh <= MAX_DISPLAY_LENGTH) { // Don't store more than 200 chars per line line = line.substr(0, Math.min(MAX_DISPLAY_LENGTH, line.length)); } else if (totalMatchLength > MAX_DISPLAY_LENGTH) { // impossible to display the whole match line = line.substr(ch, ch + MAX_DISPLAY_LENGTH); highlightOffset = ch; } else { // Try to have both beginning and end of match displayed padding = MAX_DISPLAY_LENGTH - totalMatchLength; rightPadding = Math.floor(Math.min(padding / 2, line.length - highlightEndCh)); leftPadding = Math.ceil(padding - rightPadding); highlightOffset = ch - leftPadding; line = line.substring(highlightOffset, highlightEndCh + rightPadding); } matches.push({ start: {line: lineNum, ch: ch}, end: {line: lineNum + numMatchedLines - 1, ch: endCh}, highlightOffset: highlightOffset, // Note that the following offsets from the beginning of the file are *not* updated if the search // results change. These are currently only used for multi-file replacement, and we always // abort the replace (by shutting the results panel) if we detect any result changes, so we don't // need to keep them up to date. Eventually, we should either get rid of the need for these (by // doing everything in terms of line/ch offsets, though that will require re-splitting files when // doing a replace) or properly update them. startOffset: match.index, endOffset: match.index + totalMatchLength, line: line, result: match, isChecked: true }); // We have the max hits in just this 1 file. Stop searching this file. // This fixed issue #1829 where code hangs on too many hits. // Adds one over MAX_RESULTS_IN_A_FILE in order to know if the search has exceeded // or is equal to MAX_RESULTS_IN_A_FILE. Additional result removed in SearchModel if (matches.length > MAX_RESULTS_IN_A_FILE) { queryExpr.lastIndex = 0; break; } // Pathological regexps like /^/ return 0-length matches. Ensure we make progress anyway if (totalMatchLength === 0) { queryExpr.lastIndex++; } } return matches; }
javascript
{ "resource": "" }
q16915
getFilesizeInBytes
train
function getFilesizeInBytes(fileName) { try { var stats = fs.statSync(fileName); return stats.size || 0; } catch (ex) { console.log(ex); return 0; } }
javascript
{ "resource": "" }
q16916
setResults
train
function setResults(fullpath, resultInfo, maxResultsToReturn) { if (results[fullpath]) { numMatches -= results[fullpath].matches.length; delete results[fullpath]; } if (foundMaximum || !resultInfo || !resultInfo.matches || !resultInfo.matches.length) { return; } // Make sure that the optional `collapsed` property is explicitly set to either true or false, // to avoid logic issues later with comparing values. resultInfo.collapsed = collapseResults; results[fullpath] = resultInfo; numMatches += resultInfo.matches.length; evaluatedMatches += resultInfo.matches.length; maxResultsToReturn = maxResultsToReturn || MAX_RESULTS_TO_RETURN; if (numMatches >= maxResultsToReturn || evaluatedMatches > MAX_TOTAL_RESULTS) { foundMaximum = true; } }
javascript
{ "resource": "" }
q16917
doSearchInOneFile
train
function doSearchInOneFile(filepath, text, queryExpr, maxResultsToReturn) { var matches = getSearchMatches(text, queryExpr); setResults(filepath, {matches: matches}, maxResultsToReturn); }
javascript
{ "resource": "" }
q16918
doSearchInFiles
train
function doSearchInFiles(fileList, queryExpr, startFileIndex, maxResultsToReturn) { var i; if (fileList.length === 0) { console.log('no files found'); return; } else { startFileIndex = startFileIndex || 0; for (i = startFileIndex; i < fileList.length && !foundMaximum; i++) { doSearchInOneFile(fileList[i], getFileContentsForFile(fileList[i]), queryExpr, maxResultsToReturn); } lastSearchedIndex = i; } }
javascript
{ "resource": "" }
q16919
fileCrawler
train
function fileCrawler() { if (!files || (files && files.length === 0)) { setTimeout(fileCrawler, 1000); return; } var contents = ""; if (currentCrawlIndex < files.length) { contents = getFileContentsForFile(files[currentCrawlIndex]); if (contents) { cacheSize += contents.length; } currentCrawlIndex++; } if (currentCrawlIndex < files.length) { crawlComplete = false; setImmediate(fileCrawler); } else { crawlComplete = true; if (!crawlEventSent) { crawlEventSent = true; _domainManager.emitEvent("FindInFiles", "crawlComplete", [files.length, cacheSize]); } setTimeout(fileCrawler, 1000); } }
javascript
{ "resource": "" }
q16920
countNumMatches
train
function countNumMatches(contents, queryExpr) { if (!contents) { return 0; } var matches = contents.match(queryExpr); return matches ? matches.length : 0; }
javascript
{ "resource": "" }
q16921
getNumMatches
train
function getNumMatches(fileList, queryExpr) { var i, matches = 0; for (i = 0; i < fileList.length; i++) { var temp = countNumMatches(getFileContentsForFile(fileList[i]), queryExpr); if (temp) { numFiles++; matches += temp; } if (matches > MAX_TOTAL_RESULTS) { exceedsMaximum = true; break; } } return matches; }
javascript
{ "resource": "" }
q16922
doSearch
train
function doSearch(searchObject, nextPages) { savedSearchObject = searchObject; if (!files) { console.log("no file object found"); return {}; } results = {}; numMatches = 0; numFiles = 0; foundMaximum = false; if (!nextPages) { exceedsMaximum = false; evaluatedMatches = 0; } var queryObject = parseQueryInfo(searchObject.queryInfo); if (searchObject.files) { files = searchObject.files; } if (searchObject.getAllResults) { searchObject.maxResultsToReturn = MAX_TOTAL_RESULTS; } doSearchInFiles(files, queryObject.queryExpr, searchObject.startFileIndex, searchObject.maxResultsToReturn); if (crawlComplete && !nextPages) { numMatches = getNumMatches(files, queryObject.queryExpr); } var send_object = { "results": results, "foundMaximum": foundMaximum, "exceedsMaximum": exceedsMaximum }; if (!nextPages) { send_object.numMatches = numMatches; send_object.numFiles = numFiles; } if (searchObject.getAllResults) { send_object.allResultsAvailable = true; } return send_object; }
javascript
{ "resource": "" }
q16923
removeFilesFromCache
train
function removeFilesFromCache(updateObject) { var fileList = updateObject.fileList || [], filesInSearchScope = updateObject.filesInSearchScope || [], i = 0; for (i = 0; i < fileList.length; i++) { delete projectCache[fileList[i]]; } function isNotInRemovedFilesList(path) { return (filesInSearchScope.indexOf(path) === -1) ? true : false; } files = files ? files.filter(isNotInRemovedFilesList) : files; }
javascript
{ "resource": "" }
q16924
addFilesToCache
train
function addFilesToCache(updateObject) { var fileList = updateObject.fileList || [], filesInSearchScope = updateObject.filesInSearchScope || [], i = 0, changedFilesAlreadyInList = [], newFiles = []; for (i = 0; i < fileList.length; i++) { // We just add a null entry indicating the precense of the file in the project list. // The file will be later read when required. projectCache[fileList[i]] = null; } //Now update the search scope function isInChangedFileList(path) { return (filesInSearchScope.indexOf(path) !== -1) ? true : false; } changedFilesAlreadyInList = files ? files.filter(isInChangedFileList) : []; function isNotAlreadyInList(path) { return (changedFilesAlreadyInList.indexOf(path) === -1) ? true : false; } newFiles = changedFilesAlreadyInList.filter(isNotAlreadyInList); files.push.apply(files, newFiles); }
javascript
{ "resource": "" }
q16925
getNextPage
train
function getNextPage() { var send_object = { "results": {}, "numMatches": 0, "foundMaximum": foundMaximum, "exceedsMaximum": exceedsMaximum }; if (!savedSearchObject) { return send_object; } savedSearchObject.startFileIndex = lastSearchedIndex; return doSearch(savedSearchObject, true); }
javascript
{ "resource": "" }
q16926
getAllResults
train
function getAllResults() { var send_object = { "results": {}, "numMatches": 0, "foundMaximum": foundMaximum, "exceedsMaximum": exceedsMaximum }; if (!savedSearchObject) { return send_object; } savedSearchObject.startFileIndex = 0; savedSearchObject.getAllResults = true; return doSearch(savedSearchObject); }
javascript
{ "resource": "" }
q16927
train
function (e, autoDismiss) { var $primaryBtn = this.find(".primary"), buttonId = null, which = String.fromCharCode(e.which), $focusedElement = this.find(".dialog-button:focus, a:focus"); function stopEvent() { e.preventDefault(); e.stopPropagation(); } // There might be a textfield in the dialog's UI; don't want to mistake normal typing for dialog dismissal var inTextArea = (e.target.tagName === "TEXTAREA"), inTypingField = inTextArea || ($(e.target).filter(":text, :password").length > 0); if (e.which === KeyEvent.DOM_VK_TAB) { // We don't want to stopEvent() in this case since we might want the default behavior. // _handleTab takes care of stopping/preventing default as necessary. _handleTab(e, this); } else if (e.which === KeyEvent.DOM_VK_ESCAPE) { buttonId = DIALOG_BTN_CANCEL; } else if (e.which === KeyEvent.DOM_VK_RETURN && (!inTextArea || e.ctrlKey)) { // Enter key in single-line text input always dismisses; in text area, only Ctrl+Enter dismisses // Click primary stopEvent(); if (e.target.tagName === "BUTTON") { this.find(e.target).click(); } else if (e.target.tagName !== "INPUT") { // If the target element is not BUTTON or INPUT, click the primary button // We're making an exception for INPUT element because of this issue: GH-11416 $primaryBtn.click(); } } else if (e.which === KeyEvent.DOM_VK_SPACE) { if ($focusedElement.length) { // Space bar on focused button or link stopEvent(); $focusedElement.click(); } } else if (brackets.platform === "mac") { // CMD+Backspace Don't Save if (e.metaKey && (e.which === KeyEvent.DOM_VK_BACK_SPACE)) { if (_hasButton(this, DIALOG_BTN_DONTSAVE)) { buttonId = DIALOG_BTN_DONTSAVE; } // FIXME (issue #418) CMD+. Cancel swallowed by native shell } else if (e.metaKey && (e.which === KeyEvent.DOM_VK_PERIOD)) { buttonId = DIALOG_BTN_CANCEL; } } else { // if (brackets.platform === "win") { // 'N' Don't Save if (which === "N" && !inTypingField) { if (_hasButton(this, DIALOG_BTN_DONTSAVE)) { buttonId = DIALOG_BTN_DONTSAVE; } } } if (buttonId) { stopEvent(); _processButton(this, buttonId, autoDismiss); } // Stop any other global hooks from processing the event (but // allow it to continue bubbling if we haven't otherwise stopped it). return true; }
javascript
{ "resource": "" }
q16928
setDialogMaxSize
train
function setDialogMaxSize() { var maxWidth, maxHeight, $dlgs = $(".modal-inner-wrapper > .instance"); // Verify 1 or more modal dialogs are showing if ($dlgs.length > 0) { maxWidth = $("body").width(); maxHeight = $("body").height(); $dlgs.css({ "max-width": maxWidth, "max-height": maxHeight, "overflow": "auto" }); } }
javascript
{ "resource": "" }
q16929
showModalDialog
train
function showModalDialog(dlgClass, title, message, buttons, autoDismiss) { var templateVars = { dlgClass: dlgClass, title: title || "", message: message || "", buttons: buttons || [{ className: DIALOG_BTN_CLASS_PRIMARY, id: DIALOG_BTN_OK, text: Strings.OK }] }; var template = Mustache.render(DialogTemplate, templateVars); return showModalDialogUsingTemplate(template, autoDismiss); }
javascript
{ "resource": "" }
q16930
_loadSHA
train
function _loadSHA(path, callback) { var result = new $.Deferred(); if (brackets.inBrowser) { result.reject(); } else { // HEAD contains a SHA in detached-head mode; otherwise it contains a relative path // to a file in /refs which in turn contains the SHA var file = FileSystem.getFileForPath(path); FileUtils.readAsText(file).done(function (text) { if (text.indexOf("ref: ") === 0) { // e.g. "ref: refs/heads/branchname" var basePath = path.substr(0, path.lastIndexOf("/")), refRelPath = text.substr(5).trim(), branch = text.substr(16).trim(); _loadSHA(basePath + "/" + refRelPath, callback).done(function (data) { result.resolve({ branch: branch, sha: data.sha.trim() }); }).fail(function () { result.resolve({ branch: branch }); }); } else { result.resolve({ sha: text }); } }).fail(function () { result.reject(); }); } return result.promise(); }
javascript
{ "resource": "" }
q16931
_getVersionInfoUrl
train
function _getVersionInfoUrl(locale, removeCountryPartOfLocale) { locale = locale || brackets.getLocale(); if (removeCountryPartOfLocale) { locale = locale.substring(0, 2); } //AUTOUPDATE_PRERELEASE_BEGIN // The following code is needed for supporting Auto Update in prerelease, //and will be removed eventually for stable releases { if (locale) { if(locale.length > 2) { locale = locale.substring(0, 2); } switch(locale) { case "de": break; case "es": break; case "fr": break; case "ja": break; case "en": default: locale = "en"; } return brackets.config.update_info_url.replace("<locale>", locale); } } //AUTOUPDATE_PRERELEASE_END return brackets.config.update_info_url + '?locale=' + locale; }
javascript
{ "resource": "" }
q16932
_getUpdateInformation
train
function _getUpdateInformation(force, dontCache, _versionInfoUrl) { // Last time the versionInfoURL was fetched var lastInfoURLFetchTime = PreferencesManager.getViewState("lastInfoURLFetchTime"); var result = new $.Deferred(); var fetchData = false; var data; // If force is true, always fetch if (force) { fetchData = true; } // If we don't have data saved in prefs, fetch data = PreferencesManager.getViewState("updateInfo"); if (!data) { fetchData = true; } // If more than 24 hours have passed since our last fetch, fetch again if ((new Date()).getTime() > lastInfoURLFetchTime + ONE_DAY) { fetchData = true; } if (fetchData) { var lookupPromise = new $.Deferred(), localVersionInfoUrl; // If the current locale isn't "en" or "en-US", check whether we actually have a // locale-specific update notification, and fall back to "en" if not. // Note: we check for both "en" and "en-US" to watch for the general case or // country-specific English locale. The former appears default on Mac, while // the latter appears default on Windows. var locale = brackets.getLocale().toLowerCase(); if (locale !== "en" && locale !== "en-us") { localVersionInfoUrl = _versionInfoUrl || _getVersionInfoUrl(); $.ajax({ url: localVersionInfoUrl, cache: false, type: "HEAD" }).fail(function (jqXHR, status, error) { // get rid of any country information from locale and try again var tmpUrl = _getVersionInfoUrl(brackets.getLocale(), true); if (tmpUrl !== localVersionInfoUrl) { $.ajax({ url: tmpUrl, cache: false, type: "HEAD" }).fail(function (jqXHR, status, error) { localVersionInfoUrl = _getVersionInfoUrl("en"); }).done(function (jqXHR, status, error) { localVersionInfoUrl = tmpUrl; }).always(function (jqXHR, status, error) { lookupPromise.resolve(); }); } else { localVersionInfoUrl = _getVersionInfoUrl("en"); lookupPromise.resolve(); } }).done(function (jqXHR, status, error) { lookupPromise.resolve(); }); } else { localVersionInfoUrl = _versionInfoUrl || _getVersionInfoUrl("en"); lookupPromise.resolve(); } lookupPromise.done(function () { $.ajax({ url: localVersionInfoUrl, dataType: "json", cache: false }).done(function (updateInfo, textStatus, jqXHR) { if (!dontCache) { lastInfoURLFetchTime = (new Date()).getTime(); PreferencesManager.setViewState("lastInfoURLFetchTime", lastInfoURLFetchTime); PreferencesManager.setViewState("updateInfo", updateInfo); } result.resolve(updateInfo); }).fail(function (jqXHR, status, error) { // When loading data for unit tests, the error handler is // called but the responseText is valid. Try to use it here, // but *don't* save the results in prefs. if (!jqXHR.responseText) { // Text is NULL or empty string, reject(). result.reject(); return; } try { data = JSON.parse(jqXHR.responseText); result.resolve(data); } catch (e) { result.reject(); } }); }); } else { result.resolve(data); } return result.promise(); }
javascript
{ "resource": "" }
q16933
_stripOldVersionInfo
train
function _stripOldVersionInfo(versionInfo, buildNumber) { // Do a simple linear search. Since we are going in reverse-chronological order, we // should get through the search quickly. var lastIndex = 0; var len = versionInfo.length; var versionEntry; var validBuildEntries; while (lastIndex < len) { versionEntry = versionInfo[lastIndex]; if (versionEntry.buildNumber <= buildNumber) { break; } lastIndex++; } if (lastIndex > 0) { // Filter recent update entries based on applicability to current platform validBuildEntries = versionInfo.slice(0, lastIndex).filter(_checkBuildApplicability); } return validBuildEntries; }
javascript
{ "resource": "" }
q16934
_showUpdateNotificationDialog
train
function _showUpdateNotificationDialog(updates, force) { Dialogs.showModalDialogUsingTemplate(Mustache.render(UpdateDialogTemplate, Strings)) .done(function (id) { if (id === Dialogs.DIALOG_BTN_DOWNLOAD) { HealthLogger.sendAnalyticsData( eventNames.AUTOUPDATE_UPDATENOW_CLICK, "autoUpdate", "updateNotification", "updateNow", "click" ); handleUpdateProcess(updates); } else { HealthLogger.sendAnalyticsData( eventNames.AUTOUPDATE_CANCEL_CLICK, "autoUpdate", "updateNotification", "cancel", "click" ); } }); // Populate the update data var $dlg = $(".update-dialog.instance"), $updateList = $dlg.find(".update-info"), subTypeString = force ? "userAction" : "auto"; // Make the update notification icon clickable again _addedClickHandler = false; updates.Strings = Strings; $updateList.html(Mustache.render(UpdateListTemplate, updates)); HealthLogger.sendAnalyticsData( eventNames.AUTOUPDATE_UPDATE_AVAILABLE_DIALOG_BOX_RENDERED, "autoUpdate", "updateNotification", "render", subTypeString ); }
javascript
{ "resource": "" }
q16935
_onRegistryDownloaded
train
function _onRegistryDownloaded() { var availableUpdates = ExtensionManager.getAvailableUpdates(); PreferencesManager.setViewState("extensionUpdateInfo", availableUpdates); PreferencesManager.setViewState("lastExtensionRegistryCheckTime", (new Date()).getTime()); $("#toolbar-extension-manager").toggleClass("updatesAvailable", availableUpdates.length > 0); }
javascript
{ "resource": "" }
q16936
handleUpdateProcess
train
function handleUpdateProcess(updates) { var handler = _updateProcessHandler || _defaultUpdateProcessHandler; var initSuccess = handler(updates); if (_updateProcessHandler && !initSuccess) { // Give a chance to default handler in case // the auot update mechanism has failed. _defaultUpdateProcessHandler(updates); } }
javascript
{ "resource": "" }
q16937
_0xColorToHex
train
function _0xColorToHex(color, convertToStr) { var hexColor = tinycolor(color.replace("0x", "#")); hexColor._format = "0x"; if (convertToStr) { return hexColor.toString(); } return hexColor; }
javascript
{ "resource": "" }
q16938
checkSetFormat
train
function checkSetFormat(color, convertToStr) { if ((/^0x/).test(color)) { return _0xColorToHex(color, convertToStr); } if (convertToStr) { return tinycolor(color).toString(); } return tinycolor(color); }
javascript
{ "resource": "" }
q16939
ColorEditor
train
function ColorEditor($parent, color, callback, swatches) { // Create the DOM structure, filling in localized strings via Mustache this.$element = $(Mustache.render(ColorEditorTemplate, Strings)); $parent.append(this.$element); this._callback = callback; this._handleKeydown = this._handleKeydown.bind(this); this._handleOpacityKeydown = this._handleOpacityKeydown.bind(this); this._handleHslKeydown = this._handleHslKeydown.bind(this); this._handleHueKeydown = this._handleHueKeydown.bind(this); this._handleSelectionKeydown = this._handleSelectionKeydown.bind(this); this._handleOpacityDrag = this._handleOpacityDrag.bind(this); this._handleHueDrag = this._handleHueDrag.bind(this); this._handleSelectionFieldDrag = this._handleSelectionFieldDrag.bind(this); this._originalColor = color; this._color = checkSetFormat(color); this._redoColor = null; this._isUpperCase = PreferencesManager.get("uppercaseColors"); PreferencesManager.on("change", "uppercaseColors", function () { this._isUpperCase = PreferencesManager.get("uppercaseColors"); }.bind(this)); this.$colorValue = this.$element.find(".color-value"); this.$buttonList = this.$element.find("ul.button-bar"); this.$rgbaButton = this.$element.find(".rgba"); this.$hexButton = this.$element.find(".hex"); this.$hslButton = this.$element.find(".hsla"); this.$0xButton = this.$element.find(".0x"); this.$currentColor = this.$element.find(".current-color"); this.$originalColor = this.$element.find(".original-color"); this.$selection = this.$element.find(".color-selection-field"); this.$selectionBase = this.$element.find(".color-selection-field .selector-base"); this.$hueBase = this.$element.find(".hue-slider .selector-base"); this.$opacityGradient = this.$element.find(".opacity-gradient"); this.$hueSlider = this.$element.find(".hue-slider"); this.$hueSelector = this.$element.find(".hue-slider .selector-base"); this.$opacitySlider = this.$element.find(".opacity-slider"); this.$opacitySelector = this.$element.find(".opacity-slider .selector-base"); this.$swatches = this.$element.find(".swatches"); // Create quick-access color swatches this._addSwatches(swatches); // Attach event listeners to main UI elements this._addListeners(); // Initially selected color this.$originalColor.css("background-color", checkSetFormat(this._originalColor)); this._commitColor(color); }
javascript
{ "resource": "" }
q16940
_handleKeydown
train
function _handleKeydown(e) { if (e.keyCode === KeyEvent.DOM_VK_ESCAPE) { e.stopPropagation(); e.preventDefault(); self.close(); } }
javascript
{ "resource": "" }
q16941
_setMenuItemsVisible
train
function _setMenuItemsVisible() { var file = MainViewManager.getCurrentlyViewedFile(MainViewManager.ACTIVE_PANE), cMenuItems = [Commands.FILE_SAVE, Commands.FILE_RENAME, Commands.NAVIGATE_SHOW_IN_FILE_TREE, Commands.NAVIGATE_SHOW_IN_OS], // Enable menu options when no file is present in active pane enable = !file || (file.constructor.name !== "RemoteFile"); // Enable or disable commands based on whether the file is a remoteFile or not. cMenuItems.forEach(function (item) { CommandManager.get(item).setEnabled(enable); }); }
javascript
{ "resource": "" }
q16942
getUniqueIdentifierName
train
function getUniqueIdentifierName(scopes, prefix, num) { if (!scopes) { return prefix; } var props = scopes.reduce(function(props, scope) { return _.union(props, _.keys(scope.props)); }, []); if (!props) { return prefix; } num = num || "1"; var name; while (num < 100) { // limit search length name = prefix + num; if (props.indexOf(name) === -1) { break; } ++num; } return name; }
javascript
{ "resource": "" }
q16943
isStandAloneExpression
train
function isStandAloneExpression(text) { var found = ASTWalker.findNodeAt(getAST(text), 0, text.length, function (nodeType, node) { if (nodeType === "Expression") { return true; } return false; }); return found && found.node; }
javascript
{ "resource": "" }
q16944
getScopeData
train
function getScopeData(session, offset) { var path = session.path, fileInfo = { type: MessageIds.TERN_FILE_INFO_TYPE_FULL, name: path, offsetLines: 0, text: ScopeManager.filterText(session.getJavascriptText()) }; ScopeManager.postMessage({ type: MessageIds.TERN_SCOPEDATA_MSG, fileInfo: fileInfo, offset: offset }); var ternPromise = ScopeManager.addPendingRequest(fileInfo.name, offset, MessageIds.TERN_SCOPEDATA_MSG); var result = new $.Deferred(); ternPromise.done(function (response) { result.resolveWith(null, [response.scope]); }).fail(function () { result.reject(); }); return result; }
javascript
{ "resource": "" }
q16945
normalizeText
train
function normalizeText(text, start, end, removeTrailingSemiColons) { var trimmedText; // Remove leading spaces trimmedText = _.trimLeft(text); if (trimmedText.length < text.length) { start += (text.length - trimmedText.length); } text = trimmedText; // Remove trailing spaces trimmedText = _.trimRight(text); if (trimmedText.length < text.length) { end -= (text.length - trimmedText.length); } text = trimmedText; // Remove trailing semicolons if (removeTrailingSemiColons) { trimmedText = _.trimRight(text, ';'); if (trimmedText.length < text.length) { end -= (text.length - trimmedText.length); } } return { text: trimmedText, start: start, end: end }; }
javascript
{ "resource": "" }
q16946
findSurroundASTNode
train
function findSurroundASTNode(ast, expn, types) { var foundNode = ASTWalker.findNodeAround(ast, expn.start, function (nodeType, node) { if (expn.end) { return types.includes(nodeType) && node.end >= expn.end; } else { return types.includes(nodeType); } }); return foundNode && _.clone(foundNode.node); }
javascript
{ "resource": "" }
q16947
train
function (url) { var self = this; this._ws = new WebSocket(url); // One potential source of confusion: the transport sends two "types" of messages - // these are distinct from the protocol's own messages. This is because this transport // needs to send an initial "connect" message telling the Brackets side of the transport // the URL of the page that it's connecting from, distinct from the actual protocol // message traffic. Actual protocol messages are sent as a JSON payload in a message of // type "message". // // Other transports might not need to do this - for example, a transport that simply // talks to an iframe within the same process already knows what URL that iframe is // pointing to, so the only comunication that needs to happen via postMessage() is the // actual protocol message strings, and no extra wrapping is necessary. this._ws.onopen = function (event) { // Send the initial "connect" message to tell the other end what URL we're from. self._ws.send(JSON.stringify({ type: "connect", url: global.location.href })); console.log("[Brackets LiveDev] Connected to Brackets at " + url); if (self._callbacks && self._callbacks.connect) { self._callbacks.connect(); } }; this._ws.onmessage = function (event) { console.log("[Brackets LiveDev] Got message: " + event.data); if (self._callbacks && self._callbacks.message) { self._callbacks.message(event.data); } }; this._ws.onclose = function (event) { self._ws = null; if (self._callbacks && self._callbacks.close) { self._callbacks.close(); } }; // TODO: onerror }
javascript
{ "resource": "" }
q16948
train
function (msgStr) { if (this._ws) { // See comment in `connect()` above about why we wrap the message in a transport message // object. this._ws.send(JSON.stringify({ type: "message", message: msgStr })); } else { console.log("[Brackets LiveDev] Tried to send message over closed connection: " + msgStr); } }
javascript
{ "resource": "" }
q16949
handleClose
train
function handleClose(mode) { var targetIndex = MainViewManager.findInWorkingSet(MainViewManager.ACTIVE_PANE, MainViewManager.getCurrentlyViewedPath(MainViewManager.ACTIVE_PANE)), workingSetList = MainViewManager.getWorkingSet(MainViewManager.ACTIVE_PANE), start = (mode === closeBelow) ? (targetIndex + 1) : 0, end = (mode === closeAbove) ? (targetIndex) : (workingSetList.length), files = [], i; for (i = start; i < end; i++) { if ((mode === closeOthers && i !== targetIndex) || (mode !== closeOthers)) { files.push(workingSetList[i]); } } CommandManager.execute(Commands.FILE_CLOSE_LIST, {fileList: files}); }
javascript
{ "resource": "" }
q16950
initializeCommands
train
function initializeCommands() { var prefs = getPreferences(); CommandManager.register(Strings.CMD_FILE_CLOSE_BELOW, closeBelow, function () { handleClose(closeBelow); }); CommandManager.register(Strings.CMD_FILE_CLOSE_OTHERS, closeOthers, function () { handleClose(closeOthers); }); CommandManager.register(Strings.CMD_FILE_CLOSE_ABOVE, closeAbove, function () { handleClose(closeAbove); }); if (prefs.closeBelow) { workingSetListCmenu.addMenuItem(closeBelow, "", Menus.AFTER, Commands.FILE_CLOSE); } if (prefs.closeOthers) { workingSetListCmenu.addMenuItem(closeOthers, "", Menus.AFTER, Commands.FILE_CLOSE); } if (prefs.closeAbove) { workingSetListCmenu.addMenuItem(closeAbove, "", Menus.AFTER, Commands.FILE_CLOSE); } menuEntriesShown = prefs; }
javascript
{ "resource": "" }
q16951
_ensurePaneIsFocused
train
function _ensurePaneIsFocused(paneId) { var pane = MainViewManager._getPane(paneId); // Defer the focusing until other focus events have occurred. setTimeout(function () { // Focus has most likely changed: give it back to the given pane. pane.focus(); this._lastFocusedElement = pane.$el[0]; MainViewManager.setActivePaneId(paneId); }, 1); }
javascript
{ "resource": "" }
q16952
tryFocusingCurrentView
train
function tryFocusingCurrentView() { if (self._currentView) { if (self._currentView.focus) { // Views can implement a focus // method for focusing a complex // DOM like codemirror self._currentView.focus(); } else { // Otherwise, no focus method // just try and give the DOM // element focus self._currentView.$el.focus(); } } else { // no view so just focus the pane self.$el.focus(); } }
javascript
{ "resource": "" }
q16953
registerHintProvider
train
function registerHintProvider(providerInfo, languageIds, priority) { var providerObj = { provider: providerInfo, priority: priority || 0 }; if (languageIds.indexOf("all") !== -1) { // Ignore anything else in languageIds and just register for every language. This includes // the special "all" language since its key is in the hintProviders map from the beginning. var languageId; for (languageId in hintProviders) { if (hintProviders.hasOwnProperty(languageId)) { hintProviders[languageId].push(providerObj); hintProviders[languageId].sort(_providerSort); } } } else { languageIds.forEach(function (languageId) { if (!hintProviders[languageId]) { // Initialize provider list with any existing all-language providers hintProviders[languageId] = Array.prototype.concat(hintProviders.all); } hintProviders[languageId].push(providerObj); hintProviders[languageId].sort(_providerSort); }); } }
javascript
{ "resource": "" }
q16954
_endSession
train
function _endSession() { if (!hintList) { return; } hintList.close(); hintList = null; codeHintOpened = false; keyDownEditor = null; sessionProvider = null; sessionEditor = null; if (deferredHints) { deferredHints.reject(); deferredHints = null; } }
javascript
{ "resource": "" }
q16955
_inSession
train
function _inSession(editor) { if (sessionEditor) { if (sessionEditor === editor && (hintList.isOpen() || (deferredHints && deferredHints.state() === "pending"))) { return true; } else { // the editor has changed _endSession(); } } return false; }
javascript
{ "resource": "" }
q16956
_updateHintList
train
function _updateHintList(callMoveUpEvent) { callMoveUpEvent = typeof callMoveUpEvent === "undefined" ? false : callMoveUpEvent; if (deferredHints) { deferredHints.reject(); deferredHints = null; } if (callMoveUpEvent) { return hintList.callMoveUp(callMoveUpEvent); } var response = sessionProvider.getHints(lastChar); lastChar = null; if (!response) { // the provider wishes to close the session _endSession(); } else { // if the response is true, end the session and begin another if (response === true) { var previousEditor = sessionEditor; _endSession(); _beginSession(previousEditor); } else if (response.hasOwnProperty("hints")) { // a synchronous response if (hintList.isOpen()) { // the session is open hintList.update(response); } else { hintList.open(response); } } else { // response is a deferred deferredHints = response; response.done(function (hints) { // Guard against timing issues where the session ends before the // response gets a chance to execute the callback. If the session // ends first while still waiting on the response, then hintList // will get cleared up. if (!hintList) { return; } if (hintList.isOpen()) { // the session is open hintList.update(hints); } else { hintList.open(hints); } }); } } }
javascript
{ "resource": "" }
q16957
_handleKeydownEvent
train
function _handleKeydownEvent(jqEvent, editor, event) { keyDownEditor = editor; if (!(event.ctrlKey || event.altKey || event.metaKey) && (event.keyCode === KeyEvent.DOM_VK_ENTER || event.keyCode === KeyEvent.DOM_VK_RETURN || event.keyCode === KeyEvent.DOM_VK_TAB)) { lastChar = String.fromCharCode(event.keyCode); } }
javascript
{ "resource": "" }
q16958
_startNewSession
train
function _startNewSession(editor) { if (isOpen()) { return; } if (!editor) { editor = EditorManager.getFocusedEditor(); } if (editor) { lastChar = null; if (_inSession(editor)) { _endSession(); } // Begin a new explicit session _beginSession(editor); } }
javascript
{ "resource": "" }
q16959
_doJumpToDef
train
function _doJumpToDef() { var request = null, result = new $.Deferred(), jumpToDefProvider = null, editor = EditorManager.getActiveEditor(); if (editor) { // Find a suitable provider, if any var language = editor.getLanguageForSelection(), enabledProviders = _providerRegistrationHandler.getProvidersForLanguageId(language.getId()); enabledProviders.some(function (item, index) { if (item.provider.canJumpToDef(editor)) { jumpToDefProvider = item.provider; return true; } }); if (jumpToDefProvider) { request = jumpToDefProvider.doJumpToDef(editor); if (request) { request.done(function () { result.resolve(); }).fail(function () { result.reject(); }); } else { result.reject(); } } else { result.reject(); } } else { result.reject(); } return result.promise(); }
javascript
{ "resource": "" }
q16960
positionHint
train
function positionHint(xpos, ypos, ybot) { var hintWidth = $hintContainer.width(), hintHeight = $hintContainer.height(), top = ypos - hintHeight - POINTER_TOP_OFFSET, left = xpos, $editorHolder = $("#editor-holder"), editorLeft; if ($editorHolder.offset() === undefined) { // this happens in jasmine tests that run // without a windowed document. return; } editorLeft = $editorHolder.offset().left; left = Math.max(left, editorLeft); left = Math.min(left, editorLeft + $editorHolder.width() - hintWidth); if (top < 0) { $hintContainer.removeClass("preview-bubble-above"); $hintContainer.addClass("preview-bubble-below"); top = ybot + POSITION_BELOW_OFFSET; $hintContainer.offset({ left: left, top: top }); } else { $hintContainer.removeClass("preview-bubble-below"); $hintContainer.addClass("preview-bubble-above"); $hintContainer.offset({ left: left, top: top - POINTER_TOP_OFFSET }); } }
javascript
{ "resource": "" }
q16961
formatHint
train
function formatHint(hints) { $hintContent.empty(); $hintContent.addClass("brackets-hints"); function appendSeparators(separators) { $hintContent.append(separators); } function appendParameter(param, documentation, index) { if (hints.currentIndex === index) { $hintContent.append($("<span>") .append(_.escape(param)) .addClass("current-parameter")); } else { $hintContent.append($("<span>") .append(_.escape(param)) .addClass("parameter")); } } if (hints.parameters.length > 0) { _formatParameterHint(hints.parameters, appendSeparators, appendParameter); } else { $hintContent.append(_.escape(Strings.NO_ARGUMENTS)); } }
javascript
{ "resource": "" }
q16962
dismissHint
train
function dismissHint(editor) { if (hintState.visible) { $hintContainer.hide(); $hintContent.empty(); hintState = {}; if (editor) { editor.off("cursorActivity.ParameterHinting", handleCursorActivity); sessionEditor = null; } else if (sessionEditor) { sessionEditor.off("cursorActivity.ParameterHinting", handleCursorActivity); sessionEditor = null; } } }
javascript
{ "resource": "" }
q16963
popUpHint
train
function popUpHint(editor, explicit, onCursorActivity) { var request = null; var $deferredPopUp = $.Deferred(); var sessionProvider = null; dismissHint(editor); // Find a suitable provider, if any var language = editor.getLanguageForSelection(), enabledProviders = _providerRegistrationHandler.getProvidersForLanguageId(language.getId()); enabledProviders.some(function (item, index) { if (item.provider.hasParameterHints(editor, lastChar)) { sessionProvider = item.provider; return true; } }); if (sessionProvider) { request = sessionProvider.getParameterHints(explicit, onCursorActivity); } if (request) { request.done(function (parameterHint) { var cm = editor._codeMirror, pos = parameterHint.functionCallPos || editor.getCursorPos(); pos = cm.charCoords(pos); formatHint(parameterHint); $hintContainer.show(); positionHint(pos.left, pos.top, pos.bottom); hintState.visible = true; sessionEditor = editor; editor.on("cursorActivity.ParameterHinting", handleCursorActivity); $deferredPopUp.resolveWith(null); }).fail(function () { hintState = {}; }); } return $deferredPopUp; }
javascript
{ "resource": "" }
q16964
installListeners
train
function installListeners(editor) { editor.on("keydown.ParameterHinting", function (event, editor, domEvent) { if (domEvent.keyCode === KeyEvent.DOM_VK_ESCAPE) { dismissHint(editor); } }).on("scroll.ParameterHinting", function () { dismissHint(editor); }) .on("editorChange.ParameterHinting", _handleChange) .on("keypress.ParameterHinting", _handleKeypressEvent); }
javascript
{ "resource": "" }
q16965
readAsText
train
function readAsText(file) { var result = new $.Deferred(); // Measure performance var perfTimerName = PerfUtils.markStart("readAsText:\t" + file.fullPath); result.always(function () { PerfUtils.addMeasurement(perfTimerName); }); // Read file file.read(function (err, data, encoding, stat) { if (!err) { result.resolve(data, stat.mtime); } else { result.reject(err); } }); return result.promise(); }
javascript
{ "resource": "" }
q16966
writeText
train
function writeText(file, text, allowBlindWrite) { var result = new $.Deferred(), options = {}; if (allowBlindWrite) { options.blind = true; } file.write(text, options, function (err) { if (!err) { result.resolve(); } else { result.reject(err); } }); return result.promise(); }
javascript
{ "resource": "" }
q16967
sniffLineEndings
train
function sniffLineEndings(text) { var subset = text.substr(0, 1000); // (length is clipped to text.length) var hasCRLF = /\r\n/.test(subset); var hasLF = /[^\r]\n/.test(subset); if ((hasCRLF && hasLF) || (!hasCRLF && !hasLF)) { return null; } else { return hasCRLF ? LINE_ENDINGS_CRLF : LINE_ENDINGS_LF; } }
javascript
{ "resource": "" }
q16968
translateLineEndings
train
function translateLineEndings(text, lineEndings) { if (lineEndings !== LINE_ENDINGS_CRLF && lineEndings !== LINE_ENDINGS_LF) { lineEndings = getPlatformLineEndings(); } var eolStr = (lineEndings === LINE_ENDINGS_CRLF ? "\r\n" : "\n"); var findAnyEol = /\r\n|\r|\n/g; return text.replace(findAnyEol, eolStr); }
javascript
{ "resource": "" }
q16969
makeDialogFileList
train
function makeDialogFileList(paths) { var result = "<ul class='dialog-list'>"; paths.forEach(function (path) { result += "<li><span class='dialog-filename'>"; result += StringUtils.breakableUrl(path); result += "</span></li>"; }); result += "</ul>"; return result; }
javascript
{ "resource": "" }
q16970
getBaseName
train
function getBaseName(fullPath) { var lastSlash = fullPath.lastIndexOf("/"); if (lastSlash === fullPath.length - 1) { // directory: exclude trailing "/" too return fullPath.slice(fullPath.lastIndexOf("/", fullPath.length - 2) + 1, -1); } else { return fullPath.slice(lastSlash + 1); } }
javascript
{ "resource": "" }
q16971
getNativeModuleDirectoryPath
train
function getNativeModuleDirectoryPath(module) { var path; if (module && module.uri) { path = decodeURI(module.uri); // Remove module name and trailing slash from path. path = path.substr(0, path.lastIndexOf("/")); } return path; }
javascript
{ "resource": "" }
q16972
getFilenameWithoutExtension
train
function getFilenameWithoutExtension(filename) { var index = filename.lastIndexOf("."); return index === -1 ? filename : filename.slice(0, index); }
javascript
{ "resource": "" }
q16973
DropdownEventHandler
train
function DropdownEventHandler($list, selectionCallback, closeCallback) { this.$list = $list; this.$items = $list.find("li"); this.selectionCallback = selectionCallback; this.closeCallback = closeCallback; this.scrolling = false; /** * @private * The selected position in the list; otherwise -1. * @type {number} */ this._selectedIndex = -1; }
javascript
{ "resource": "" }
q16974
_keydownHook
train
function _keydownHook(event) { var keyCode; // (page) up, (page) down, enter and tab key are handled by the list if (event.type === "keydown") { keyCode = event.keyCode; if (keyCode === KeyEvent.DOM_VK_TAB) { self.close(); } else if (keyCode === KeyEvent.DOM_VK_UP) { // Move up one, wrapping at edges (if nothing selected, select the last item) self._tryToSelect(self._selectedIndex === -1 ? -1 : self._selectedIndex - 1, -1); } else if (keyCode === KeyEvent.DOM_VK_DOWN) { // Move down one, wrapping at edges (if nothing selected, select the first item) self._tryToSelect(self._selectedIndex === -1 ? 0 : self._selectedIndex + 1, +1); } else if (keyCode === KeyEvent.DOM_VK_PAGE_UP) { // Move up roughly one 'page', stopping at edges (not wrapping) (if nothing selected, selects the first item) self._tryToSelect((self._selectedIndex || 0) - self._itemsPerPage(), -1, true); } else if (keyCode === KeyEvent.DOM_VK_PAGE_DOWN) { // Move down roughly one 'page', stopping at edges (not wrapping) (if nothing selected, selects the item one page down from the top) self._tryToSelect((self._selectedIndex || 0) + self._itemsPerPage(), +1, true); } else if (keyCode === KeyEvent.DOM_VK_HOME) { self._tryToSelect(0, +1); } else if (keyCode === KeyEvent.DOM_VK_END) { self._tryToSelect(self.$items.length - 1, -1); } else if (self._selectedIndex !== -1 && (keyCode === KeyEvent.DOM_VK_RETURN)) { // Trigger a click handler to commmit the selected item self._selectionHandler(); } else { // Let the event bubble. return false; } event.stopImmediatePropagation(); event.preventDefault(); return true; } // If we didn't handle it, let other global keydown hooks handle it. return false; }
javascript
{ "resource": "" }
q16975
_createTagInfo
train
function _createTagInfo(token, tokenType, offset, exclusionList, tagName, attrName, shouldReplace) { return { token: token || null, tokenType: tokenType || null, offset: offset || 0, exclusionList: exclusionList || [], tagName: tagName || "", attrName: attrName || "", shouldReplace: shouldReplace || false }; }
javascript
{ "resource": "" }
q16976
_getTagAttributes
train
function _getTagAttributes(editor, constPos) { var pos, ctx, ctxPrev, ctxNext, ctxTemp, tagName, exclusionList = [], shouldReplace; pos = $.extend({}, constPos); ctx = TokenUtils.getInitialContext(editor._codeMirror, pos); // Stop if the cursor is before = or an attribute value. ctxTemp = $.extend(true, {}, ctx); if (ctxTemp.token.type === null && regexWhitespace.test(ctxTemp.token.string)) { if (TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctxTemp)) { if ((ctxTemp.token.type === null && ctxTemp.token.string === "=") || ctxTemp.token.type === "string") { return null; } TokenUtils.moveSkippingWhitespace(TokenUtils.movePrevToken, ctxTemp); } } // Incase an attribute is followed by an equal sign, shouldReplace will be used // to prevent from appending ="" again. if (ctxTemp.token.type === "attribute") { if (TokenUtils.moveSkippingWhitespace(TokenUtils.moveNextToken, ctxTemp)) { if (ctxTemp.token.type === null && ctxTemp.token.string === "=") { shouldReplace = true; } } } // Look-Back and get the attributes and tag name. pos = $.extend({}, constPos); ctxPrev = TokenUtils.getInitialContext(editor._codeMirror, pos); while (TokenUtils.movePrevToken(ctxPrev)) { if (ctxPrev.token.type && ctxPrev.token.type.indexOf("tag bracket") >= 0) { // Disallow hints in closed tag and inside tag content if (ctxPrev.token.string === "</" || ctxPrev.token.string.indexOf(">") !== -1) { return null; } } // Get attributes. if (ctxPrev.token.type === "attribute") { exclusionList.push(ctxPrev.token.string); } // Get tag. if (ctxPrev.token.type === "tag") { tagName = ctxPrev.token.string; if (TokenUtils.movePrevToken(ctxPrev)) { if (ctxPrev.token.type === "tag bracket" && ctxPrev.token.string === "<") { break; } return null; } } } // Look-Ahead and find rest of the attributes. pos = $.extend({}, constPos); ctxNext = TokenUtils.getInitialContext(editor._codeMirror, pos); while (TokenUtils.moveNextToken(ctxNext)) { if (ctxNext.token.type === "string" && ctxNext.token.string === "\"") { return null; } // Stop on closing bracket of its own tag or opening bracket of next tag. if (ctxNext.token.type === "tag bracket" && (ctxNext.token.string.indexOf(">") >= 0 || ctxNext.token.string === "<")) { break; } if (ctxNext.token.type === "attribute" && exclusionList.indexOf(ctxNext.token.string) === -1) { exclusionList.push(ctxNext.token.string); } } return { tagName: tagName, exclusionList: exclusionList, shouldReplace: shouldReplace }; }
javascript
{ "resource": "" }
q16977
_getTagAttributeValue
train
function _getTagAttributeValue(editor, pos) { var ctx, tagName, attrName, exclusionList = [], offset, textBefore, textAfter; ctx = TokenUtils.getInitialContext(editor._codeMirror, pos); offset = TokenUtils.offsetInToken(ctx); // To support multiple options on the same attribute, we have // to break the value, these values will not be available then. if (ctx.token.type === "string" && /\s+/.test(ctx.token.string)) { textBefore = ctx.token.string.substr(1, offset); textAfter = ctx.token.string.substr(offset); // Remove quote from end of the string. if (/^['"]$/.test(ctx.token.string.substr(-1, 1))) { textAfter = textAfter.substr(0, textAfter.length - 1); } // Split the text before and after the offset, skipping the current query. exclusionList = exclusionList.concat(textBefore.split(/\s+/).slice(0, -1)); exclusionList = exclusionList.concat(textAfter.split(/\s+/)); // Filter through the list removing empty strings. exclusionList = exclusionList.filter(function (value) { if (value.length > 0) { return true; } }); } // Look-back and find tag and attributes. while (TokenUtils.movePrevToken(ctx)) { if (ctx.token.type === "tag bracket") { // Disallow hints in closing tags. if (ctx.token.string === "</") { return null; } // Stop when closing bracket of another tag or opening bracket of its own in encountered. if (ctx.token.string.indexOf(">") >= 0 || ctx.token.string === "<") { break; } } // Get the first previous attribute. if (ctx.token.type === "attribute" && !attrName) { attrName = ctx.token.string; } // Stop if we get a bracket after tag. if (ctx.token.type === "tag") { tagName = ctx.token.string; if (TokenUtils.movePrevToken(ctx)) { if (ctx.token.type === "tag bracket" && ctx.token.string === "<") { break; } return null; } } } return { tagName: tagName, attrName: attrName, exclusionList: exclusionList }; }
javascript
{ "resource": "" }
q16978
getTagInfo
train
function getTagInfo(editor, pos) { var ctx, offset, tagAttrs, tagAttrValue; ctx = TokenUtils.getInitialContext(editor._codeMirror, pos); offset = TokenUtils.offsetInToken(ctx); if (ctx.token && ctx.token.type === "tag bracket" && ctx.token.string === "<") { // Returns tagInfo when an angle bracket is created. return _createTagInfo(ctx.token, TOKEN_TAG); } else if (ctx.token && ctx.token.type === "tag") { // Return tagInfo when a tag is created. if (TokenUtils.movePrevToken(ctx)) { if (ctx.token.type === "tag bracket" && ctx.token.string === "<") { TokenUtils.moveNextToken(ctx); return _createTagInfo(ctx.token, TOKEN_TAG, offset); } } } else if (ctx.token && (ctx.token.type === "attribute" || (ctx.token.type === null && regexWhitespace.test(ctx.token.string)))) { // Return tagInfo when an attribute is created. tagAttrs = _getTagAttributes(editor, pos); if (tagAttrs && tagAttrs.tagName) { return _createTagInfo(ctx.token, TOKEN_ATTR, offset, tagAttrs.exclusionList, tagAttrs.tagName, null, tagAttrs.shouldReplace); } } else if (ctx.token && ((ctx.token.type === null && ctx.token.string === "=") || (ctx.token.type === "string" && /^['"]$/.test(ctx.token.string.charAt(0))))) { // Return tag info when an attribute value is created. // Allow no hints if the cursor is outside the value. if (ctx.token.type === "string" && /^['"]$/.test(ctx.token.string.substr(-1, 1)) && ctx.token.string.length !== 1 && ctx.token.end === pos.ch) { return _createTagInfo(); } tagAttrValue = _getTagAttributeValue(editor, pos); if (tagAttrValue && tagAttrValue.tagName && tagAttrValue.attrName) { return _createTagInfo(ctx.token, TOKEN_VALUE, offset, tagAttrValue.exclusionList, tagAttrValue.tagName, tagAttrValue.attrName); } } return _createTagInfo(); }
javascript
{ "resource": "" }
q16979
getValueQuery
train
function getValueQuery(tagInfo) { var query; if (tagInfo.token.string === "=") { return ""; } // Remove quotation marks in query. query = tagInfo.token.string.substr(1, tagInfo.offset - 1); // Get the last option to use as a query to support multiple options. return query.split(/\s+/).slice(-1)[0]; }
javascript
{ "resource": "" }
q16980
isAbsolutePathOrUrl
train
function isAbsolutePathOrUrl(pathOrUrl) { return brackets.platform === "win" ? PathUtils.isAbsoluteUrl(pathOrUrl) : FileSystem.isAbsolutePath(pathOrUrl); }
javascript
{ "resource": "" }
q16981
parseLessCode
train
function parseLessCode(code, url) { var result = new $.Deferred(), options; if (url) { var dir = url.slice(0, url.lastIndexOf("/") + 1); options = { filename: url, rootpath: dir }; if (isAbsolutePathOrUrl(url)) { options.currentFileInfo = { currentDirectory: dir, entryPath: dir, filename: url, rootFilename: url, rootpath: dir }; } } less.render(code, options, function onParse(err, tree) { if (err) { result.reject(err); } else { result.resolve(tree.css); } }); return result.promise(); }
javascript
{ "resource": "" }
q16982
getModulePath
train
function getModulePath(module, path) { var modulePath = module.uri.substr(0, module.uri.lastIndexOf("/") + 1); if (path) { modulePath += path; } return modulePath; }
javascript
{ "resource": "" }
q16983
getModuleUrl
train
function getModuleUrl(module, path) { var url = encodeURI(getModulePath(module, path)); // On Windows, $.get() fails if the url is a full pathname. To work around this, // prepend "file:///". On the Mac, $.get() works fine if the url is a full pathname, // but *doesn't* work if it is prepended with "file://". Go figure. // However, the prefix "file://localhost" does work. if (brackets.platform === "win" && url.indexOf(":") !== -1) { url = "file:///" + url; } return url; }
javascript
{ "resource": "" }
q16984
loadFile
train
function loadFile(module, path) { var url = PathUtils.isAbsoluteUrl(path) ? path : getModuleUrl(module, path), promise = $.get(url); return promise; }
javascript
{ "resource": "" }
q16985
loadMetadata
train
function loadMetadata(folder) { var packageJSONFile = FileSystem.getFileForPath(folder + "/package.json"), disabledFile = FileSystem.getFileForPath(folder + "/.disabled"), baseName = FileUtils.getBaseName(folder), result = new $.Deferred(), jsonPromise = new $.Deferred(), disabledPromise = new $.Deferred(), json, disabled; FileUtils.readAsText(packageJSONFile) .then(function (text) { try { json = JSON.parse(text); jsonPromise.resolve(); } catch (e) { jsonPromise.reject(); } }) .fail(jsonPromise.reject); disabledFile.exists(function (err, exists) { if (err) { disabled = false; } else { disabled = exists; } var defaultDisabled = PreferencesManager.get("extensions.default.disabled"); if (Array.isArray(defaultDisabled) && defaultDisabled.indexOf(folder) !== -1) { console.warn("Default extension has been disabled on startup: " + baseName); disabled = true; } disabledPromise.resolve(); }); Async.waitForAll([jsonPromise, disabledPromise]) .always(function () { if (!json) { // if we don't have any metadata for the extension // we should still create an empty one, so we can attach // disabled property on it in case it's disabled json = { name: baseName }; } json.disabled = disabled; result.resolve(json); }); return result.promise(); }
javascript
{ "resource": "" }
q16986
_markTags
train
function _markTags(cm, node) { node.children.forEach(function (childNode) { if (childNode.isElement()) { _markTags(cm, childNode); } }); var mark = cm.markText(node.startPos, node.endPos); mark.tagID = node.tagID; }
javascript
{ "resource": "" }
q16987
_markTextFromDOM
train
function _markTextFromDOM(editor, dom) { var cm = editor._codeMirror; // Remove existing marks var marks = cm.getAllMarks(); cm.operation(function () { marks.forEach(function (mark) { if (mark.hasOwnProperty("tagID")) { mark.clear(); } }); }); // Mark _markTags(cm, dom); }
javascript
{ "resource": "" }
q16988
scanDocument
train
function scanDocument(doc) { if (!_cachedValues.hasOwnProperty(doc.file.fullPath)) { // TODO: this doesn't seem to be correct any more. The DOM should never be "dirty" (i.e., out of sync // with the editor) unless the doc is invalid. // $(doc).on("change.htmlInstrumentation", function () { // if (_cachedValues[doc.file.fullPath]) { // _cachedValues[doc.file.fullPath].dirty = true; // } // }); // Assign to cache, but don't set a value yet _cachedValues[doc.file.fullPath] = null; } var cachedValue = _cachedValues[doc.file.fullPath]; // TODO: No longer look at doc or cached value "dirty" settings, because even if the doc is dirty, the dom // should generally be up to date unless the HTML is invalid. (However, the node offsets will be dirty of // the dom was incrementally updated - we should note that somewhere.) if (cachedValue && !cachedValue.invalid && cachedValue.timestamp === doc.diskTimestamp) { return cachedValue.dom; } var text = doc.getText(), dom = HTMLSimpleDOM.build(text); if (dom) { // Cache results _cachedValues[doc.file.fullPath] = { timestamp: doc.diskTimestamp, dom: dom, dirty: false }; // Note that this was a full build, so we know that we can trust the node start/end offsets. dom.fullBuild = true; } return dom; }
javascript
{ "resource": "" }
q16989
walk
train
function walk(node) { if (node.tag) { var attrText = " data-brackets-id='" + node.tagID + "'"; // If the dom was fully rebuilt, use its offsets. Otherwise, use the marks in the // associated editor, since they'll be more up to date. var startOffset; if (dom.fullBuild) { startOffset = node.start; } else { var mark = markCache[node.tagID]; if (mark) { startOffset = editor._codeMirror.indexFromPos(mark.range.from); } else { console.warn("generateInstrumentedHTML(): couldn't find existing mark for tagID " + node.tagID); startOffset = node.start; } } // Insert the attribute as the first attribute in the tag. var insertIndex = startOffset + node.tag.length + 1; gen += orig.substr(lastIndex, insertIndex - lastIndex) + attrText; lastIndex = insertIndex; // If we have a script to inject and this is the head tag, inject it immediately // after the open tag. if (remoteScript && !remoteScriptInserted && node.tag === "head") { insertIndex = node.openEnd; gen += orig.substr(lastIndex, insertIndex - lastIndex) + remoteScript; lastIndex = insertIndex; remoteScriptInserted = true; } } if (node.isElement()) { node.children.forEach(walk); } }
javascript
{ "resource": "" }
q16990
setCachedHintContext
train
function setCachedHintContext(hints, cursor, type, token) { cachedHints = hints; cachedCursor = cursor; cachedType = type; cachedToken = token; }
javascript
{ "resource": "" }
q16991
getSessionHints
train
function getSessionHints(query, cursor, type, token, $deferredHints) { var hintResults = session.getHints(query, getStringMatcher()); if (hintResults.needGuesses) { var guessesResponse = ScopeManager.requestGuesses(session, session.editor.document); if (!$deferredHints) { $deferredHints = $.Deferred(); } guessesResponse.done(function () { if (hintsArePending($deferredHints)) { hintResults = session.getHints(query, getStringMatcher()); setCachedHintContext(hintResults.hints, cursor, type, token); var hintResponse = getHintResponse(cachedHints, query, type); $deferredHints.resolveWith(null, [hintResponse]); } }).fail(function () { if (hintsArePending($deferredHints)) { $deferredHints.reject(); } }); return $deferredHints; } else if (hintsArePending($deferredHints)) { setCachedHintContext(hintResults.hints, cursor, type, token); var hintResponse = getHintResponse(cachedHints, query, type); $deferredHints.resolveWith(null, [hintResponse]); return null; } else { setCachedHintContext(hintResults.hints, cursor, type, token); return getHintResponse(cachedHints, query, type); } }
javascript
{ "resource": "" }
q16992
requestJumpToDef
train
function requestJumpToDef(session, offset) { var response = ScopeManager.requestJumptoDef(session, session.editor.document, offset); if (response.hasOwnProperty("promise")) { response.promise.done(handleJumpResponse).fail(function () { result.reject(); }); } }
javascript
{ "resource": "" }
q16993
setJumpSelection
train
function setJumpSelection(start, end, isFunction) { /** * helper function to decide if the tokens on the RHS of an assignment * look like an identifier, or member expr. */ function validIdOrProp(token) { if (!token) { return false; } if (token.string === ".") { return true; } var type = token.type; if (type === "variable-2" || type === "variable" || type === "property") { return true; } return false; } var madeNewRequest = false; if (isFunction) { // When jumping to function defs, follow the chain back // to get to the original function def var cursor = {line: end.line, ch: end.ch}, prev = session._getPreviousToken(cursor), next, offset; // see if the selection is preceded by a '.', indicating we're in a member expr if (prev.string === ".") { cursor = {line: end.line, ch: end.ch}; next = session.getNextToken(cursor, true); // check if the next token indicates an assignment if (next && next.string === "=") { next = session.getNextToken(cursor, true); // find the last token of the identifier, or member expr while (validIdOrProp(next)) { offset = session.getOffsetFromCursor({line: cursor.line, ch: next.end}); next = session.getNextToken(cursor, false); } if (offset) { // trigger another jump to def based on the offset of the RHS requestJumpToDef(session, offset); madeNewRequest = true; } } } } // We didn't make a new jump-to-def request, so we can resolve the promise // and set the selection if (!madeNewRequest) { // set the selection session.editor.setSelection(start, end, true); result.resolve(true); } }
javascript
{ "resource": "" }
q16994
validIdOrProp
train
function validIdOrProp(token) { if (!token) { return false; } if (token.string === ".") { return true; } var type = token.type; if (type === "variable-2" || type === "variable" || type === "property") { return true; } return false; }
javascript
{ "resource": "" }
q16995
_urlWithoutQueryString
train
function _urlWithoutQueryString(url) { var index = url.search(/[#\?]/); if (index >= 0) { url = url.substr(0, index); } return url; }
javascript
{ "resource": "" }
q16996
_makeHTMLTarget
train
function _makeHTMLTarget(targets, node) { if (node.location) { var url = DOMAgent.url; var location = node.location; if (node.canHaveChildren()) { location += node.length; } url += ":" + location; var name = "&lt;" + node.name + "&gt;"; var file = _fileFromURL(url); targets.push({"type": "html", "url": url, "name": name, "file": file}); } }
javascript
{ "resource": "" }
q16997
_makeCSSTarget
train
function _makeCSSTarget(targets, rule) { if (rule.sourceURL) { var url = rule.sourceURL; url += ":" + rule.style.range.start; var name = rule.selectorList.text; var file = _fileFromURL(url); targets.push({"type": "css", "url": url, "name": name, "file": file}); } }
javascript
{ "resource": "" }
q16998
_makeJSTarget
train
function _makeJSTarget(targets, callFrame) { var script = ScriptAgent.scriptWithId(callFrame.location.scriptId); if (script && script.url) { var url = script.url; url += ":" + callFrame.location.lineNumber + "," + callFrame.location.columnNumber; var name = callFrame.functionName; if (name === "") { name = "anonymous function"; } var file = _fileFromURL(url); targets.push({"type": "js", "url": url, "name": name, "file": file}); } }
javascript
{ "resource": "" }
q16999
_onRemoteShowGoto
train
function _onRemoteShowGoto(event, res) { // res = {nodeId, name, value} var node = DOMAgent.nodeWithId(res.nodeId); // get all css rules that apply to the given node Inspector.CSS.getMatchedStylesForNode(node.nodeId, function onMatchedStyles(res) { var i, targets = []; _makeHTMLTarget(targets, node); for (i in node.trace) { _makeJSTarget(targets, node.trace[i]); } for (i in node.events) { var trace = node.events[i]; _makeJSTarget(targets, trace.callFrames[0]); } for (i in res.matchedCSSRules.reverse()) { _makeCSSTarget(targets, res.matchedCSSRules[i].rule); } RemoteAgent.call("showGoto", targets); }); }
javascript
{ "resource": "" }