com.intellij.openapi.editor.SelectionModel Java Examples

The following examples show how to use com.intellij.openapi.editor.SelectionModel. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ExtractRuleAction.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@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);
	}
}
 
Example #2
Source File: XQuickEvaluateHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #3
Source File: PlainTextEditor.java    From netbeans-mmd-plugin with Apache License 2.0 6 votes vote down vote up
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());
    }
  });
}
 
Example #4
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #5
Source File: EscapeHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #6
Source File: SearchActionBase.java    From sourcegraph-jetbrains with Apache License 2.0 6 votes vote down vote up
@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();
}
 
Example #7
Source File: GoogleTranslation.java    From GoogleTranslation with Apache License 2.0 6 votes vote down vote up
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();
}
 
Example #8
Source File: EscapeHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #9
Source File: GitLabOpenInBrowserAction.java    From IDEA-GitLab-Integration with MIT License 6 votes vote down vote up
@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();
}
 
Example #10
Source File: ReciteWords.java    From ReciteWords with MIT License 6 votes vote down vote up
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();
}
 
Example #11
Source File: StepsBuilder.java    From Intellij-Plugin with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #12
Source File: AbstractCaseConvertingAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
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;
}
 
Example #13
Source File: WrapEditorAction.java    From idea-latex with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #14
Source File: FoldLinesLikeThis.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example #15
Source File: HungryBackspaceAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #16
Source File: LivePreviewController.java    From consulo with Apache License 2.0 6 votes vote down vote up
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);
  }
}
 
Example #17
Source File: ConvertIndentsActionBase.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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"));
  }
}
 
Example #18
Source File: SwapSelectionBoundariesAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
  }
}
 
Example #19
Source File: KillRingSaveAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@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);
      }
    });
  } 
}
 
Example #20
Source File: AbstractStringManipAction.java    From StringManipulation with Apache License 2.0 6 votes vote down vote up
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);
  }
 
Example #21
Source File: WrapEditorAction.java    From idea-latex with MIT License 6 votes vote down vote up
/**
 * 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);
}
 
Example #22
Source File: AbstractRegionToKillRingTest.java    From consulo with Apache License 2.0 5 votes vote down vote up
/**
 * Checks current editor and returns tuple of <code>(selected text; text over than selected)</code>.
 * 
 * @return    tuple of <code>(selected text; text over than selected)</code>.
 */
@Nonnull
protected static Pair<String, String> parse() {
  SelectionModel selectionModel = myEditor.getSelectionModel();
  if (!selectionModel.hasSelection()) {
    return new Pair<String, String>(null, myEditor.getDocument().getText());
  }
  
  CharSequence text = myEditor.getDocument().getCharsSequence();
  String selectedText = text.subSequence(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()).toString();
  StringBuilder nonSelectedText = new StringBuilder();
  nonSelectedText.append(text.subSequence(0, selectionModel.getSelectionStart()))
    .append(text.subSequence(selectionModel.getSelectionEnd(), text.length()));
  return new Pair<String, String>(selectedText, nonSelectedText.toString());
}
 
Example #23
Source File: EditorTextFieldCellRenderer.java    From consulo with Apache License 2.0 5 votes vote down vote up
protected void setTextToEditor(String text) {
  myEditor.getMarkupModel().removeAllHighlighters();
  myEditor.getDocument().setText(text);
  ((DesktopEditorImpl)myEditor).resetSizes();
  myEditor.getHighlighter().setText(text);
  if (myTextAttributes != null) {
    myEditor.getMarkupModel().addRangeHighlighter(0, myEditor.getDocument().getTextLength(), HighlighterLayer.ADDITIONAL_SYNTAX, myTextAttributes, HighlighterTargetArea.EXACT_RANGE);
  }

  ((DesktopEditorImpl)myEditor).setPaintSelection(mySelected);
  SelectionModel selectionModel = myEditor.getSelectionModel();
  selectionModel.setSelection(0, mySelected ? myEditor.getDocument().getTextLength() : 0);
}
 
Example #24
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
/**
 * 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);
                }
            });
        });
    });
}
 
Example #25
Source File: HighlightUsagesHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void invoke(@Nonnull final Project project, @Nonnull final Editor editor, final PsiFile file) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();

  final SelectionModel selectionModel = editor.getSelectionModel();
  if (file == null && !selectionModel.hasSelection()) {
    selectionModel.selectWordAtCaret(false);
  }
  if (file == null || selectionModel.hasSelection()) {
    doRangeHighlighting(editor, project);
    return;
  }

  final HighlightUsagesHandlerBase handler = createCustomHandler(editor, file);
  if (handler != null) {
    final String featureId = handler.getFeatureId();

    if (featureId != null) {
      FeatureUsageTracker.getInstance().triggerFeatureUsed(featureId);
    }

    handler.highlightUsages();
    return;
  }

  DumbService.getInstance(project).withAlternativeResolveEnabled(() -> {
    UsageTarget[] usageTargets = getUsageTargets(editor, file);
    if (usageTargets == null) {
      handleNoUsageTargets(file, editor, selectionModel, project);
      return;
    }

    boolean clearHighlights = isClearHighlights(editor);
    for (UsageTarget target : usageTargets) {
      target.highlightUsages(file, editor, clearHighlights);
    }
  });
}
 
Example #26
Source File: CompareClipboardWithSelectionAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nonnull
private static DocumentContent createContent(@Nonnull Project project, @Nonnull Editor editor, @Nullable FileType type) {
  DocumentContent content = DiffContentFactory.getInstance().create(project, editor.getDocument(), type);

  SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection()) {
    TextRange range = new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
    content = DiffContentFactory.getInstance().createFragment(project, content, range);
  }

  return content;
}
 
Example #27
Source File: RearrangeCodeAction.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredUIAccess
@Override
public void actionPerformed(@Nonnull AnActionEvent e) {
  final Project project = e.getProject();
  if (project == null) {
    return;
  }

  final Editor editor = e.getData(CommonDataKeys.EDITOR);
  if (editor == null) {
    return;
  }

  PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
  Document document = editor.getDocument();
  documentManager.commitDocument(document);

  final PsiFile file = documentManager.getPsiFile(document);
  if (file == null) {
    return;
  }

  SelectionModel model = editor.getSelectionModel();
  if (model.hasSelection()) {
    new RearrangeCodeProcessor(file, model).run();
  }
  else {
    new RearrangeCodeProcessor(file).run();
  }
}
 
Example #28
Source File: AbstractLayoutCodeProcessor.java    From consulo with Apache License 2.0 5 votes vote down vote up
static List<TextRange> getSelectedRanges(@Nonnull SelectionModel selectionModel) {
  final List<TextRange> ranges = new SmartList<>();
  if (selectionModel.hasSelection()) {
    TextRange range = TextRange.create(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd());
    ranges.add(range);
  }
  return ranges;
}
 
Example #29
Source File: VcsSelectionUtil.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private static VcsSelection getSelectionFromEditor(VcsContext context) {
  Editor editor = context.getEditor();
  if (editor == null) return null;
  SelectionModel selectionModel = editor.getSelectionModel();
  if (!selectionModel.hasSelection()) {
    return null;
  }
  return new VcsSelection(editor.getDocument(), selectionModel);
}
 
Example #30
Source File: UnwrapDescriptorBase.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
protected PsiElement findTargetElement(Editor editor, PsiFile file) {
  int offset = editor.getCaretModel().getOffset();
  PsiElement endElement = file.findElementAt(offset);
  SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection() && selectionModel.getSelectionStart() < offset) {
    PsiElement startElement = file.findElementAt(selectionModel.getSelectionStart());
    if (startElement != null && startElement != endElement && startElement.getTextRange().getEndOffset() == offset) {
      return startElement;
    }
  }
  return endElement;
}