String (Project project, PsiFile file, Editor editor, String text, RawText rawText) { if (!CodeInsightSettings.getInstance().INDENT_TO_CARET_ON_PASTE || !isSupportedFile(file)) { return text; } final CaretModel caretModel = editor.getCaretModel(); final SelectionModel selectionModel = editor.getSelectionModel(); final Document document = editor.getDocument(); final int caretOffset = selectionModel.getSelectionStart() != selectionModel.getSelectionEnd() ? selectionModel.getSelectionStart() : caretModel.getOffset(); final int lineNumber = document.getLineNumber(caretOffset); final int lineStartOffset = getLineStartSafeOffset(document, lineNumber); final int lineEndOffset = document.getLineEndOffset(lineNumber); final String line = document.getText(TextRange.create(lineStartOffset, lineEndOffset)); final String linePrefix = document.getText(TextRange.create(lineStartOffset, caretOffset)); if (!StringUtil.isEmptyOrSpaces(linePrefix)) return text; final PsiElement element = file.findElementAt(caretOffset); if (PsiTreeUtil.getParentOfType(element, PyStringLiteralExpression.class) != null) return text; text = addLeadingSpacesToNormalizeSelection(file, text); final String fragmentIndent = PyIndentUtil.findCommonIndent(text, false); final String newIndent = inferBestIndent(file, document, caretOffset, lineNumber, fragmentIndent); String newText = PyIndentUtil.changeIndent(text, false, newIndent); if (!selectionModel.hasSelection() && shouldPasteOnPreviousLine(file, text, caretOffset)) { caretModel.moveToOffset(lineStartOffset); if (StringUtil.isEmptyOrSpaces(line)) { ApplicationManager.getApplication().runWriteAction(() -> document.deleteString(lineStartOffset, lineEndOffset)); } } else { // Don't duplicate the existing whitespace prefix of the line newText = StringUtil.trimStart(newText, linePrefix); } final boolean useTabs = PyIndentUtil.areTabsUsedForIndentation(file); // TODO Combine shouldPasteOnPreviousLine() check with addLineBreak() as they really complement each other if (addLinebreak(text, line, useTabs) && selectionModel.getSelectionStart() == selectionModel.getSelectionEnd()) { newText += "\n"; } return newText; }