下面列出了com.intellij.psi.impl.source.tree.java.PsiJavaTokenImpl#com.intellij.openapi.editor.SelectionModel 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void getTranslation(AnActionEvent event) {
Editor editor = event.getData(PlatformDataKeys.EDITOR);
if (editor == null) {
return;
}
SelectionModel model = editor.getSelectionModel();
String selectedText = model.getSelectedText();
if (TextUtils.isEmpty(selectedText)) {
selectedText = getCurrentWords(editor);
if (TextUtils.isEmpty(selectedText)) {
return;
}
}
String queryText = strip(addBlanks(selectedText));
new Thread(new RequestRunnable(mTranslator, editor, queryText)).start();
}
@Nullable
private String getSelectedText(Project project) {
Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
if (editor == null) {
return null;
}
Document currentDoc = editor.getDocument();
if (currentDoc == null) {
return null;
}
VirtualFile currentFile = FileDocumentManager.getInstance().getFile(currentDoc);
if (currentFile == null) {
return null;
}
SelectionModel sel = editor.getSelectionModel();
return sel.getSelectedText();
}
private void getTranslation(AnActionEvent event) {
Editor mEditor = event.getData(PlatformDataKeys.EDITOR);
Project project = event.getData(PlatformDataKeys.PROJECT);
String basePath = project.getBasePath();
if (null == mEditor) {
return;
}
SelectionModel model = mEditor.getSelectionModel();
String selectedText = model.getSelectedText();
if (TextUtils.isEmpty(selectedText)) {
selectedText = getCurrentWords(mEditor);
if (TextUtils.isEmpty(selectedText)) {
return;
}
}
String queryText = strip(addBlanks(selectedText));
new Thread(new RequestRunnable(mEditor, queryText,basePath)).start();
}
public void replaceSelection(@Nonnull final String clipboardText) {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
@Override
public void run() {
CommandProcessor.getInstance().executeCommand(getProject(), new Runnable() {
@Override
public void run() {
final SelectionModel model = Assertions.assertNotNull(getEditor()).getSelectionModel();
final int start = model.getSelectionStart();
final int end = model.getSelectionEnd();
getDocument().replaceString(start, end, "");
getDocument().insertString(start, clipboardText);
}
}, null, null, UndoConfirmationPolicy.DEFAULT, getDocument());
}
});
}
protected List<PsiElement> getPsiElements(Class stepClass) {
SelectionModel selectionModel = editor.getSelectionModel();
List<PsiElement> specSteps = new ArrayList<>();
int currentOffset = selectionModel.getSelectionStart();
while (selectionModel.getSelectionEnd() >= currentOffset) {
try {
if (psiFile.getText().charAt(currentOffset++) == '\n') continue;
PsiElement step = getStep(psiFile.findElementAt(currentOffset), stepClass);
if (step == null) return new ArrayList<>();
specSteps.add(step);
currentOffset += step.getText().length();
} catch (Exception ignored) {
LOG.debug(ignored);
}
}
return specSteps;
}
/**
* Wraps selection.
*
* @param editor Current editor.
*/
private void wrap(@NotNull TextEditor editor) {
final Document document = editor.getEditor().getDocument();
final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
final CaretModel caretModel = editor.getEditor().getCaretModel();
final int start = selectionModel.getSelectionStart();
final int end = selectionModel.getSelectionEnd();
final String text = StringUtil.notNullize(selectionModel.getSelectedText());
String newText = getLeftText() + text + getRightText();
int newStart = start + getLeftText().length();
int newEnd = StringUtil.isEmpty(text) ? newStart : end + getLeftText().length();
document.replaceString(start, end, newText);
selectionModel.setSelection(newStart, newEnd);
caretModel.moveToOffset(newEnd);
}
/**
* Unwraps selection.
*
* @param editor Current editor.
* @param matched Matched PSI element.
*/
private void unwrap(@NotNull final TextEditor editor, @NotNull final PsiElement matched) {
final Document document = editor.getEditor().getDocument();
final SelectionModel selectionModel = editor.getEditor().getSelectionModel();
final CaretModel caretModel = editor.getEditor().getCaretModel();
final int start = matched.getTextRange().getStartOffset();
final int end = matched.getTextRange().getEndOffset();
final String text = StringUtil.notNullize(matched.getText());
String newText = StringUtil.trimEnd(StringUtil.trimStart(text, getLeftText()), getRightText());
int newStart = selectionModel.getSelectionStart() - getLeftText().length();
int newEnd = selectionModel.getSelectionEnd() - getLeftText().length();
document.replaceString(start, end, newText);
selectionModel.setSelection(newStart, newEnd);
caretModel.moveToOffset(newEnd);
}
private boolean propertiesHandling(Editor editor, DataContext dataContext, SelectionModel selectionModel,
PsiFile psiFile) {
PsiElement elementAtCaret = PsiUtilBase.getElementAtCaret(editor);
if (elementAtCaret instanceof PsiWhiteSpace) {
return false;
} else if (elementAtCaret instanceof LeafPsiElement) {
IElementType elementType = ((LeafPsiElement) elementAtCaret).getElementType();
if (elementType.toString().equals("Properties:VALUE_CHARACTERS")
|| elementType.toString().equals("Properties:KEY_CHARACTERS")) {
TextRange textRange = elementAtCaret.getTextRange();
if (textRange.getLength() == 0) {
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
return true;
}
}
return false;
}
protected void executeMyWriteActionPerCaret(Editor editor, Caret caret, Map<String, Object> actionContext, DataContext dataContext, T additionalParam) {
final SelectionModel selectionModel = editor.getSelectionModel();
String selectedText = selectionModel.getSelectedText();
if (selectedText == null) {
selectSomethingUnderCaret(editor, dataContext, selectionModel);
selectedText = selectionModel.getSelectedText();
if (selectedText == null) {
return;
}
}
String s = transformSelection(editor, actionContext, dataContext, selectedText, additionalParam);
s = s.replace("\r\n", "\n");
s = s.replace("\r", "\n");
editor.getDocument().replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), s);
}
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
PsiElement el = MyActionUtils.getSelectedPsiElement(e);
if ( el==null ) return;
final PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
if ( psiFile==null ) return;
Editor editor = e.getData(PlatformDataKeys.EDITOR);
if ( editor==null ) return;
SelectionModel selectionModel = editor.getSelectionModel();
if ( !selectionModel.hasSelection() ) {
List<PsiElement> expressions = findExtractableRules(el);
IntroduceTargetChooser.showChooser(editor, expressions, new Pass<PsiElement>() {
@Override
public void pass(PsiElement element) {
selectionModel.setSelection(element.getTextOffset(), element.getTextRange().getEndOffset());
extractSelection(psiFile, editor, selectionModel);
}
}, PsiElement::getText);
} else {
extractSelection(psiFile, editor, selectionModel);
}
}
@RequiredWriteAction
@Override
public void executeWriteAction(@Nonnull Editor editor, Caret caret, DataContext dataContext) {
final Document document = editor.getDocument();
final int caretOffset = editor.getCaretModel().getOffset();
if (caretOffset < 1) {
return;
}
final SelectionModel selectionModel = editor.getSelectionModel();
final CharSequence text = document.getCharsSequence();
final char c = text.charAt(caretOffset - 1);
if (!selectionModel.hasSelection() && StringUtil.isWhiteSpace(c)) {
int startOffset = CharArrayUtil.shiftBackward(text, caretOffset - 2, "\t \n") + 1;
document.deleteString(startOffset, caretOffset);
}
else {
final EditorActionHandler handler = EditorActionManager.getInstance().getActionHandler(IdeActions.ACTION_EDITOR_BACKSPACE);
handler.execute(editor, caret, dataContext);
}
}
@RequiredWriteAction
@Override
public void executeWriteAction(final Editor editor, @Nullable Caret caret, DataContext dataContext) {
final SelectionModel selectionModel = editor.getSelectionModel();
int changedLines = 0;
if (selectionModel.hasSelection()) {
changedLines = performAction(editor, new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()));
}
else {
changedLines += performAction(editor, new TextRange(0, editor.getDocument().getTextLength()));
}
if (changedLines == 0) {
HintManager.getInstance().showInformationHint(editor, "All lines already have requested indentation");
}
else {
HintManager.getInstance().showInformationHint(editor, "Changed indentation in " + changedLines + (changedLines == 1 ? " line" : " lines"));
}
}
@Override
public void execute(Editor editor, DataContext dataContext) {
if (!(editor instanceof EditorEx)) {
return;
}
final SelectionModel selectionModel = editor.getSelectionModel();
if (!selectionModel.hasSelection()) {
return;
}
EditorEx editorEx = (EditorEx)editor;
final int start = selectionModel.getSelectionStart();
final int end = selectionModel.getSelectionEnd();
final CaretModel caretModel = editor.getCaretModel();
boolean moveToEnd = caretModel.getOffset() == start;
editorEx.setStickySelection(false);
editorEx.setStickySelection(true);
if (moveToEnd) {
caretModel.moveToOffset(end);
}
else {
caretModel.moveToOffset(start);
}
}
@Override
public void execute(final Editor editor, final DataContext dataContext) {
SelectionModel selectionModel = editor.getSelectionModel();
if (!selectionModel.hasSelection()) {
return;
}
final int start = selectionModel.getSelectionStart();
final int end = selectionModel.getSelectionEnd();
if (start >= end) {
return;
}
KillRingUtil.copyToKillRing(editor, start, end, false);
if (myRemove) {
ApplicationManager.getApplication().runWriteAction(new DocumentRunnable(editor.getDocument(),editor.getProject()) {
@Override
public void run() {
editor.getDocument().deleteString(start, end);
}
});
}
}
@Nullable
private static ExpressionInfo getExpressionInfo(final XDebuggerEvaluator evaluator,
final Project project,
final ValueHintType type,
final Editor editor,
final int offset) {
SelectionModel selectionModel = editor.getSelectionModel();
int selectionStart = selectionModel.getSelectionStart();
int selectionEnd = selectionModel.getSelectionEnd();
if ((type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT) &&
selectionModel.hasSelection() &&
selectionStart <= offset &&
offset <= selectionEnd) {
return new ExpressionInfo(new TextRange(selectionStart, selectionEnd));
}
return evaluator.getExpressionInfoAtOffset(project, editor.getDocument(), offset,
type == ValueHintType.MOUSE_CLICK_HINT || type == ValueHintType.MOUSE_ALT_OVER_HINT);
}
private static void handleNoUsageTargets(PsiFile file,
@Nonnull Editor editor,
SelectionModel selectionModel,
@Nonnull Project project) {
if (file.findElementAt(editor.getCaretModel().getOffset()) instanceof PsiWhiteSpace) return;
selectionModel.selectWordAtCaret(false);
String selection = selectionModel.getSelectedText();
LOG.assertTrue(selection != null);
for (int i = 0; i < selection.length(); i++) {
if (!Character.isJavaIdentifierPart(selection.charAt(i))) {
selectionModel.removeSelection();
}
}
doRangeHighlighting(editor, project);
selectionModel.removeSelection();
}
@Override
public void execute(Editor editor, DataContext dataContext) {
TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
if (templateState != null && !templateState.isFinished()) {
SelectionModel selectionModel = editor.getSelectionModel();
LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
// the idea behind lookup checking is that if there is a preselected value in lookup
// then user might want just to close lookup but not finish a template.
// E.g. user wants to move to the next template segment by Tab without completion invocation.
// If there is no selected value in completion that user definitely wants to finish template
boolean lookupIsEmpty = lookup == null || lookup.getCurrentItem() == null;
if (!selectionModel.hasSelection() && lookupIsEmpty) {
CommandProcessor.getInstance().setCurrentCommandName(CodeInsightBundle.message("finish.template.command"));
templateState.gotoEnd(true);
return;
}
}
if (myOriginalHandler.isEnabled(editor, dataContext)) {
myOriginalHandler.execute(editor, dataContext);
}
}
@Nullable
private static String getSingleLineSelection(@Nonnull Editor editor) {
final SelectionModel model = editor.getSelectionModel();
final Document document = editor.getDocument();
if (!model.hasSelection()) {
final int offset = editor.getCaretModel().getOffset();
if (offset <= document.getTextLength()) {
final int lineNumber = document.getLineNumber(offset);
final String line = document.getText().substring(document.getLineStartOffset(lineNumber), document.getLineEndOffset(lineNumber)).trim();
if (StringUtil.isNotEmpty(line)) {
return line;
}
}
return null;
}
final int start = model.getSelectionStart();
final int end = model.getSelectionEnd();
if (document.getLineNumber(start) == document.getLineNumber(end)) {
final String selection = document.getText().substring(start, end).trim();
if (StringUtil.isNotEmpty(selection)) {
return selection;
}
}
return null;
}
private void performReplaceAll(Editor e) {
Project project = mySearchResults.getProject();
if (!ReadonlyStatusHandler.ensureDocumentWritable(project, e.getDocument())) {
return;
}
if (mySearchResults.getFindModel() != null) {
final FindModel copy = new FindModel();
copy.copyFrom(mySearchResults.getFindModel());
final SelectionModel selectionModel = mySearchResults.getEditor().getSelectionModel();
final int offset;
if (!selectionModel.hasSelection() || copy.isGlobal()) {
copy.setGlobal(true);
offset = 0;
}
else {
offset = selectionModel.getBlockSelectionStarts()[0];
}
FindUtil.replace(project, e, offset, copy, this);
}
}
@Override
public void execute(Editor editor, DataContext dataContext) {
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
final TemplateState state = TemplateManagerImpl.getTemplateState(editor);
if (state != null && editor.getUserData(InplaceRefactoring.INPLACE_RENAMER) != null) {
final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);
if (lookup != null) {
selectionModel.removeSelection();
lookup.hide();
return;
}
}
}
myOriginalHandler.execute(editor, dataContext);
}
@Nullable
static String makeUrlToOpen(@Nullable Editor editor,
@NotNull String relativePath,
@NotNull String branch,
@NotNull String remoteUrl) {
final StringBuilder builder = new StringBuilder();
final String repoUrl = GitlabUrlUtil.makeRepoUrlFromRemoteUrl(remoteUrl);
if (repoUrl == null) {
return null;
}
builder.append(repoUrl).append("/blob/").append(branch).append(relativePath);
if (editor != null && editor.getDocument().getLineCount() >= 1) {
// lines are counted internally from 0, but from 1 on gitlab
SelectionModel selectionModel = editor.getSelectionModel();
final int begin = editor.getDocument().getLineNumber(selectionModel.getSelectionStart()) + 1;
final int selectionEnd = selectionModel.getSelectionEnd();
int end = editor.getDocument().getLineNumber(selectionEnd) + 1;
if (editor.getDocument().getLineStartOffset(end - 1) == selectionEnd) {
end -= 1;
}
builder.append("#L").append(begin).append('-').append(end);
}
return builder.toString();
}
/**
* Reformat the text currently selected in the editor
*/
public void reformatSelection() {
pool(() -> {
if (editor.isDisposed()) {
return;
}
DocumentRangeFormattingParams params = new DocumentRangeFormattingParams();
params.setTextDocument(identifier);
SelectionModel selectionModel = editor.getSelectionModel();
int start = computableReadAction(selectionModel::getSelectionStart);
int end = computableReadAction(selectionModel::getSelectionEnd);
Position startingPos = DocumentUtils.offsetToLSPPos(editor, start);
Position endPos = DocumentUtils.offsetToLSPPos(editor, end);
params.setRange(new Range(startingPos, endPos));
// Todo - Make Formatting Options configurable
FormattingOptions options = new FormattingOptions();
params.setOptions(options);
CompletableFuture<List<? extends TextEdit>> request = requestManager.rangeFormatting(params);
if (request == null) {
return;
}
request.thenAccept(formatting -> {
if (formatting == null) {
return;
}
invokeLater(() -> {
if (!editor.isDisposed()) {
applyEdit((List<TextEdit>) formatting, "Reformat selection", false);
}
});
});
});
}
/**
* Returns the selected text if there is any selection. If not return all based on parameter
*
* @param defaultToAll If no selection, then this decides whether to return all text
*/
String getSelectedText(boolean defaultToAll) {
ConsoleView console = this.getConsole();
Editor myEditor = console != null ? (Editor) CommonDataKeys.EDITOR.getData((DataProvider) console) : null;
if (myEditor != null) {
Document document = myEditor.getDocument();
final SelectionModel selectionModel = myEditor.getSelectionModel();
if (selectionModel.hasSelection()) {
return selectionModel.getSelectedText();
} else if (defaultToAll) {
return document.getText();
}
}
return null;
}
@NotNull
@Override
public String preprocessOnPaste(
Project project, PsiFile psiFile, Editor editor, String text, RawText rawText) {
if (!(psiFile instanceof BuckFile)) {
return text;
}
final Document document = editor.getDocument();
PsiDocumentManager.getInstance(project).commitDocument(document);
final SelectionModel selectionModel = editor.getSelectionModel();
// Pastes in block selection mode (column mode) are not handled by a CopyPasteProcessor.
final int selectionStart = selectionModel.getSelectionStart();
final PsiElement element = psiFile.findElementAt(selectionStart);
if (element == null) {
return text;
}
if (BuckPsiUtils.hasElementType(
element.getNode(),
TokenType.WHITE_SPACE,
BuckTypes.SINGLE_QUOTED_STRING,
BuckTypes.DOUBLE_QUOTED_STRING)) {
PsiElement property = BuckPsiUtils.findAncestorWithType(element, BuckTypes.PROPERTY);
if (checkPropertyName(property)) {
text = buildBuckDependencyPath(element, project, text);
}
}
return text;
}
public final Pair<Integer, Integer> getLineOffSets(final Editor projectEditor,
final int distance) {
Document document = projectEditor.getDocument();
SelectionModel selectionModel = projectEditor.getSelectionModel();
int head = 0;
int tail = document.getLineCount() - 1;
if (selectionModel.hasSelection()) {
head = document.getLineNumber(selectionModel.getSelectionStart());
tail = document.getLineNumber(selectionModel.getSelectionEnd());
/*Selection model gives one more line if line is selected completely.
By Checking if complete line is slected and decreasing tail*/
if ((document.getLineStartOffset(tail) == selectionModel.getSelectionEnd())) {
tail--;
}
} else {
int currentLine = document.getLineNumber(projectEditor.getCaretModel().getOffset());
if (currentLine - distance >= 0) {
head = currentLine - distance;
}
if (currentLine + distance <= document.getLineCount() - 1) {
tail = currentLine + distance;
}
}
int start = document.getLineStartOffset(head);
int end = document.getLineEndOffset(tail);
Pair<Integer, Integer> pair = new Pair<>(start, end);
return pair;
}
private void replaceSelection(final Editor editor, final XmlOutput xmlOutput) {
final SelectionModel selectionModel = editor.getSelectionModel();
editor.getDocument()
.replaceString(selectionModel.getSelectionStart(),
selectionModel.getSelectionEnd(),
xmlOutput.getText());
editor.getSelectionModel().removeSelection();
}
@Override
protected boolean selectSomethingUnderCaret(Editor editor, DataContext dataContext, SelectionModel selectionModel) {
try {
PsiFile psiFile = PsiDocumentManager.getInstance(editor.getProject()).getPsiFile(editor.getDocument());
if (psiFile == null) {// select whole line in plaintext
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
FileType fileType = psiFile.getFileType();
boolean handled = false;
if (fileType.equals(StdFileTypes.JAVA) && isJavaInstalled()) {
handled = javaHandling(editor, dataContext, selectionModel, psiFile);
}
if (!handled && fileType.equals(StdFileTypes.PROPERTIES)) {
handled = propertiesHandling(editor, dataContext, selectionModel, psiFile);
}
if (!handled && fileType.equals(StdFileTypes.PLAIN_TEXT)) {
handled = super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
if (!handled) {
handled = genericHandling(editor, dataContext, selectionModel, psiFile);
}
return handled;
} catch (Exception e) {
LOG.error("please report this, so I can fix it :(", e);
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
}
private boolean genericHandling(Editor editor, DataContext dataContext, SelectionModel selectionModel,
PsiFile psiFile) {
int caretOffset = editor.getCaretModel().getOffset();
PsiElement elementAtCaret = PsiUtilBase.getElementAtCaret(editor);
if (elementAtCaret instanceof PsiPlainText) {
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
} else if (elementAtCaret instanceof PsiWhiteSpace) {
elementAtCaret = PsiUtilBase.getElementAtOffset(psiFile, caretOffset - 1);
}
if (elementAtCaret == null || elementAtCaret instanceof PsiWhiteSpace) {
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
} else {
TextRange textRange = elementAtCaret.getTextRange();
if (textRange.getLength() == 0) {
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
selectionModel.setSelection(textRange.getStartOffset(), textRange.getEndOffset());
String selectedText = selectionModel.getSelectedText();
if (selectedText != null && selectedText.contains("\n")) {
selectionModel.removeSelection();
return super.selectSomethingUnderCaret(editor, dataContext, selectionModel);
}
if (StringUtil.isQuoted(selectedText)) {
selectionModel.setSelection(selectionModel.getSelectionStart() + 1,
selectionModel.getSelectionEnd() - 1);
}
if (caretOffset < selectionModel.getSelectionStart()) {
editor.getCaretModel().moveToOffset(selectionModel.getSelectionStart());
}
if (caretOffset > selectionModel.getSelectionEnd()) {
editor.getCaretModel().moveToOffset(selectionModel.getSelectionEnd());
}
return true;
}
}
protected boolean selectSomethingUnderCaret(Editor editor, DataContext dataContext, SelectionModel selectionModel) {
selectionModel.selectLineAtCaret();
String selectedText = selectionModel.getSelectedText();
if (selectedText != null && selectedText.endsWith("\n")) {
selectionModel.setSelection(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd() - 1);
}
return true;
}
public RemoveEmptyLinesAction() {
super(null);
setupHandler(new EditorWriteActionHandler(true) {
@Override
public void executeWriteAction(Editor editor, DataContext dataContext) {
MyApplicationService.setAction(getActionClass());
// Column mode not supported
if (editor.isColumnMode()) {
return;
}
final SelectionModel selectionModel = editor.getSelectionModel();
if (selectionModel.hasSelection()) {
final String selectedText = selectionModel.getSelectedText();
String[] textParts = selectedText.split("\n");
Collection<String> result = new ArrayList<String>();
for (String textPart : textParts) {
if (StringUtils.isNotBlank(textPart)) {
result.add(textPart);
}
}
String[] res = result.toArray(new String[result.size()]);
final String s = StringUtils.join(res, '\n');
editor.getDocument().replaceString(selectionModel.getSelectionStart(),
selectionModel.getSelectionEnd(), s);
}
}
});
}