Unnamed: 0
int64
0
305k
body
stringlengths
7
52.9k
name
stringlengths
1
185
14,700
int (@NotNull Caret caret) { return caret.hasSelection() ? caret.getSelectionEnd() : caret.getOffset(); }
calcSelectionEnd
14,701
int (@NotNull Editor editor, int startFrom) { final CharSequence text = editor.getDocument().getCharsSequence(); int idEnd = startFrom; int length = text.length(); while (idEnd < length) { char ch = text.charAt(idEnd); if (Character.isJavaIdentifierPart(ch) || ch == '.' || ch == '-' || ch == '@') idEnd++; else if (idEnd < length - 1 && ch == '\\' && ShStringUtil.ORIGINS_SET.contains(text.charAt(idEnd + 1))) idEnd += 2; else return idEnd; } return idEnd; }
calcDefaultIdentifierEnd
14,702
void (@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) { String originalText = getTextWithEnvVarReplacement(parameters); if (originalText != null) { int lastSlashIndex = originalText.lastIndexOf("/"); if (lastSlashIndex >= 0) { String afterSlash = originalText.substring(lastSlashIndex + 1); String beforeSlash = originalText.substring(0, lastSlashIndex); boolean isRoot = beforeSlash.isEmpty(); if (beforeSlash.startsWith("/") || isRoot || beforeSlash.startsWith("~")) { // absolute paths String path = beforeSlash.equals("~") ? "~/" : beforeSlash; String maybeFilePath = FileUtil.expandUserHome(unquote(path)); File dir = isRoot ? new File("/") : new File(maybeFilePath); if (dir.exists() && dir.isDirectory()) { File[] files = dir.listFiles(); if (files != null) { List<LookupElement> collect = ContainerUtil.map(files, ShFilePathCompletionContributor::createFileLookupElement); String prefix = afterSlash.endsWith("\\") ? afterSlash.substring(0, afterSlash.length() - 1) : afterSlash; result.withPrefixMatcher(prefix).caseInsensitive().addAllElements(collect); } } result.stopHere(); } } } }
addCompletions
14,703
LookupElement (@NotNull File file) { String name = file.getName(); boolean isDirectory = file.isDirectory(); return LookupElementBuilder.create(file, quote(name)) .withIcon(isDirectory ? PlatformIcons.FOLDER_ICON : null) .withInsertHandler(FILE_INSERT_HANDLER); }
createFileLookupElement
14,704
String (@NotNull CompletionParameters parameters) { PsiElement original = parameters.getOriginalPosition(); if (original == null) return null; int textLength = parameters.getOffset() - parameters.getPosition().getTextRange().getStartOffset(); String originalText = original.getText().substring(0, textLength); int offset = original.getTextOffset() - 1; if (offset < 0) return originalText; PsiElement var = getNearestVarIfExist(parameters.getOriginalFile(), offset); if (var == null) return originalText; String variable = variableText(var); String envPath = EnvironmentUtil.getValue(variable); return envPath != null ? envPath + originalText : originalText; }
getTextWithEnvVarReplacement
14,705
PsiElement (@NotNull PsiFile file, int offset) { PsiElement e = file.findElementAt(offset); if (!(e instanceof LeafPsiElement leaf)) return null; if (leaf.getElementType() == ShTypes.VAR) return leaf; if (isStringOfVar(leaf)) return leaf.getPrevSibling(); return null; }
getNearestVarIfExist
14,706
boolean (@NotNull LeafPsiElement e) { if (e.getElementType() != ShTypes.CLOSE_QUOTE) return false; PsiElement str = e.getParent(); if (!(str instanceof ShString)) return false; ASTNode[] children = str.getNode().getChildren(null); return children.length == 3 && children[0].getElementType() == ShTypes.OPEN_QUOTE && children[1].getElementType() == ShTypes.VARIABLE && children[2].getElementType() == ShTypes.CLOSE_QUOTE; }
isStringOfVar
14,707
String (PsiElement e) { String variable = e.getText(); int index = variable.indexOf("$"); if (index + 1 <= 0) return variable; return variable.substring(index + 1); }
variableText
14,708
void (@NotNull CompletionParameters parameters, @NotNull ProcessingContext context, @NotNull CompletionResultSet result) { if (endsWithDot(parameters)) return; Collection<String> kws = new SmartList<>(); PsiElement original = parameters.getOriginalPosition(); if (original == null || !original.getText().contains("/")) { result.addAllElements(ContainerUtil.map(BUILTIN, s -> PrioritizedLookupElement.withPriority(LookupElementBuilder .create(s) .withIcon( IconManager.getInstance().getPlatformIcon(com.intellij.ui.PlatformIcons.Function)) .withInsertHandler( AddSpaceInsertHandler.INSTANCE), BUILTIN_PRIORITY))); kws = suggestKeywords(parameters.getPosition()); for (String keywords : kws) { result.addElement(LookupElementBuilder.create(keywords).bold().withInsertHandler(AddSpaceInsertHandler.INSTANCE)); } } kws.addAll(BUILTIN); Arrays.stream(ShTokenTypes.HUMAN_READABLE_KEYWORDS.getTypes()).map(IElementType::toString).forEach(kws::add); String prefix = CompletionUtil.findJavaIdentifierPrefix(parameters); if (prefix.isEmpty() && parameters.isAutoPopup()) { return; } CompletionResultSet resultSetWithPrefix = result.withPrefixMatcher(prefix); WordCompletionContributor.addWordCompletionVariants(resultSetWithPrefix, parameters, new HashSet<>(kws)); }
addCompletions
14,709
Collection<String> (PsiElement position) { TextRange posRange = position.getTextRange(); ShFile posFile = (ShFile) position.getContainingFile(); ShCommandsList parent = PsiTreeUtil.getTopmostParentOfType(position, ShCommandsList.class); TextRange range = new TextRange(parent == null ? 0 : parent.getTextRange().getStartOffset(), posRange.getStartOffset()); String text = range.isEmpty() ? CompletionInitializationContext.DUMMY_IDENTIFIER : range.substring(posFile.getText()); PsiFile file = PsiFileFactory.getInstance(posFile.getProject()).createFileFromText("a.sh", ShLanguage.INSTANCE, text, true, false); int completionOffset = posRange.getStartOffset() - range.getStartOffset(); GeneratedParserUtilBase.CompletionState state = new GeneratedParserUtilBase.CompletionState(completionOffset) { @Override public String convertItem(Object o) { if (o instanceof IElementType[] && ((IElementType[]) o).length > 0) return kw2str(((IElementType[]) o)[0]); return o instanceof IElementType ? kw2str(((IElementType) o)) : null; } @Nullable private static String kw2str(IElementType o) { return ShTokenTypes.HUMAN_READABLE_KEYWORDS_WITHOUT_TEMPLATES.contains(o) ? o.toString() : null; } }; file.putUserData(GeneratedParserUtilBase.COMPLETION_STATE_KEY, state); TreeUtil.ensureParsed(file.getNode()); return state.items; }
suggestKeywords
14,710
String (Object o) { if (o instanceof IElementType[] && ((IElementType[]) o).length > 0) return kw2str(((IElementType[]) o)[0]); return o instanceof IElementType ? kw2str(((IElementType) o)) : null; }
convertItem
14,711
String (IElementType o) { return ShTokenTypes.HUMAN_READABLE_KEYWORDS_WITHOUT_TEMPLATES.contains(o) ? o.toString() : null; }
kw2str
14,712
Object2LongMap<String> (PsiBuilder b) { Object2LongMap<String> flags = b.getUserData(MODES_KEY); if (flags == null) b.putUserData(MODES_KEY, flags = new Object2LongOpenHashMap<>()); return flags; }
getParsingModes
14,713
boolean (PsiBuilder b, int level_, String mode, Parser parser) { return withImpl(b, level_, mode, true, parser, parser); }
withOn
14,714
boolean (PsiBuilder b, int level_, String mode, boolean onOff, Parser whenOn, Parser whenOff) { Object2LongMap<String> map = getParsingModes(b); long prev = map.getLong(mode); boolean change = ((prev & 1) == 0) == onOff; if (change) map.put(mode, prev << 1 | (onOff ? 1 : 0)); boolean result = (change ? whenOn : whenOff).parse(b, level_); if (change) map.put(mode, prev); return result; }
withImpl
14,715
void (IElementType type, int start, int end) { isWhitespaceSkipped[0] = true; }
onSkip
14,716
Lexer (Project project) { return new ShLexer(); }
createLexer
14,717
PsiParser (Project project) { return new ShParser(); }
createParser
14,718
IFileElementType () { return ShFileElementType.INSTANCE; }
getFileNodeType
14,719
TokenSet () { return whitespaceTokens; }
getWhitespaceTokens
14,720
TokenSet () { return commentTokens; }
getCommentTokens
14,721
TokenSet () { return stringLiterals; }
getStringLiteralElements
14,722
PsiElement (ASTNode astNode) { return ShTypes.Factory.createElement(astNode); }
createElement
14,723
PsiFile (@NotNull FileViewProvider fileViewProvider) { return new ShFile(fileViewProvider); }
createFile
14,724
SpaceRequirements (ASTNode left, ASTNode right) { return SpaceRequirements.MAY; }
spaceExistenceTypeBetweenTokens
14,725
String (@NotNull ShFile file) { VirtualFile virtualFile = file.getVirtualFile(); if (virtualFile != null && virtualFile.exists()) { ASTNode shebang = file.getNode().findChildByType(ShTypes.SHEBANG); String prefix = "#!"; if (shebang != null && shebang.getText().startsWith(prefix)) { return shebang.getText().substring(prefix.length()).trim(); } } return null; }
getShebangExecutable
14,726
String (@Nullable String shebang) { if (shebang == null || !shebang.startsWith(PREFIX)) return null; String interpreterPath = getInterpreterPath(shebang.substring(PREFIX.length()).trim()); String lowerCasePath = SystemInfo.isFileSystemCaseSensitive ? interpreterPath.toLowerCase(Locale.ENGLISH) : interpreterPath; return trimKnownExt(PathUtil.getFileName(lowerCasePath)); }
detectInterpreter
14,727
String (@NotNull String shebang) { int index = shebang.indexOf(" "); @NonNls String possiblePath = index < 0 ? shebang : shebang.substring(0, index); if (!possiblePath.equals("/usr/bin/env")) return possiblePath; String interpreterPath = shebang.substring(index + 1); index = interpreterPath.indexOf(" "); return index < 0 ? interpreterPath : interpreterPath.substring(0, index); }
getInterpreterPath
14,728
String (@NotNull String name) { String ext = PathUtil.getFileExtension(name); return ext != null && KNOWN_EXTENSIONS.contains(ext) ? name.substring(0, name.length() - ext.length() - 1) : name; }
trimKnownExt
14,729
String () { return PropertiesComponent.getInstance().getValue(SHELLCHECK_PATH, ""); }
getShellcheckPath
14,730
void (@Nullable String path) { if (StringUtil.isNotEmpty(path)) PropertiesComponent.getInstance().setValue(SHELLCHECK_PATH, path); }
setShellcheckPath
14,731
String () { return PropertiesComponent.getInstance().getValue(SHFMT_PATH, ""); }
getShfmtPath
14,732
void (@Nullable String path) { if (StringUtil.isNotEmpty(path)) PropertiesComponent.getInstance().setValue(SHFMT_PATH, path); }
setShfmtPath
14,733
String () { return PropertiesComponent.getInstance().getValue(SHELLCHECK_SKIPPED_VERSION, ""); }
getSkippedShellcheckVersion
14,734
void (@NotNull String version) { if (StringUtil.isNotEmpty(version)) PropertiesComponent.getInstance().setValue(SHELLCHECK_SKIPPED_VERSION, version); }
setSkippedShellcheckVersion
14,735
String () { return PropertiesComponent.getInstance().getValue(SHFMT_SKIPPED_VERSION, ""); }
getSkippedShfmtVersion
14,736
void (@NotNull String version) { if (StringUtil.isNotEmpty(version)) PropertiesComponent.getInstance().setValue(SHFMT_SKIPPED_VERSION, version); }
setSkippedShfmtVersion
14,737
boolean (@NotNull TemplateActionContext templateActionContext) { PsiFile psiFile = templateActionContext.getFile(); if (psiFile instanceof ShFile) { PsiElement element = psiFile.findElementAt(templateActionContext.getStartOffset()); if (element == null) return true; return element.getNode().getElementType() != ShTokenTypes.COMMENT; } return false; }
isInContext
14,738
Tokenizer (PsiElement element) { final ASTNode node = element.getNode(); if (node != null && TOKENS_WITH_TEXT.contains(node.getElementType())) return TEXT_TOKENIZER; if (element instanceof PsiNameIdentifierOwner) return ShIdentifierOwnerTokenizer.INSTANCE; return EMPTY_TOKENIZER; }
getTokenizer
14,739
void (@NotNull PsiNameIdentifierOwner element, @NotNull TokenConsumer consumer) { PsiElement identifier = element.getNameIdentifier(); if (identifier == null) { return; } PsiElement parent = element; final TextRange range = identifier.getTextRange(); if (range.isEmpty()) return; int offset = range.getStartOffset() - parent.getTextRange().getStartOffset(); if (offset < 0) { parent = PsiTreeUtil.findCommonParent(identifier, element); offset = range.getStartOffset() - parent.getTextRange().getStartOffset(); } String text = identifier.getText(); consumer.consumeToken(parent, text, true, offset, TextRange.allOf(text), PlainTextSplitter.getInstance()); }
tokenize
14,740
CodeInsightActionHandler () { return this; }
getHandler
14,741
void (@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { TemplateManager templateManager = TemplateManager.getInstance(project); Template template = TemplateSettings.getInstance().getTemplateById("shell_until"); if (template == null) return; moveAtNewLineIfNeeded(editor); templateManager.startTemplate(editor, template); }
invoke
14,742
CodeInsightActionHandler () { return this; }
getHandler
14,743
void (@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { TemplateManager templateManager = TemplateManager.getInstance(project); Template template = TemplateSettings.getInstance().getTemplateById("shell_for"); if (template == null) return; moveAtNewLineIfNeeded(editor); templateManager.startTemplate(editor, template); }
invoke
14,744
CodeInsightActionHandler () { return this; }
getHandler
14,745
void (@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { TemplateManager templateManager = TemplateManager.getInstance(project); Template template = TemplateSettings.getInstance().getTemplateById("shell_while"); if (template == null) return; moveAtNewLineIfNeeded(editor); templateManager.startTemplate(editor, template); }
invoke
14,746
boolean (@NotNull Project project, @NotNull Editor editor, @NotNull PsiFile file) { return file.getLanguage().is(ShLanguage.INSTANCE); }
isValidForFile
14,747
void (@NotNull Editor editor) { Document document = editor.getDocument(); Caret caret = editor.getCaretModel().getPrimaryCaret(); int line = caret.getLogicalPosition().line; if (DocumentUtil.isLineEmpty(document, line)) return; int lineEndOffset = DocumentUtil.getLineEndOffset(caret.getOffset(), document); caret.moveToOffset(lineEndOffset); EditorActionHandler actionHandler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_ENTER); actionHandler.execute(editor, caret, EditorUtil.getEditorDataContext(editor)); }
moveAtNewLineIfNeeded
14,748
EventLogGroup () { return GROUP; }
getGroup
14,749
String (@NotNull Project project, @NotNull Editor editor, @Nullable Language language, int offset) { if (offset > 0) { ShSemanticEditorPosition position = getPosition(editor, offset - 1); if (position.isAt(ShTypes.LINEFEED) || position.isAt(ShTokenTypes.WHITESPACE)) { moveAtEndOfPreviousLine(position); if (position.isAtAnyOf(ShTypes.DO, ShTypes.LEFT_CURLY, ShTypes.ELSE, ShTypes.THEN)) { return getIndentString(editor, position.getStartOffset(), true); } else if (position.isAt(ShTypes.CASE_END)) { return getIndentString(editor, position.getStartOffset(), false); } else if (isInCasePattern(editor, position)) { return getIndentString(editor, position.getStartOffset(), true); } } } return null; }
getLineIndent
14,750
boolean (@Nullable Language language) { return language instanceof ShLanguage; }
isSuitableFor
14,751
boolean (@NotNull Editor editor, ShSemanticEditorPosition position) { CharSequence docChars = editor.getDocument().getCharsSequence(); int lineStart = CharArrayUtil.shiftBackwardUntil(docChars, position.getStartOffset(), "\n") + 1; if (lineStart >= 0) { ShSemanticEditorPosition possiblePatternPosition = getPosition(editor, lineStart); possiblePatternPosition.moveAfterOptionalMix(ShTokenTypes.WHITESPACE); possiblePatternPosition.moveAfterOptionalMix(ShTypes.WORD); possiblePatternPosition.moveAfterOptionalMix(ShTokenTypes.WHITESPACE); return possiblePatternPosition.isAt(ShTypes.RIGHT_PAREN); } return false; }
isInCasePattern
14,752
void (ShSemanticEditorPosition position) { position.moveBeforeOptionalMix(ShTokenTypes.WHITESPACE); if (position.isAt(ShTypes.LINEFEED)) { position.moveBefore(); position.moveBeforeOptionalMix(ShTokenTypes.WHITESPACE); } }
moveAtEndOfPreviousLine
14,753
String (@NotNull Editor editor, int offset, boolean shouldExpand) { CodeStyleSettings settings = CodeStyle.getSettings(editor); CommonCodeStyleSettings.IndentOptions indentOptions = settings.getIndentOptions(ShFileType.INSTANCE); CharSequence docChars = editor.getDocument().getCharsSequence(); String baseIndent = ""; if (offset > 0) { int indentStart = CharArrayUtil.shiftBackwardUntil(docChars, offset, "\n") + 1; if (indentStart >= 0) { int indentEnd = CharArrayUtil.shiftForward(docChars, indentStart, " \t"); int diff = indentEnd - indentStart; if (diff > 0) { if (shouldExpand) { baseIndent = docChars.subSequence(indentStart, indentEnd).toString(); } else { if (diff >= indentOptions.INDENT_SIZE) { baseIndent = docChars.subSequence(indentStart, indentEnd - indentOptions.INDENT_SIZE).toString(); } } } } } if (shouldExpand) { baseIndent += new IndentInfo(0, indentOptions.INDENT_SIZE, 0).generateNewWhiteSpace(indentOptions); } return baseIndent; }
getIndentString
14,754
ShSemanticEditorPosition (@NotNull Editor editor, int offset) { return ShSemanticEditorPosition.createEditorPosition(editor, offset); }
getPosition
14,755
void (@Nullable Project project, @NotNull Runnable onSuccess, @NotNull Runnable onFailure) { download(project, onSuccess, onFailure, false); }
download
14,756
void (@Nullable Project project, @NotNull Runnable onSuccess, @NotNull Runnable onFailure, boolean withReplace) { File directory = new File(DOWNLOAD_PATH); if (!directory.exists()) { //noinspection ResultOfMethodCallIgnored directory.mkdirs(); } File formatter = new File(DOWNLOAD_PATH + File.separator + SHFMT + (SystemInfo.isWindows ? WINDOWS_EXTENSION : "")); File oldFormatter = new File(DOWNLOAD_PATH + File.separator + OLD_SHFMT + (SystemInfo.isWindows ? WINDOWS_EXTENSION : "")); if (formatter.exists()) { if (withReplace) { boolean successful = renameOldFormatter(formatter, oldFormatter, onFailure); if (!successful) return; } else { setupFormatterPath(formatter, onSuccess, onFailure); return; } } String downloadName = SHFMT + (SystemInfo.isWindows ? WINDOWS_EXTENSION : ""); DownloadableFileService service = DownloadableFileService.getInstance(); DownloadableFileDescription description = service.createFileDescription(getShfmtDistributionLink(), downloadName); FileDownloader downloader = service.createDownloader(Collections.singletonList(description), downloadName); Task.Backgroundable task = new Task.Backgroundable(project, message("sh.label.download.shfmt.formatter")) { @Override public void run(@NotNull ProgressIndicator indicator) { try { List<Pair<File, DownloadableFileDescription>> pairs = downloader.download(new File(DOWNLOAD_PATH)); Pair<File, DownloadableFileDescription> first = ContainerUtil.getFirstItem(pairs); File file = first != null ? first.first : null; if (file != null) { FileUtil.setExecutable(file); ShSettings.setShfmtPath(file.getCanonicalPath()); if (withReplace) { LOG.info("Remove old formatter"); FileUtil.delete(oldFormatter); } ApplicationManager.getApplication().invokeLater(onSuccess); EXTERNAL_FORMATTER_DOWNLOADED_EVENT_ID.log(); } } catch (IOException e) { LOG.warn("Can't download shfmt formatter", e); if (withReplace) rollbackToOldFormatter(formatter, oldFormatter); ApplicationManager.getApplication().invokeLater(onFailure); } } }; BackgroundableProcessIndicator processIndicator = new BackgroundableProcessIndicator(task); processIndicator.setIndeterminate(false); ProgressManager.getInstance().runProcessWithProgressAsynchronously(task, processIndicator); }
download
14,757
void (@NotNull ProgressIndicator indicator) { try { List<Pair<File, DownloadableFileDescription>> pairs = downloader.download(new File(DOWNLOAD_PATH)); Pair<File, DownloadableFileDescription> first = ContainerUtil.getFirstItem(pairs); File file = first != null ? first.first : null; if (file != null) { FileUtil.setExecutable(file); ShSettings.setShfmtPath(file.getCanonicalPath()); if (withReplace) { LOG.info("Remove old formatter"); FileUtil.delete(oldFormatter); } ApplicationManager.getApplication().invokeLater(onSuccess); EXTERNAL_FORMATTER_DOWNLOADED_EVENT_ID.log(); } } catch (IOException e) { LOG.warn("Can't download shfmt formatter", e); if (withReplace) rollbackToOldFormatter(formatter, oldFormatter); ApplicationManager.getApplication().invokeLater(onFailure); } }
run
14,758
void (@NotNull File formatter, @NotNull Runnable onSuccess, @NotNull Runnable onFailure) { try { String formatterPath = formatter.getCanonicalPath(); if (ShSettings.getShfmtPath().equals(formatterPath)) { LOG.info("Shfmt formatter already downloaded"); } else { ShSettings.setShfmtPath(formatterPath); } if (!formatter.canExecute()) FileUtil.setExecutable(formatter); ApplicationManager.getApplication().invokeLater(onSuccess); } catch (IOException e) { LOG.warn("Can't evaluate formatter path or make it executable", e); ApplicationManager.getApplication().invokeLater(onFailure); } }
setupFormatterPath
14,759
boolean (@NotNull File formatter, @NotNull File oldFormatter, @NotNull Runnable onFailure) { LOG.info("Rename formatter to the temporary filename"); try { FileUtil.rename(formatter, oldFormatter); } catch (IOException e) { LOG.info("Can't rename formatter to the temporary filename", e); ApplicationManager.getApplication().invokeLater(onFailure); return false; } return true; }
renameOldFormatter
14,760
void (@NotNull File formatter, @NotNull File oldFormatter) { LOG.info("Update failed, rollback"); try { FileUtil.rename(oldFormatter, formatter); } catch (IOException e) { LOG.info("Can't rollback formatter after failed update", e); } FileUtil.delete(oldFormatter); }
rollbackToOldFormatter
14,761
boolean (@Nullable String path) { if (path == null) return false; if (ShSettings.I_DO_MIND_SUPPLIER.get().equals(path)) return true; File file = new File(path); if (!file.canExecute()) return false; return file.getName().contains(SHFMT); }
isValidPath
14,762
void (@NotNull Project project) { Application application = ApplicationManager.getApplication(); if (application.getUserData(UPDATE_NOTIFICATION_SHOWN) != null) return; application.putUserData(UPDATE_NOTIFICATION_SHOWN, true); if (application.isDispatchThread()) { application.executeOnPooledThread(() -> checkForUpdateInBackgroundThread(project)); } else { checkForUpdateInBackgroundThread(project); } }
checkShfmtForUpdate
14,763
void (@NotNull Project project) { ApplicationManager.getApplication().assertIsNonDispatchThread(); if (!isNewVersionAvailable()) return; Notification notification = NOTIFICATION_GROUP.createNotification(message("sh.shell.script"), message("sh.fmt.update.question"), NotificationType.INFORMATION); notification.setSuggestionType(true); notification.setDisplayId(ShNotificationDisplayIds.UPDATE_FORMATTER); notification.addAction( NotificationAction.createSimple(messagePointer("sh.update"), () -> { notification.expire(); download(project, () -> Notifications.Bus .notify(NOTIFICATION_GROUP.createNotification(message("sh.shell.script"), message("sh.fmt.success.update"), NotificationType.INFORMATION) .setDisplayId(ShNotificationDisplayIds.UPDATE_FORMATTER_SUCCESS)), () -> Notifications.Bus .notify(NOTIFICATION_GROUP.createNotification(message("sh.shell.script"), message("sh.fmt.cannot.update"), NotificationType.ERROR) .setDisplayId(ShNotificationDisplayIds.UPDATE_FORMATTER_ERROR)), true); })); notification.addAction(NotificationAction.createSimple(messagePointer("sh.skip.version"), () -> { notification.expire(); ShSettings.setSkippedShfmtVersion(SHFMT_VERSION); })); Notifications.Bus.notify(notification, project); }
checkForUpdateInBackgroundThread
14,764
boolean () { String path = ShSettings.getShfmtPath(); if (ShSettings.I_DO_MIND_SUPPLIER.get().equals(path)) return false; File file = new File(path); if (!file.canExecute()) return false; if (!file.getName().contains(SHFMT)) return false; try { GeneralCommandLine commandLine = new GeneralCommandLine().withExePath(path).withParameters("--version"); ProcessOutput processOutput = ExecUtil.execAndGetOutput(commandLine, 3000); String stdout = processOutput.getStdout(); return !stdout.contains(SHFMT_VERSION) && !ShSettings.getSkippedShfmtVersion().equals(SHFMT_VERSION); } catch (ExecutionException e) { LOG.debug("Exception in process execution", e); } return false; }
isNewVersionAvailable
14,765
String () { StringBuilder baseUrl = new StringBuilder("https://github.com/mvdan/sh/releases/download/") .append(SHFMT_VERSION) .append('/') .append(SHFMT) .append('_') .append(SHFMT_VERSION); if (SystemInfo.isMac) { baseUrl.append(MAC); } else if (SystemInfo.isLinux) { baseUrl.append(LINUX); } else if (SystemInfo.isWindows) { baseUrl.append(WINDOWS); } else if (SystemInfo.isFreeBSD) { baseUrl.append(FREE_BSD); } if (CpuArch.isIntel64()) { baseUrl.append(ARCH_x86_64); } if (CpuArch.isIntel32()) { baseUrl.append(ARCH_i386); } else if (CpuArch.isArm64()) { baseUrl.append(ARCH_ARM64); } if (SystemInfo.isWindows) { baseUrl.append(WINDOWS_EXTENSION); } return baseUrl.toString(); }
getShfmtDistributionLink
14,766
void () { statusBarUpdated = false; }
beforeAllDocumentsSaving
14,767
void (@NotNull Document document) { VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document); if (virtualFile == null) return; Project project = ProjectUtil.guessProjectForFile(virtualFile); if (project == null) return; PsiFile psiFile = PsiManager.getInstance(project).findFile(virtualFile); if (!(psiFile instanceof ShFile)) return; CodeStyleSettings settings = CodeStyle.getSettings(psiFile); ShCodeStyleSettings shSettings = settings.getCustomSettings(ShCodeStyleSettings.class); String expectedLineSeparator = shSettings.USE_UNIX_LINE_SEPARATOR ? LineSeparator.LF.getSeparatorString() : LineSeparator.getSystemLineSeparator().getSeparatorString(); String fileDetectedLineSeparator = virtualFile.getDetectedLineSeparator(); if (fileDetectedLineSeparator == null || !fileDetectedLineSeparator.equals(expectedLineSeparator)) { virtualFile.setDetectedLineSeparator(expectedLineSeparator); if (!statusBarUpdated) { statusBarUpdated = true; updateStatusBar(project); } } }
beforeDocumentSaving
14,768
void (@NotNull Project project) { ApplicationManager.getApplication().invokeLater(() -> { IdeFrame frame = WindowManager.getInstance().getIdeFrame(project); StatusBar statusBar = frame != null ? frame.getStatusBar() : null; StatusBarWidget widget = statusBar != null ? statusBar.getWidget(StatusBar.StandardWidgets.LINE_SEPARATOR_PANEL) : null; if (widget instanceof LineSeparatorPanel) { ((LineSeparatorPanel)widget).selectionChanged(null); } }); }
updateStatusBar
14,769
ShSemanticEditorPosition (@NotNull Editor editor, int offset) { return new ShSemanticEditorPosition(editor, offset); }
createEditorPosition
14,770
boolean (@NotNull PsiFile file) { return file instanceof ShFile; }
canFormat
14,771
Set<Feature> () { return FEATURES; }
getFeatures
14,772
String () { return NOTIFICATION_GROUP_ID; }
getNotificationGroupId
14,773
String () { return message("sh.shell.script"); }
getName
14,774
void () { handler.addProcessListener(new CapturingProcessAdapter() { @Override public void processTerminated(@NotNull ProcessEvent event) { int exitCode = event.getExitCode(); if (exitCode == 0) { request.onTextReady(getOutput().getStdout()); } else { request.onError(message("sh.shell.script"), getOutput().getStderr()); } } }); handler.startNotify(); }
run
14,775
void (@NotNull ProcessEvent event) { int exitCode = event.getExitCode(); if (exitCode == 0) { request.onTextReady(getOutput().getStdout()); } else { request.onError(message("sh.shell.script"), getOutput().getStderr()); } }
processTerminated
14,776
boolean () { handler.destroyProcess(); return true; }
cancel
14,777
boolean () { return true; }
isRunUnderProgress
14,778
String () { return getText(); }
getFamilyName
14,779
String () { return ShBundle.message("sh.rename.all.occurrences"); }
getText
14,780
boolean () { return false; }
startInWriteAction
14,781
boolean (@NotNull Project project, Editor editor, PsiFile file) { return ShOccurrencesHighlightingSuppressor.isOccurrencesHighlightingEnabled(editor, file) && ShRenameAllOccurrencesHandler.INSTANCE.isEnabled(editor, editor.getCaretModel().getPrimaryCaret(), null); }
isAvailable
14,782
ShortcutSet () { return CommonShortcuts.getRename(); }
getShortcut
14,783
ShTextRenameRefactoring (@NotNull Editor editor, @NotNull Project project, @NotNull String occurrenceText, @NotNull Collection<TextRange> occurrenceRanges, @NotNull TextRange occurrenceRangeAtCaret) { PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument()); if (psiFile != null) { return new ShTextRenameRefactoring(editor, project, psiFile, occurrenceText, occurrenceRanges, occurrenceRangeAtCaret); } return null; }
create
14,784
void () { int offset = myEditor.getCaretModel().getOffset(); myCaretRangeMarker = myEditor.getDocument().createRangeMarker(offset, offset); myCaretRangeMarker.setGreedyToLeft(true); myCaretRangeMarker.setGreedyToRight(true); }
createCaretRangeMarker
14,785
void (TemplateBuilderImpl builder) { int caretOffset = myEditor.getCaretModel().getOffset(); TextRange range = myPsiFile.getTextRange(); assert range != null; RangeMarker rangeMarker = myEditor.getDocument().createRangeMarker(range); Template template = builder.buildInlineTemplate(); template.setToShortenLongNames(false); template.setToReformat(false); myEditor.getCaretModel().moveToOffset(rangeMarker.getStartOffset()); TemplateManager.getInstance(myProject).startTemplate(myEditor, template, new MyTemplateListener()); restoreOldCaretPositionAndSelection(caretOffset); myHighlighters = new ArrayList<>(); highlightTemplateVariables(template); }
startTemplate
14,786
void (@NotNull Template template) { if (myHighlighters != null) { // can be null if finish is called during testing Map<TextRange, TextAttributes> rangesToHighlight = new HashMap<>(); TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor); if (templateState != null) { EditorColorsManager colorsManager = EditorColorsManager.getInstance(); for (int i = 0; i < templateState.getSegmentsCount(); i++) { TextRange segmentOffset = templateState.getSegmentRange(i); TextAttributes attributes = getAttributes(colorsManager, template.getSegmentName(i)); if (attributes != null) { rangesToHighlight.put(segmentOffset, attributes); } } } addHighlights(rangesToHighlight, myHighlighters); } }
highlightTemplateVariables
14,787
TextAttributes (@NotNull EditorColorsManager colorsManager, @NotNull String segmentName) { if (segmentName.equals(PRIMARY_VARIABLE_NAME)) { return colorsManager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES); } if (segmentName.equals(OTHER_VARIABLE_NAME)) { return colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES); } return null; }
getAttributes
14,788
void (@NotNull Map<TextRange, TextAttributes> ranges, @NotNull Collection<RangeHighlighter> highlighters) { HighlightManager highlightManager = HighlightManager.getInstance(myProject); for (Map.Entry<TextRange, TextAttributes> entry : ranges.entrySet()) { TextRange range = entry.getKey(); TextAttributes attributes = entry.getValue(); highlightManager.addOccurrenceHighlight(myEditor, range.getStartOffset(), range.getEndOffset(), attributes, 0, highlighters, null); } for (RangeHighlighter highlighter : highlighters) { highlighter.setGreedyToLeft(true); highlighter.setGreedyToRight(true); } }
addHighlights
14,789
void () { if (myHighlighters != null) { if (!myProject.isDisposed()) { HighlightManager highlightManager = HighlightManager.getInstance(myProject); for (RangeHighlighter highlighter : myHighlighters) { highlightManager.removeSegmentHighlighter(myEditor, highlighter); } } myHighlighters = null; } }
clearHighlights
14,790
void (int offset) { Runnable runnable = () -> myEditor.getCaretModel().moveToOffset(restoreCaretOffset(offset)); LookupImpl lookup = (LookupImpl) LookupManager.getActiveLookup(myEditor); if (lookup != null && lookup.getLookupStart() <= (restoreCaretOffset(offset))) { lookup.setLookupFocusDegree(LookupFocusDegree.UNFOCUSED); lookup.performGuardedChange(runnable); } else { runnable.run(); } }
restoreOldCaretPositionAndSelection
14,791
int (int offset) { return myCaretRangeMarker.isValid() ? myCaretRangeMarker.getEndOffset() : offset; }
restoreCaretOffset
14,792
Result (ExpressionContext context) { Editor editor = context.getEditor(); if (editor != null) { TextResult insertedValue = context.getVariableValue(PRIMARY_VARIABLE_NAME); if (insertedValue != null && !insertedValue.getText().isEmpty()) { return insertedValue; } } return new TextResult(myInitialText); }
calculateResult
14,793
LookupElement[] (ExpressionContext context) { return LookupElement.EMPTY_ARRAY; }
calculateLookupItems
14,794
void (@NotNull TemplateState templateState, Template template) { clearHighlights(); }
beforeTemplateFinished
14,795
void (Template template) { clearHighlights(); }
templateCancelled
14,796
boolean (@NotNull Editor editor, @NotNull Caret caret, DataContext dataContext) { return editor.getProject() != null; }
isEnabledForCaret
14,797
void (@NotNull final Editor editor, @Nullable Caret c, DataContext dataContext) { Caret caret = editor.getCaretModel().getPrimaryCaret(); SelectionModel selectionModel = editor.getSelectionModel(); boolean hasSelection = caret.hasSelection(); TextRange occurrenceAtCaret = hasSelection ? new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) : ShTextOccurrencesUtil.findTextRangeOfIdentifierAtCaret(editor); if (occurrenceAtCaret == null) return; CharSequence documentText = editor.getDocument().getImmutableCharSequence(); CharSequence textToFind = occurrenceAtCaret.subSequence(documentText); Collection<TextRange> occurrences = ShTextOccurrencesUtil.findAllOccurrences(documentText, textToFind, !hasSelection); Project project = editor.getProject(); assert project != null; if (occurrences.size() < getMaxInplaceRenameSegments() && documentText.length() < FileUtilRt.MEGABYTE) { ShTextRenameRefactoring rename = ShTextRenameRefactoring.create(editor, project, textToFind.toString(), occurrences, occurrenceAtCaret); if (rename != null) { rename.start(); return; } } TextOccurrencesRenamer renamer = new TextOccurrencesRenamer(editor, textToFind.toString(), occurrences, occurrenceAtCaret); if (ApplicationManager.getApplication().isUnitTestMode()) { editor.putUserData(RENAMER_KEY, renamer); } else { new ShRenameDialog(project, renamer).show(); } }
doExecute
14,798
RegistryValue () { return Registry.get("inplace.rename.segments.limit"); }
getMaxInplaceRenameSegmentsRegistryValue
14,799
int () { try { return getMaxInplaceRenameSegmentsRegistryValue().asInteger(); } catch (MissingResourceException e) { return -1; } }
getMaxInplaceRenameSegments