Java Code Examples for com.intellij.openapi.editor.Editor#getSelectionModel()

The following examples show how to use com.intellij.openapi.editor.Editor#getSelectionModel() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 11
Source File: EditorDocOps.java    From KodeBeagle with Apache License 2.0 5 votes vote down vote up
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;
}
 
Example 12
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;
}
 
Example 13
Source File: BuckCopyPasteProcessor.java    From Buck-IntelliJ-Plugin with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example 14
Source File: EditorAPI.java    From saros with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns the current selection in the given editor.
 *
 * @param editor the editor to get the selection for
 * @return the current selection in the given editor
 */
@NotNull
static TextSelection getSelection(@NotNull Editor editor) {
  SelectionModel selectionModel = editor.getSelectionModel();

  int selectionStart = selectionModel.getSelectionStart();
  int selectionEnd = selectionModel.getSelectionEnd();

  return calculateSelectionPosition(editor, selectionStart, selectionEnd);
}
 
Example 15
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 16
Source File: ExtractToFlowAction.java    From mule-intellij-plugins with Apache License 2.0 5 votes vote down vote up
@Override
public void update(AnActionEvent anActionEvent)
{
    //final VirtualFile file = CommonDataKeys.VIRTUAL_FILE.getData(anActionEvent.getDataContext());
    final PsiFile psiFile = anActionEvent.getData(CommonDataKeys.PSI_FILE);
    final Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);

    boolean inMuleFlow = false;

    if (psiFile != null)
    {
        PsiElement muleFlowTagElement = null;
        XmlTag muleFlowTag = null;

        if (editor != null && editor.getSelectionModel() != null && editor.getSelectionModel().hasSelection()) {
            PsiElement startPsi = psiFile.findElementAt(editor.getSelectionModel().getSelectionStart());
            PsiElement endPsi = psiFile.findElementAt(editor.getSelectionModel().getSelectionEnd());

            muleFlowTagElement = PsiTreeUtil.findCommonParent(startPsi, endPsi);
        } else {//Just find element under the caret
            muleFlowTagElement = anActionEvent.getData(LangDataKeys.PSI_ELEMENT);
        }

        if (muleFlowTagElement != null && muleFlowTagElement instanceof XmlTag) {
            muleFlowTag = (XmlTag)muleFlowTagElement;
        } else {
            muleFlowTag = PsiTreeUtil.getParentOfType(muleFlowTagElement, XmlTag.class);
        }

        inMuleFlow = MuleConfigUtils.isInTopLevelTag(muleFlowTag);
    }

    anActionEvent.getPresentation().setEnabled(inMuleFlow);
    anActionEvent.getPresentation().setVisible(inMuleFlow);
}
 
Example 17
Source File: NameSuggestionsField.java    From consulo with Apache License 2.0 5 votes vote down vote up
public NameSuggestionsField(final String[] suggestedNames, final Project project, final FileType fileType, @Nullable final Editor editor) {
  this(suggestedNames, project, fileType);
  if (editor == null) return;
  // later here because EditorTextField creates Editor during addNotify()
  final Runnable selectionRunnable = new Runnable() {
    @Override
    public void run() {
      final int offset = editor.getCaretModel().getOffset();
      List<TextRange> ranges = new ArrayList<TextRange>();
      SelectWordUtil.addWordSelection(editor.getSettings().isCamelWords(), editor.getDocument().getCharsSequence(), offset, ranges);
      Editor myEditor = getEditor();
      if (myEditor == null) return;
      for (TextRange wordRange : ranges) {
        String word = editor.getDocument().getText(wordRange);
        if (!word.equals(getEnteredName())) continue;
        final SelectionModel selectionModel = editor.getSelectionModel();
        myEditor.getSelectionModel().removeSelection();
        final int wordRangeStartOffset = wordRange.getStartOffset();
        int myOffset = offset - wordRangeStartOffset;
        myEditor.getCaretModel().moveToOffset(myOffset);
        TextRange selected = new TextRange(Math.max(0, selectionModel.getSelectionStart() - wordRangeStartOffset),
                                           Math.max(0, selectionModel.getSelectionEnd() - wordRangeStartOffset));
        selected = selected.intersection(new TextRange(0, myEditor.getDocument().getTextLength()));
        if (selectionModel.hasSelection() && selected != null && !selected.isEmpty()) {
          myEditor.getSelectionModel().setSelection(selected.getStartOffset(), selected.getEndOffset());
        }
        else if (shouldSelectAll()) {
          myEditor.getSelectionModel().setSelection(0, myEditor.getDocument().getTextLength());
        }
        break;
      }
    }
  };
  SwingUtilities.invokeLater(selectionRunnable);
}
 
Example 18
Source File: LogView.java    From logviewer with Apache License 2.0 5 votes vote down vote up
/**
 * 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;
}
 
Example 19
Source File: CustomTemplateCallback.java    From consulo with Apache License 2.0 4 votes vote down vote up
public static int getOffset(@Nonnull Editor editor) {
  SelectionModel selectionModel = editor.getSelectionModel();
  return selectionModel.hasSelection() ? selectionModel.getSelectionStart() : Math.max(editor.getCaretModel().getOffset() - 1, 0);
}
 
Example 20
Source File: HaxeIntroduceHandler.java    From intellij-haxe with Apache License 2.0 4 votes vote down vote up
protected void performAction(HaxeIntroduceOperation operation) {
  final PsiFile file = operation.getFile();
  if (!CommonRefactoringUtil.checkReadOnlyStatus(file)) {
    return;
  }
  final Editor editor = operation.getEditor();
  if (editor.getSettings().isVariableInplaceRenameEnabled()) {
    final TemplateState templateState = TemplateManagerImpl.getTemplateState(operation.getEditor());
    if (templateState != null && !templateState.isFinished()) {
      return;
    }
  }

  PsiElement element1 = null;
  PsiElement element2 = null;
  final SelectionModel selectionModel = editor.getSelectionModel();
  if (selectionModel.hasSelection()) {
    element1 = file.findElementAt(selectionModel.getSelectionStart());
    element2 = file.findElementAt(selectionModel.getSelectionEnd() - 1);
  }
  else {
    if (smartIntroduce(operation)) {
      return;
    }
    final CaretModel caretModel = editor.getCaretModel();
    final Document document = editor.getDocument();
    int lineNumber = document.getLineNumber(caretModel.getOffset());
    if ((lineNumber >= 0) && (lineNumber < document.getLineCount())) {
      element1 = file.findElementAt(document.getLineStartOffset(lineNumber));
      element2 = file.findElementAt(document.getLineEndOffset(lineNumber) - 1);
    }
  }
  if (element1 instanceof PsiWhiteSpace) {
    int startOffset = element1.getTextRange().getEndOffset();
    element1 = file.findElementAt(startOffset);
  }
  if (element2 instanceof PsiWhiteSpace) {
    int endOffset = element2.getTextRange().getStartOffset();
    element2 = file.findElementAt(endOffset - 1);
  }


  final Project project = operation.getProject();
  if (element1 == null || element2 == null) {
    showCannotPerformError(project, editor);
    return;
  }

  element1 = HaxeRefactoringUtil.getSelectedExpression(project, file, element1, element2);
  if (!isValidForExtraction(element1)) {
    showCannotPerformError(project, editor);
    return;
  }

  if (!checkIntroduceContext(file, editor, element1)) {
    return;
  }
  operation.setElement(element1);
  performActionOnElement(operation);
}