com.intellij.openapi.editor.EditorModificationUtil Java Examples

The following examples show how to use com.intellij.openapi.editor.EditorModificationUtil. 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: JsonInsertFieldHandler.java    From intellij-swagger with MIT License 6 votes vote down vote up
@Override
public void handleInsert(
    final InsertionContext insertionContext, final LookupElement lookupElement) {
  handleStartingQuote(insertionContext, lookupElement);
  handleEndingQuote(insertionContext);

  if (!StringUtils.nextCharAfterSpacesAndQuotesIsColon(
      getStringAfterAutoCompletedValue(insertionContext))) {
    final String suffixWithCaret =
        field.getJsonPlaceholderSuffix(getIndentation(insertionContext, lookupElement));
    final String suffixWithoutCaret = suffixWithCaret.replace(CARET, "");
    EditorModificationUtil.insertStringAtCaret(
        insertionContext.getEditor(),
        withOptionalComma(suffixWithoutCaret, insertionContext),
        false,
        true,
        getCaretIndex(suffixWithCaret));
  }
}
 
Example #2
Source File: PhpClassInsertHandler.java    From intellij-latte with MIT License 6 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	// for removing first `\` (because class completion is triggered if prev element is `\` and PHP completion adding `\` before)
	super.handleInsert(context, lookupElement);

	PsiElement prev = context.getFile().findElementAt(context.getStartOffset() - 1);
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	String prevText = prev != null ? prev.getText() : null;
	String text = element != null ? element.getText() : null;
	if (prevText == null || text == null || (prevText.startsWith("\\") && !text.startsWith("\\"))) {
		return;
	}
	LattePhpClassUsage classUsage = element.getParent() instanceof LattePhpClassUsage ? (LattePhpClassUsage) element.getParent() : null;
	String[] className = (classUsage != null ? classUsage.getClassName() : "").split("\\\\");

	if ((prevText.length() > 0 || className.length > 1) && element.getNode().getElementType() == LatteTypes.T_PHP_NAMESPACE_RESOLUTION) {
		Editor editor = context.getEditor();
		CaretModel caretModel = editor.getCaretModel();
		int offset = caretModel.getOffset();
		caretModel.moveToOffset(element.getTextOffset());
		editor.getSelectionModel().setSelection(element.getTextOffset(), element.getTextOffset() + 1);
		EditorModificationUtil.deleteSelectedText(editor);
		caretModel.moveToOffset(offset - 1);
		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example #3
Source File: AddColonSpaceInsertHandler.java    From js-graphql-intellij-plugin with MIT License 6 votes vote down vote up
public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  char completionChar = context.getCompletionChar();
  if (completionChar == ' ' || StringUtil.containsChar(myIgnoreOnChars, completionChar)) return;
  Project project = editor.getProject();
  if (project != null) {
    if (!isCharAtColon(editor)) {
      EditorModificationUtil.insertStringAtCaret(editor, ": ");
      PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    } else {
      editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 2);
    }
    if (myTriggerAutoPopup) {
      AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
    }
  }
}
 
Example #4
Source File: XQueryXmlGtTypedHandler.java    From intellij-xquery with Apache License 2.0 6 votes vote down vote up
@Override
public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && c == '>') {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        final int offset = editor.getCaretModel().getOffset();
        FileViewProvider provider = file.getViewProvider();
        PsiElement element = provider.findElementAt(offset, XQueryLanguage.class);

        if (element != null && element.getNode() != null && (
                element.getNode().getElementType() == XQueryTypes.XMLTAGEND ||
                        element.getNode().getElementType() == XQueryTypes.XMLEMPTYELEMENTEND)) {
            EditorModificationUtil.moveCaretRelatively(editor, 1);
            editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
            return Result.STOP;
        }
    }
    return Result.CONTINUE;
}
 
Example #5
Source File: CutAfterJumpCommand.java    From emacsIDEAs with Apache License 2.0 6 votes vote down vote up
@Override
public void afterJump() {
    final Runnable runnable = new Runnable() {
        @Override
        public void run() {
            if (inSameEditor()) {
                selectJumpArea();

                _se.getSelectionModel().copySelectionToClipboard();
                EditorModificationUtil.deleteSelectedText(_se);
                _se.getSelectionModel().removeSelection();
            }
        }
    };

    AppUtil.runWriteAction(runnable, _se);
}
 
Example #6
Source File: DeleteSelectionHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredWriteAction
@Override
public void executeWriteAction(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  if (caret == null ? editor.getSelectionModel().hasSelection(true) : caret.hasSelection()) {
    EditorUIUtil.hideCursorInEditor(editor);
    CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
    CopyPasteManager.getInstance().stopKillRings();
    CaretAction action = c -> EditorModificationUtil.deleteSelectedText(editor);
    if (caret == null) {
      editor.getCaretModel().runForEachCaret(action);
    }
    else {
      action.perform(caret);
    }
  }
  else {
    myOriginalHandler.execute(editor, caret, dataContext);
  }
}
 
Example #7
Source File: CodeInsightAction.java    From consulo with Apache License 2.0 6 votes vote down vote up
@RequiredUIAccess
public void actionPerformedImpl(@Nonnull final Project project, final Editor editor) {
  if (editor == null) return;
  //final PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  final PsiFile psiFile = PsiUtilBase.getPsiFileInEditor(editor, project);
  if (psiFile == null) return;
  final CodeInsightActionHandler handler = getHandler();
  PsiElement elementToMakeWritable = handler.getElementToMakeWritable(psiFile);
  if (elementToMakeWritable != null && !(EditorModificationUtil.checkModificationAllowed(editor) && FileModificationService.getInstance().preparePsiElementsForWrite(elementToMakeWritable))) {
    return;
  }

  CommandProcessor.getInstance().executeCommand(project, () -> {
    final Runnable action = () -> {
      if (!ApplicationManager.getApplication().isHeadlessEnvironment() && !editor.getContentComponent().isShowing()) return;
      handler.invoke(project, editor, psiFile);
    };
    if (handler.startInWriteAction()) {
      ApplicationManager.getApplication().runWriteAction(action);
    }
    else {
      action.run();
    }
  }, getCommandName(), DocCommandGroupId.noneGroupId(editor.getDocument()), editor.getDocument());
}
 
Example #8
Source File: AddSpaceInsertHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void handleInsert(InsertionContext context, LookupElement item) {
  Editor editor = context.getEditor();
  char completionChar = context.getCompletionChar();
  if (completionChar == ' ' || StringUtil.containsChar(myIgnoreOnChars, completionChar)) return;
  Project project = editor.getProject();
  if (project != null) {
    if (!isCharAtSpace(editor)) {
      EditorModificationUtil.insertStringAtCaret(editor, " ");
      PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
    }
    else if (shouldOverwriteExistingSpace(editor)) {
      editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() + 1);
    }
    if (myTriggerAutoPopup) {
      AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
    }
  }
}
 
Example #9
Source File: CompletionAutoPopupHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public Result checkAutoPopup(char charTyped, @Nonnull final Project project, @Nonnull final Editor editor, @Nonnull final PsiFile file) {
  LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(editor);

  if (LOG.isDebugEnabled()) {
    LOG.debug("checkAutoPopup: character=" + charTyped + ";");
    LOG.debug("phase=" + CompletionServiceImpl.getCompletionPhase());
    LOG.debug("lookup=" + lookup);
    LOG.debug("currentCompletion=" + CompletionServiceImpl.getCompletionService().getCurrentCompletion());
  }

  if (lookup != null) {
    if (editor.getSelectionModel().hasSelection()) {
      lookup.performGuardedChange(() -> EditorModificationUtil.deleteSelectedText(editor));
    }
    return Result.STOP;
  }

  if (Character.isLetterOrDigit(charTyped) || charTyped == '_') {
    AutoPopupController.getInstance(project).scheduleAutoPopup(editor);
    return Result.STOP;
  }

  return Result.CONTINUE;
}
 
Example #10
Source File: TemplateLineStartEndHandler.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
protected void doExecute(Editor editor, @Nullable Caret caret, DataContext dataContext) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null && !templateState.isFinished()) {
    final TextRange range = templateState.getCurrentVariableRange();
    final int caretOffset = editor.getCaretModel().getOffset();
    if (range != null && shouldStayInsideVariable(range, caretOffset)) {
      int selectionOffset = editor.getSelectionModel().getLeadSelectionOffset();
      int offsetToMove = myIsHomeHandler ? range.getStartOffset() : range.getEndOffset();
      LogicalPosition logicalPosition = editor.offsetToLogicalPosition(offsetToMove).leanForward(myIsHomeHandler);
      editor.getCaretModel().moveToLogicalPosition(logicalPosition);
      EditorModificationUtil.scrollToCaret(editor);
      if (myWithSelection) {
        editor.getSelectionModel().setSelection(selectionOffset, offsetToMove);
      }
      else {
        editor.getSelectionModel().removeSelection();
      }
      return;
    }
  }
  myOriginalHandler.execute(editor, caret, dataContext);
}
 
Example #11
Source File: LookupImpl.java    From consulo with Apache License 2.0 6 votes vote down vote up
public void replacePrefix(final String presentPrefix, final String newPrefix) {
  if (!performGuardedChange(() -> {
    EditorModificationUtil.deleteSelectedText(myEditor);
    int offset = myEditor.getCaretModel().getOffset();
    final int start = offset - presentPrefix.length();
    myEditor.getDocument().replaceString(start, offset, newPrefix);
    myOffsets.clearAdditionalPrefix();
    myEditor.getCaretModel().moveToOffset(start + newPrefix.length());
  })) {
    return;
  }
  withLock(() -> {
    myPresentableArranger.prefixReplaced(this, newPrefix);
    return null;
  });
  refreshUi(true, true);
}
 
Example #12
Source File: PasteReferenceProvider.java    From consulo with Apache License 2.0 6 votes vote down vote up
private static void insert(final String fqn, final PsiElement element, final Editor editor, final QualifiedNameProvider provider) {
  final Project project = editor.getProject();
  if (project == null) return;

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

  final PsiFile file = documentManager.getPsiFile(editor.getDocument());
  if (!FileModificationService.getInstance().prepareFileForWrite(file)) return;

  CommandProcessor.getInstance().executeCommand(project, () -> ApplicationManager.getApplication().runWriteAction(() -> {
    Document document = editor.getDocument();
    documentManager.doPostponedOperationsAndUnblockDocument(document);
    documentManager.commitDocument(document);
    EditorModificationUtil.deleteSelectedText(editor);
    provider.insertQualifiedName(fqn, element, editor, project);
  }), IdeBundle.message("command.pasting.reference"), null);
}
 
Example #13
Source File: BackspaceHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void deleteToTargetPosition(@Nonnull Editor editor, @Nonnull LogicalPosition pos) {
  final int offset = editor.getCaretModel().getOffset();
  final int targetOffset = editor.logicalPositionToOffset(pos);
  editor.getSelectionModel().setSelection(targetOffset, offset);
  EditorModificationUtil.deleteSelectedText(editor);
  editor.getCaretModel().moveToLogicalPosition(pos);
}
 
Example #14
Source File: TemplateExpressionLookupElement.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static boolean handleCompletionChar(InsertionContext context) {
  if (context.getCompletionChar() == '.') {
    EditorModificationUtil.insertStringAtCaret(context.getEditor(), ".");
    AutoPopupController.getInstance(context.getProject()).autoPopupMemberLookup(context.getEditor(), null);
    return false;
  }
  return true;
}
 
Example #15
Source File: TemplateManagerImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
private void startTemplate(final Editor editor,
                           final String selectionString,
                           final Template template,
                           boolean inSeparateCommand,
                           TemplateEditingListener listener,
                           final PairProcessor<String, String> processor,
                           final Map<String, String> predefinedVarValues) {
  final TemplateState templateState = initTemplateState(editor);

  //noinspection unchecked
  templateState.getProperties().put(ExpressionContext.SELECTION, selectionString);

  if (listener != null) {
    templateState.addTemplateStateListener(listener);
  }
  Runnable r = () -> {
    if (selectionString != null) {
      ApplicationManager.getApplication().runWriteAction(() -> EditorModificationUtil.deleteSelectedText(editor));
    }
    else {
      editor.getSelectionModel().removeSelection();
    }
    templateState.start((TemplateImpl)template, processor, predefinedVarValues);
  };
  if (inSeparateCommand) {
    CommandProcessor.getInstance().executeCommand(myProject, r, CodeInsightBundle.message("insert.code.template.command"), null);
  }
  else {
    r.run();
  }

  if (shouldSkipInTests()) {
    if (!templateState.isFinished()) templateState.gotoEnd(false);
  }
}
 
Example #16
Source File: FunctionDeclarationBracesBodyHandler.java    From intellij-xquery with Apache License 2.0 5 votes vote down vote up
@Override
public Result charTyped(char c, Project project, @NotNull Editor editor, @NotNull PsiFile editedFile) {
    if ((editedFile.getLanguage() instanceof XQueryLanguage) && (c == '{' || c == '}')) {
        PsiDocumentManager.getInstance(project).commitAllDocuments();
        PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
        if (file == null) return Result.CONTINUE;
        FileViewProvider provider = file.getViewProvider();
        final int offset = editor.getCaretModel().getOffset();
        PsiElement element = provider.findElementAt(offset - 1, XQueryLanguage.class);
        if (element == null) return Result.CONTINUE;
        if (!(element.getLanguage() instanceof XQueryLanguage)) return Result.CONTINUE;
        ASTNode prevLeaf = element.getNode();
        if (prevLeaf == null) return Result.CONTINUE;
        final String prevLeafText = prevLeaf.getText();

        if (isInFunctionBodyAfterInsertionOfMatchingRightBrace(element, prevLeafText)) {
            if (c == '{') {
                editor.getDocument().insertString(offset + 1, ";");
            } else {
                EditorModificationUtil.insertStringAtCaret(editor, ";", false);
            }
        }

    }

    return Result.CONTINUE;
}
 
Example #17
Source File: LookupImpl.java    From consulo with Apache License 2.0 5 votes vote down vote up
public static void insertLookupString(final Project project, Editor editor, LookupElement item, PrefixMatcher matcher, String itemPattern, final int prefixLength) {
  final String lookupString = getCaseCorrectedLookupString(item, matcher, itemPattern);

  final Editor hostEditor = editor;
  hostEditor.getCaretModel().runForEachCaret(__ -> {
    EditorModificationUtil.deleteSelectedText(hostEditor);
    final int caretOffset = hostEditor.getCaretModel().getOffset();

    int offset = insertLookupInDocumentWindowIfNeeded(project, editor, caretOffset, prefixLength, lookupString);
    hostEditor.getCaretModel().moveToOffset(offset);
    hostEditor.getSelectionModel().removeSelection();
  });

  editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
}
 
Example #18
Source File: CopyCutWithoutSelectAction.java    From emacsIDEAs with Apache License 2.0 5 votes vote down vote up
private void cutSelection() {
    Runnable cutRunnable = new Runnable() {
        @Override
        public void run() {
            _editor.getSelectionModel().copySelectionToClipboard();
            EditorModificationUtil.deleteSelectedText(_editor);
        }
    };

    AppUtil.runWriteAction(cutRunnable, _editor);
}
 
Example #19
Source File: JustOneSpace.java    From emacsIDEAs with Apache License 2.0 5 votes vote down vote up
private void makeOneSpaceBetween(final int begin, final int end) {
    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            _editor.getSelectionModel().setSelection(begin, end);
            EditorModificationUtil.deleteSelectedText(_editor);
            EditorModificationUtil.insertStringAtCaret(_editor, " ");
        }
    };
    AppUtil.runWriteAction(runnable, _editor);
}
 
Example #20
Source File: LookupTypedHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(@Nonnull Editor originalEditor, char charTyped, @Nonnull DataContext dataContext) {
  final Project project = dataContext.getData(CommonDataKeys.PROJECT);
  PsiFile file = project == null ? null : PsiUtilBase.getPsiFileInEditor(originalEditor, project);

  if (file == null) {
    if (myOriginalHandler != null) {
      myOriginalHandler.execute(originalEditor, charTyped, dataContext);
    }
    return;
  }

  if (!EditorModificationUtil.checkModificationAllowed(originalEditor)) {
    return;
  }

  CompletionPhase oldPhase = CompletionServiceImpl.getCompletionPhase();
  if (oldPhase instanceof CompletionPhase.CommittingDocuments && oldPhase.indicator != null) {
    oldPhase.indicator.scheduleRestart();
  }

  Editor editor = TypedHandler.injectedEditorIfCharTypedIsSignificant(charTyped, originalEditor, file);
  if (editor != originalEditor) {
    file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
  }

  if (originalEditor.isInsertMode() && beforeCharTyped(charTyped, project, originalEditor, editor, file)) {
    return;
  }

  if (myOriginalHandler != null) {
    myOriginalHandler.execute(originalEditor, charTyped, dataContext);
  }
}
 
Example #21
Source File: EditorEventManager.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("WeakerAccess")
public void prepareAndRunSnippet(String insertText) {

    List<SnippetVariable> variables = new ArrayList<>();
    // Extracts variables using placeholder REGEX pattern.
    Matcher varMatcher = Pattern.compile(SNIPPET_PLACEHOLDER_REGEX).matcher(insertText);
    while (varMatcher.find()) {
        variables.add(new SnippetVariable(varMatcher.group(), varMatcher.start(), varMatcher.end()));
    }

    variables.sort(Comparator.comparingInt(o -> o.startIndex));
    final String[] finalInsertText = {insertText};
    variables.forEach(var -> finalInsertText[0] = finalInsertText[0].replace(var.lspSnippetText, "$"));

    String[] splitInsertText = finalInsertText[0].split("\\$");
    finalInsertText[0] = String.join("", splitInsertText);

    TemplateImpl template = (TemplateImpl) TemplateManager.getInstance(getProject()).createTemplate(finalInsertText[0],
            "lsp4intellij");
    template.parseSegments();

    final int[] varIndex = {0};
    variables.forEach(var -> {
        template.addTextSegment(splitInsertText[varIndex[0]]);
        template.addVariable(varIndex[0] + "_" + var.variableValue, new TextExpression(var.variableValue),
                new TextExpression(var.variableValue), true, false);
        varIndex[0]++;
    });
    // If the snippet text ends with a placeholder, there will be no string segment left to append after the last
    // variable.
    if (splitInsertText.length != variables.size()) {
        template.addTextSegment(splitInsertText[splitInsertText.length - 1]);
    }
    template.setInline(true);
    EditorModificationUtil.moveCaretRelatively(editor, -template.getTemplateText().length());
    TemplateManager.getInstance(getProject()).startTemplate(editor, template);
}
 
Example #22
Source File: BaseRefactorHandler.java    From lombok-intellij-plugin with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
@Override
public void run() {
  if (!EditorModificationUtil.checkModificationAllowed(editor)) {
    return;
  }
  if (!FileDocumentManager.getInstance().requestWriting(editor.getDocument(), project)) {
    return;
  }

  process(chooser.getSelectedElements());
}
 
Example #23
Source File: FilterInsertHandler.java    From intellij-latte with MIT License 5 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE) {
		PsiElement parent = element.getParent();

		LatteFilterSettings filter = null;
		if (parent instanceof LatteMacroModifier) {
			String modifierName = ((LatteMacroModifier) parent).getModifierName();
			filter = LatteConfiguration.getInstance(element.getProject()).getFilter(modifierName);
		}

		Editor editor = context.getEditor();
		if (filter != null && filter.getModifierInsert() != null && filter.getModifierInsert().length() > 0) {
			CaretModel caretModel = editor.getCaretModel();
			String text = editor.getDocument().getText();

			int offset = caretModel.getOffset();

			int lastBraceOffset = text.indexOf(":", offset);
			int endOfLineOffset = text.indexOf("\n", offset);

			if (endOfLineOffset == -1) {
				endOfLineOffset = text.length();
			}
			if (lastBraceOffset == -1 || lastBraceOffset > endOfLineOffset) {
				EditorModificationUtil.insertStringAtCaret(editor, filter.getModifierInsert());
				caretModel.moveToOffset(offset + 1);
			}
		}
		PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
	}
}
 
Example #24
Source File: PhpVariableInsertHandler.java    From intellij-latte with MIT License 5 votes vote down vote up
public void handleInsert(@NotNull InsertionContext context, @NotNull LookupElement lookupElement) {
	PsiElement element = context.getFile().findElementAt(context.getStartOffset());
	if (element != null && element.getLanguage() == LatteLanguage.INSTANCE) {
		PsiElement parent = element.getParent();
		if (!(parent instanceof Variable) && !element.getText().startsWith("$")) {
			Editor editor = context.getEditor();
			CaretModel caretModel = editor.getCaretModel();
			int offset = caretModel.getOffset();
			caretModel.moveToOffset(element.getTextOffset() + (PhpPsiUtil.isOfType(parent, PhpElementTypes.CAST_EXPRESSION) ? 1 : 0));
			EditorModificationUtil.insertStringAtCaret(editor, "$");
			caretModel.moveToOffset(offset + 1);
			PsiDocumentManager.getInstance(context.getProject()).commitDocument(editor.getDocument());
		}
	}
}
 
Example #25
Source File: EnterInStringLiteralHandler.java    From BashSupport with Apache License 2.0 5 votes vote down vote up
@Override
public Result preprocessEnter(@NotNull PsiFile file, @NotNull Editor editor, @NotNull Ref<Integer> caretOffset, @NotNull Ref<Integer> caretAdvance, @NotNull DataContext dataContext, @Nullable EditorActionHandler originalHandler) {
    if (!(file instanceof BashFile)) {
        return Result.Continue;
    }


    int offset = caretOffset.get();

    // don't wrap at EOL or EOF
    CharSequence content = editor.getDocument().getCharsSequence();
    if (offset >= content.length() || content.charAt(offset) == '\n') {
        return Result.Continue;
    }

    if (PsiDocumentManager.getInstance(file.getProject()).isUncommited(editor.getDocument())) {
        // return early if PSI is not up-to-date to avoid blocking the editor
        // this might result in line-continuations not being inserted while editing
        return Result.Continue;
    }

    PsiElement psi = file.findElementAt(offset);
    if (psi == null || psi.getNode() == null) {
        return Result.Continue;
    }

    boolean isUserTyping = !Boolean.TRUE.equals(DataManager.getInstance().loadFromDataContext(dataContext, AutoHardWrapHandler.AUTO_WRAP_LINE_IN_PROGRESS_KEY));
    if (isUserTyping && !isInString(psi)) {
        return Result.Continue;
    }

    if (offset >= psi.getTextOffset() && psi.getNode().getElementType() != BashTokenTypes.LINE_FEED) {
        EditorModificationUtil.insertStringAtCaret(editor, "\\\n");
        return Result.Stop;
    }

    return Result.Continue;
}
 
Example #26
Source File: WriterService.java    From easy_javadoc with Apache License 2.0 5 votes vote down vote up
public void write(Project project, Editor editor, String text) {
    if (project == null || editor == null || StringUtils.isBlank(text)) {
        return;
    }
    try {
        WriteCommandAction.writeCommandAction(project).run(
            (ThrowableRunnable<Throwable>)() -> {
                int start = editor.getSelectionModel().getSelectionStart();
                EditorModificationUtil.insertStringAtCaret(editor, text);
                editor.getSelectionModel().setSelection(start, start + text.length());
            });
    } catch (Throwable throwable) {
        LOGGER.error("写入错误", throwable);
    }
}
 
Example #27
Source File: InsertToDocumentHandler.java    From markdown-image-kit with MIT License 5 votes vote down vote up
@Override
public void invoke(EventData data, Iterator<MarkdownImage> imageIterator, MarkdownImage markdownImage) {
    WriteCommandAction.runWriteCommandAction(data.getProject(),
                                             () -> EditorModificationUtil
                                                 .insertStringAtCaret(
                                                     data.getEditor(),
                                                     markdownImage.getFinalMark() + ImageContents.LINE_BREAK));
}
 
Example #28
Source File: JsxNameCompletionProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private static void insertTagNameHandler(@NotNull Project project, @NotNull InsertionContext context, @NotNull String tagName) {
    char completionChar = context.getCompletionChar();
    if (completionChar == ' ') {
        context.setAddCompletionChar(false);
    }

    Editor editor = context.getEditor();
    EditorModificationUtil.insertStringAtCaret(editor, " ></" + tagName + ">");
    editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 4 - tagName.length());

    AutoPopupController.getInstance(project).autoPopupMemberLookup(editor, null);
}
 
Example #29
Source File: FreeExpressionCompletionProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private static void insertExpression(@NotNull InsertionContext insertionContext, @NotNull LookupElement element) {
    PsiElement psiElement = element.getPsiElement();
    if (psiElement instanceof PsiLet) {
        PsiLet let = (PsiLet) psiElement;
        if (let.isFunction()) {
            insertionContext.setAddCompletionChar(false);
            Editor editor = insertionContext.getEditor();
            EditorModificationUtil.insertStringAtCaret(editor, "()");
            editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 1);
        }
    }
}
 
Example #30
Source File: JsxAttributeCompletionProvider.java    From reasonml-idea-plugin with MIT License 5 votes vote down vote up
private static void insertTagAttributeHandler(@NotNull InsertionContext context) {
    context.setAddCompletionChar(false);

    Editor editor = context.getEditor();
    EditorModificationUtil.insertStringAtCaret(editor, "=()");
    editor.getCaretModel().moveToOffset(editor.getCaretModel().getOffset() - 1);
}