@Override public void documentChanged(@NotNull DocumentEvent event) { templatesListPanel.updateContent(event.getDocument().getText()); } });
@Override public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement item) { int tailOffset = context.getTailOffset(); Document document = context.getDocument(); int documentTextLength = document.getTextLength(); boolean insertParentheses; if (documentTextLength > tailOffset) { String currentTail = document.getText( new TextRange(tailOffset, tailOffset + 1) ); char firstChar = currentTail.charAt(0); insertParentheses = firstChar != ' ' && firstChar != '(' && firstChar != '['; } else { insertParentheses = true; } if (insertParentheses) { context.getDocument().insertString(tailOffset, "()"); // + 1 to put between the `(` and `)` context.getEditor().getCaretModel().moveToOffset(tailOffset + 1); } } }
/** * Sorts a text range with a comparator. Returns true if a replace was performed, false otherwise. * * @param editor The editor to replace text in * @param start The starting position for the sort * @param end The ending position for the sort * @param lineComparator The comparator to use to sort * @return true if able to sort the text, false if not */ private boolean sortTextRange(@NotNull Editor editor, int start, int end, @NotNull Comparator<String> lineComparator) { final String selectedText = editor.getDocument().getText(new TextRangeInterval(start, end)); final List<String> lines = Lists.newArrayList(Splitter.on("\n").split(selectedText)); if (lines.size() < 1) { return false; } lines.sort(lineComparator); replaceText(editor, start, end, StringUtil.join(lines, "\n")); return true; }
if (ignoreDuplicates) { List<String> currentLines = ContainerUtil.filter( document.getText().split(Constants.NEWLINE), s -> !s.isEmpty() && !s.startsWith(Constants.HASH) ); entry += Constants.NEWLINE; if (!insertAtCursor && !document.getText().endsWith(Constants.NEWLINE) && !StringUtil.isEmpty(entry)) { entry = Constants.NEWLINE + entry;
private CompletionResultSet adjustMatcher(@NotNull CompletionParameters parameters, @NotNull CompletionResultSet result, @NotNull PsiElement parent) { int startOffset = parent.getTextRange().getStartOffset(); String newPrefix = parameters.getEditor().getDocument().getText(TextRange.create(startOffset, parameters.getOffset())); return result.withPrefixMatcher(createPrefixMatcher(newPrefix)); } });
private static boolean isLineBreakpointAvailable(@NotNull VirtualFile file, int line, @NotNull Project project) { Document document = FileDocumentManager.getInstance().getDocument(file); if (document == null || document.getLineEndOffset(line) == document.getLineStartOffset(line)) { return false; } Checker canPutAtChecker = new Checker(); XDebuggerUtil.getInstance().iterateLine(project, document, line, canPutAtChecker); // Used to identify line comments, which cannot be correctly processed by the checker. if (document.getText(new TextRange(document.getLineStartOffset(line), document.getLineEndOffset(line))).trim() .startsWith(BALLERINA_LINE_COMMENT_PREFIX)) { return false; } return canPutAtChecker.isLineBreakpointAvailable(); }
private boolean firstOnLine(@NotNull ASTNode node) { Document document = document(node.getPsi()); assert document != null; int nodeStartOffset = node.getStartOffset(); int lineNumber = document.getLineNumber(nodeStartOffset); int lineStartOffset = document.getLineStartOffset(lineNumber); String prefix = document.getText(new TextRange(lineStartOffset, nodeStartOffset)); return isWhitespace(prefix); }
@Nullable @Override public CharSequence getClosingQuote(HighlighterIterator highlighterIterator, int offset) { CharSequence closingQuote = null; if (highlighterIterator.getStart() > 0) { highlighterIterator.retreat(); try { IElementType tokenType = highlighterIterator.getTokenType(); if (CLOSING_QUOTE_BY_OPENING_QUOTE.get(tokenType) != null) { Document document = highlighterIterator.getDocument(); if (document != null) { String promoter = document.getText( new TextRange(highlighterIterator.getStart(), highlighterIterator.getEnd()) ); String terminator = StackFrame.TERMINATOR_BY_PROMOTER.get(promoter); if (terminator != null) { if (terminator.length() >= 3) { closingQuote = "\n" + terminator; } else { closingQuote = terminator; } } } } } finally { highlighterIterator.advance(); } } return closingQuote; }
@Override protected void addCompletions(@NotNull CompletionParameters parameters, ProcessingContext context, @NotNull CompletionResultSet result) { GoImportString importString = PsiTreeUtil.getParentOfType(parameters.getPosition(), GoImportString.class); if (importString == null) return; String path = importString.getPath(); if (path.startsWith("./") || path.startsWith("../")) return; TextRange pathRange = importString.getPathTextRange().shiftRight(importString.getTextRange().getStartOffset()); String newPrefix = parameters.getEditor().getDocument().getText(TextRange.create(pathRange.getStartOffset(), parameters.getOffset())); result = result.withPrefixMatcher(result.getPrefixMatcher().cloneWithPrefix(newPrefix)); Module module = ModuleUtilCore.findModuleForPsiElement(parameters.getOriginalFile()); if (module != null) { addCompletions(result, module, parameters.getOriginalFile(), GoUtil.goPathResolveScope(module, parameters.getOriginalFile()), false); } }
@Override public void execute(@NotNull Editor editor, char c, @NotNull DataContext dataContext) { if (myOriginalHandler != null) myOriginalHandler.execute(editor, c, dataContext); if (c != 'e') return; Project project = editor.getProject(); if (project == null) return; int offset = editor.getCaretModel().getOffset(); if (offset < 4) return; TextRange from = TextRange.from(offset - 4, 4); String text = editor.getDocument().getText(from); if ("case".equals(text)) { PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); ApplicationManager.getApplication().runWriteAction(() -> { if (project.isDisposed()) return; PsiFile file = PsiUtilBase.getPsiFileInEditor(editor, project); if (file == null) return; CodeStyleManager.getInstance(project).adjustLineIndent(file, from); }); } } }
/** * Creates new user template. */ private void performCreateAction() { IgnoreSettings.UserTemplate template = new IgnoreSettings.UserTemplate(name.getText(), previewDocument.getText()); settings.getUserTemplates().add(template); Notifications.Bus.notify(new Notification( IgnoreBundle.PLUGIN_ID, IgnoreBundle.message("dialog.userTemplate.added"), IgnoreBundle.message("dialog.userTemplate.added.description", template.getName()), NotificationType.INFORMATION ), project); super.doOKAction(); } }
/** * Format the ranges of the given document. * * <p>Overriding methods will need to modify the document with the result of the external * formatter (usually using {@link #performReplacements(Document, Map)}. */ private void format(Document document, Collection<TextRange> ranges) { Style style = GoogleJavaFormatSettings.getInstance(getProject()).getStyle(); Formatter formatter = new Formatter(JavaFormatterOptions.builder().style(style).build()); performReplacements( document, FormatterUtil.getReplacements(formatter, document.getText(), ranges)); }
@Override public Result postProcessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull DataContext dataContext) { if (!file.getLanguage().is(BallerinaLanguage.INSTANCE)) { return Result.Continue; } // We need to save the file before checking. Otherwise issues can occur when we press enter in a string. Project project = file.getProject(); PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); // Checks whether the previous line starts with "#". LogicalPosition caretPos = editor.getCaretModel().getLogicalPosition(); int prevLine = caretPos.line - 1; String lineString = editor.getDocument().getText( new TextRange(editor.getDocument().getLineStartOffset(prevLine), editor.getDocument().getLineEndOffset(prevLine))); if (lineString.trim().startsWith("#")) { int newCol = lineString.indexOf("#"); String enteredText = editor.getDocument().getText( new TextRange(editor.getDocument().getLineStartOffset(caretPos.line), editor.getDocument().getLineEndOffset(caretPos.line))).trim(); editor.getDocument().deleteString(editor.getDocument().getLineStartOffset(caretPos.line), editor.getDocument().getLineEndOffset(caretPos.line)); editor.getCaretModel().moveToLogicalPosition(new LogicalPosition(caretPos.line, 1)); enterNewLine(editor, enteredText, newCol); // Commit the document. PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument()); } return Result.Continue; }
private void doTest(File resource) { try { String name = resource.getName().replace("." + myFileExt, EMPTY_STRING); // Retrieves relative path of the file since loadFile() uses "myFullDataPath" as the source root. String relativeFilePath = resource.getPath().replace(getTestDataPath(), EMPTY_STRING); String text = loadFile(relativeFilePath); myFile = createPsiFile(name, text); ensureParsed(myFile); assertEquals("light virtual file text mismatch", text, ((LightVirtualFile) myFile.getVirtualFile()).getContent().toString()); assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(myFile.getVirtualFile())); assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText()); assertEquals("psi text mismatch", text, myFile.getText()); ensureCorrectReparse(myFile); checkResult(relativeFilePath, myFile); } catch (IOException e) { throw new RuntimeException(e); } }
private boolean hasStartingQuote( final InsertionContext insertionContext, final char quoteType, final int startOfLookupStringOffset) { return insertionContext.getDocument().getText().charAt(startOfLookupStringOffset - 1) == quoteType; }
@NotNull private PsiFile root() { String name = getTestName(false); PsiFile root; try { String text = loadFile(name + "." + myFileExt); myFile = createPsiFile(name, text); ensureParsed(myFile); assertEquals("light virtual file text mismatch", text, ((LightVirtualFile) myFile.getVirtualFile()).getContent().toString()); assertEquals("virtual file text mismatch", text, LoadTextUtil.loadText(myFile.getVirtualFile())); assertEquals("doc text mismatch", text, myFile.getViewProvider().getDocument().getText()); assertEquals("psi text mismatch", text, myFile.getText()); FileViewProvider fileViewProvider = myFile.getViewProvider(); root = fileViewProvider.getPsi(ElixirLanguage.INSTANCE); assertNotNull(root); } catch (IOException exception) { throw new RuntimeException(exception); } return root; } }
private void removeSiblingFieldCommaIfNecessary(final Editor editor) { final int offset = editor.getCaretModel().getOffset(); final String textAfterOffset = editor.getDocument().getText().substring(offset); if (StringUtils.nextCharAfterSpacesAndLineBreaksIsCurlyBraces(textAfterOffset)) { final String textBeforeOffset = editor.getDocument().getText().substring(0, offset); if (StringUtils.nextCharAfterSpacesAndLineBreaksIsCommaStartingFromEnd(textBeforeOffset)) { final int lastCommaIndex = textBeforeOffset.lastIndexOf(","); editor.getDocument().deleteString(lastCommaIndex, lastCommaIndex + 1); } } }
private void removeCommaIfNecessary(final Editor editor) { final int offset = editor.getCaretModel().getOffset(); if (editor.getDocument().getText().charAt(offset) == ',') { editor.getDocument().deleteString(offset, offset + 1); } }
private void handleStartingQuote( final InsertionContext insertionContext, final LookupElement lookupElement) { final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset(); final int startOfLookupStringOffset = caretOffset - lookupElement.getLookupString().length(); final boolean hasStartingQuote = insertionContext.getDocument().getText().charAt(startOfLookupStringOffset - 1) == '\"'; if (!hasStartingQuote) { insertionContext.getDocument().insertString(startOfLookupStringOffset, "\""); } }
private void handleStartingQuote( final InsertionContext insertionContext, final LookupElement lookupElement) { final int caretOffset = insertionContext.getEditor().getCaretModel().getOffset(); final int startOfLookupStringOffset = caretOffset - lookupElement.getLookupString().length(); final boolean hasStartingQuote = insertionContext.getDocument().getText().charAt(startOfLookupStringOffset - 1) == '\"'; if (!hasStartingQuote) { insertionContext.getDocument().insertString(startOfLookupStringOffset, "\""); } }