Java Code Examples for com.intellij.openapi.editor.SelectionModel#getSelectionEnd()

The following examples show how to use com.intellij.openapi.editor.SelectionModel#getSelectionEnd() . 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: 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 2
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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
Source File: VariableInplaceRenamer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected void beforeTemplateStart() {
  super.beforeTemplateStart();
  myLanguage = myScope.getLanguage();
  if (shouldCreateSnapshot()) {
    final ResolveSnapshotProvider resolveSnapshotProvider = INSTANCE.forLanguage(myLanguage);
    mySnapshot = resolveSnapshotProvider != null ? resolveSnapshotProvider.createSnapshot(myScope) : null;
  }

  final SelectionModel selectionModel = myEditor.getSelectionModel();
  mySelectedRange =
    selectionModel.hasSelection() ? new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()) : null;
}
 
Example 11
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 12
Source File: AbstractCaseConvertingAction.java    From StringManipulation with Apache License 2.0 5 votes vote down vote up
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;
	}
}
 
Example 13
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 14
Source File: PlainTextEditor.java    From netbeans-mmd-plugin with Apache License 2.0 4 votes vote down vote up
public String getSelectedText() {
  final SelectionModel model = Assertions.assertNotNull(this.getEditor()).getSelectionModel();
  final int start = model.getSelectionStart();
  final int end = model.getSelectionEnd();
  return getDocument().getText(new TextRange(start, end));
}
 
Example 15
Source File: VcsSelection.java    From consulo with Apache License 2.0 4 votes vote down vote up
public VcsSelection(Document document, SelectionModel selectionModel) {
  this(document, new TextRange(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd()),
       VcsBundle.message("action.name.show.history.for.selection"));
}
 
Example 16
Source File: ExtractRuleAction.java    From intellij-plugin-v4 with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
private void extractSelection(@NotNull PsiFile psiFile, Editor editor, SelectionModel selectionModel) {
	Document doc = editor.getDocument();
	String grammarText = psiFile.getText();
	ParsingResult results = ParsingUtils.parseANTLRGrammar(grammarText);
	final Parser parser = results.parser;
	final ParserRuleContext tree = (ParserRuleContext) results.tree;
	TokenStream tokens = parser.getTokenStream();

	int selStart = selectionModel.getSelectionStart();
	int selStop = selectionModel.getSelectionEnd() - 1; // I'm inclusive and they are exclusive for end offset

	// find appropriate tokens for bounds, don't include WS
	Token start = RefactorUtils.getTokenForCharIndex(tokens, selStart);
	Token stop = RefactorUtils.getTokenForCharIndex(tokens, selStop);
	if ( start==null || stop==null ) {
		return;
	}
	if ( start.getType()==ANTLRv4Lexer.WS ) {
		start = tokens.get(start.getTokenIndex() + 1);
	}
	if ( stop.getType()==ANTLRv4Lexer.WS ) {
		stop = tokens.get(stop.getTokenIndex() - 1);
	}

	selectionModel.setSelection(start.getStartIndex(), stop.getStopIndex() + 1);
	final Project project = psiFile.getProject();
	final ChooseExtractedRuleName nameChooser = new ChooseExtractedRuleName(project);
	nameChooser.show();
	if ( nameChooser.ruleName==null ) return;

	// make new rule string
	final String ruleText = selectionModel.getSelectedText();

	final int insertionPoint = RefactorUtils.getCharIndexOfNextRuleStart(tree, start.getTokenIndex());
	final String newRule = "\n" + nameChooser.ruleName + " : " + ruleText + " ;" + "\n";

	runWriteCommandAction(project, () -> {
		// do all as one operation.
		if ( insertionPoint >= doc.getTextLength() ) {
			doc.insertString(doc.getTextLength(), newRule);
		} else {
			doc.insertString(insertionPoint, newRule);
		}
		doc.replaceString(selectionModel.getSelectionStart(), selectionModel.getSelectionEnd(), nameChooser.ruleName);
	});

	// TODO: only allow selection of fully-formed syntactic entity.
	// E.g., "A (',' A" is invalid grammatically as a rule.
}
 
Example 17
Source File: SelectionBasedPsiElementInternalAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Nullable
protected T getElementFromSelection(@Nonnull PsiFile file, @Nonnull SelectionModel selectionModel) {
  final int selectionStart = selectionModel.getSelectionStart();
  final int selectionEnd = selectionModel.getSelectionEnd();
  return PsiTreeUtil.findElementOfClassAtRange(file, selectionStart, selectionEnd, myClass);
}