Java Code Examples for com.intellij.codeInsight.template.impl.TemplateManagerImpl#getTemplateState()

The following examples show how to use com.intellij.codeInsight.template.impl.TemplateManagerImpl#getTemplateState() . 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: AbstractInplaceIntroducer.java    From consulo with Apache License 2.0 6 votes vote down vote up
@Override
public void finish(boolean success) {
  myFinished = true;
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor);
  if (templateState != null) {
    myEditor.putUserData(ACTIVE_INTRODUCE, null);
  }
  if (myDocumentAdapter != null) {
    myEditor.getDocument().removeDocumentListener(myDocumentAdapter);
  }
  if (myBalloon == null) {
    releaseIfNotRestart();
  }
  super.finish(success);
  if (success) {
    PsiDocumentManager.getInstance(myProject).commitAllDocuments();
    final V variable = getVariable();
    if (variable == null) {
      return;
    }
    restoreState(variable);
  }
}
 
Example 2
Source File: EclipseCodeFormatter.java    From EclipseCodeFormatter with Apache License 2.0 6 votes vote down vote up
public void format(PsiFile psiFile, int startOffset, int endOffset) throws FileDoesNotExistsException {
	LOG.debug("#format " + startOffset + "-" + endOffset);
	boolean wholeFile = FileUtils.isWholeFile(startOffset, endOffset, psiFile.getText());
	Range range = new Range(startOffset, endOffset, wholeFile);

	final Editor editor = PsiUtilBase.findEditor(psiFile);
	if (editor != null) {
		TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
		if (templateState != null && !settings.isUseForLiveTemplates()) {
			throw new ReformatItInIntelliJ();
		}
		formatWhenEditorIsOpen(editor, range, psiFile);
	} else {
		formatWhenEditorIsClosed(range, psiFile);
	}
	               
}
 
Example 3
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 6 votes vote down vote up
private void highlightTemplateVariables(Template template, Editor topLevelEditor) {
  //add highlights
  if (myHighlighters != null) { // can be null if finish is called during testing
    Map<TextRange, TextAttributes> rangesToHighlight = new HashMap<TextRange, TextAttributes>();
    final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
    if (templateState != null) {
      EditorColorsManager colorsManager = EditorColorsManager.getInstance();
      for (int i = 0; i < templateState.getSegmentsCount(); i++) {
        final TextRange segmentOffset = templateState.getSegmentRange(i);
        final String name = template.getSegmentName(i);
        TextAttributes attributes = null;
        if (name.equals(PRIMARY_VARIABLE_NAME)) {
          attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.WRITE_SEARCH_RESULT_ATTRIBUTES);
        }
        else if (name.equals(OTHER_VARIABLE_NAME)) {
          attributes = colorsManager.getGlobalScheme().getAttributes(EditorColors.SEARCH_RESULT_ATTRIBUTES);
        }
        if (attributes == null) continue;
        rangesToHighlight.put(segmentOffset, attributes);
      }
    }
    addHighlights(rangesToHighlight, topLevelEditor, myHighlighters, HighlightManager.getInstance(myProject));
  }
}
 
Example 4
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 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) {
  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 6
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 7
Source File: MyLookupExpression.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public Result calculateResult(ExpressionContext context) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(context.getEditor());
  final TextResult insertedValue = templateState != null ? templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME) : null;
  if (insertedValue != null) {
    if (!insertedValue.getText().isEmpty()) return insertedValue;
  }
  return new TextResult(myName);
}
 
Example 8
Source File: LSPRenameHandler.java    From lsp4intellij with Apache License 2.0 5 votes vote down vote up
private InplaceRefactoring doRename(PsiElement elementToRename, Editor editor) {
    if (elementToRename instanceof PsiNameIdentifierOwner) {
        RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(elementToRename);
        if (processor.isInplaceRenameSupported()) {
            StartMarkAction startMarkAction = StartMarkAction.canStart(elementToRename.getProject());
            if (startMarkAction == null || (processor.substituteElementToRename(elementToRename, editor)
                    == elementToRename)) {
                processor.substituteElementToRename(elementToRename, editor, new Pass<PsiElement>() {
                    @Override
                    public void pass(PsiElement element) {
                        MemberInplaceRenamer renamer = createMemberRenamer(element,
                                (PsiNameIdentifierOwner) elementToRename, editor);
                        boolean startedRename = renamer.performInplaceRename();
                        if (!startedRename) {
                            performDialogRename(editor);
                        }
                    }
                });
                return null;
            }
        } else {
            InplaceRefactoring inplaceRefactoring = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER);
            if ((inplaceRefactoring instanceof MemberInplaceRenamer)) {
                TemplateState templateState = TemplateManagerImpl
                        .getTemplateState(InjectedLanguageUtil.getTopLevelEditor(editor));
                if (templateState != null) {
                    templateState.gotoEnd(true);
                }
            }
        }
    }
    performDialogRename(editor);
    return null;
}
 
Example 9
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void navigateToStarted(final Document oldDocument, final Project project, final int exitCode) {
  final PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(oldDocument);
  if (file != null) {
    final VirtualFile virtualFile = file.getVirtualFile();
    if (virtualFile != null) {
      final FileEditor[] editors = FileEditorManager.getInstance(project).getEditors(virtualFile);
      for (FileEditor editor : editors) {
        if (editor instanceof TextEditor) {
          final Editor textEditor = ((TextEditor)editor).getEditor();
          final TemplateState templateState = TemplateManagerImpl.getTemplateState(textEditor);
          if (templateState != null) {
            if (exitCode == DialogWrapper.OK_EXIT_CODE) {
              final TextRange range = templateState.getVariableRange(PRIMARY_VARIABLE_NAME);
              if (range != null) {
                new OpenFileDescriptor(project, virtualFile, range.getStartOffset()).navigate(true);
                return;
              }
            }
            else if (exitCode > 0){
              templateState.gotoEnd();
              return;
            }
          }
        }
      }
    }
  }
}
 
Example 10
Source File: InplaceVariableIntroducer.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Nullable
private LookupElement[] createLookupItems(String name, Editor editor, PsiNamedElement psiVariable) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (psiVariable != null) {
    final TextResult insertedValue =
      templateState != null ? templateState.getVariableValue(PRIMARY_VARIABLE_NAME) : null;
    if (insertedValue != null) {
      final String text = insertedValue.getText();
      if (!text.isEmpty() && !Comparing.strEqual(text, name)) {
        final LinkedHashSet<String> names = new LinkedHashSet<String>();
        names.add(text);
        for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
          final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(psiVariable, psiVariable, names);
          if (suggestedNameInfo != null &&
              provider instanceof PreferrableNameSuggestionProvider &&
              !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
            break;
          }
        }
        final LookupElement[] items = new LookupElement[names.size()];
        final Iterator<String> iterator = names.iterator();
        for (int i = 0; i < items.length; i++) {
          items[i] = LookupElementBuilder.create(iterator.next());
        }
        return items;
      }
    }
  }
  return myLookupItems;
}
 
Example 11
Source File: AbstractInplaceIntroducer.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void stopIntroduce(Editor editor) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null) {
    final Runnable runnable = new Runnable() {
      @Override
      public void run() {
        templateState.gotoEnd(true);
      }
    };
    CommandProcessor.getInstance().executeCommand(myProject, runnable, getCommandName(), getCommandName());
  }
}
 
Example 12
Source File: MemberInplaceRenameHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public InplaceRefactoring doRename(@Nonnull final PsiElement elementToRename, final Editor editor, final DataContext dataContext) {
  if (elementToRename instanceof PsiNameIdentifierOwner) {
    final RenamePsiElementProcessor processor = RenamePsiElementProcessor.forElement(elementToRename);
    if (processor.isInplaceRenameSupported()) {
      final StartMarkAction startMarkAction = StartMarkAction.canStart(elementToRename.getProject());
      if (startMarkAction == null || processor.substituteElementToRename(elementToRename, editor) == elementToRename) {
        processor.substituteElementToRename(elementToRename, editor, new Pass<PsiElement>() {
          @Override
          public void pass(PsiElement element) {
            final MemberInplaceRenamer renamer = createMemberRenamer(element, (PsiNameIdentifierOwner)elementToRename, editor);
            boolean startedRename = renamer.performInplaceRename();
            if (!startedRename) {
              performDialogRename(elementToRename, editor, dataContext);
            }
          }
        });
        return null;
      }
      else {
        final InplaceRefactoring inplaceRefactoring = editor.getUserData(InplaceRefactoring.INPLACE_RENAMER);
        if (inplaceRefactoring != null && inplaceRefactoring.getClass() == MemberInplaceRenamer.class) {
          final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(editor));
          if (templateState != null) {
            templateState.gotoEnd(true);
          }
        }
      }
    }
  }
  performDialogRename(elementToRename, editor, dataContext);
  return null;
}
 
Example 13
Source File: TemplateLineStartEndHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null && !templateState.isFinished()) {
    TextRange range = templateState.getCurrentVariableRange();
    int caretOffset = editor.getCaretModel().getOffset();
    if (range != null && range.containsOffset(caretOffset)) return true;
  }
  return myOriginalHandler.isEnabled(editor, caret, dataContext);
}
 
Example 14
Source File: EscapeHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public boolean isEnabled(Editor editor, DataContext dataContext) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null && !templateState.isFinished()) {
    return true;
  } else {
    return myOriginalHandler.isEnabled(editor, dataContext);
  }
}
 
Example 15
Source File: BaseCompleteMacro.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static void considerNextTab(Editor editor) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  if (templateState != null) {
    TextRange range = templateState.getCurrentVariableRange();
    if (range != null && range.getLength() > 0) {
      int caret = editor.getCaretModel().getOffset();
      if (caret == range.getEndOffset()) {
        templateState.nextTab();
      }
      else if (caret > range.getEndOffset()) {
        templateState.cancelTemplate();
      }
    }
  }
}
 
Example 16
Source File: AbstractInplaceIntroducer.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void restartInplaceIntroduceTemplate() {
  Runnable restartTemplateRunnable = new Runnable() {
    @Override
    public void run() {
      final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor);
      if (templateState != null) {
        myEditor.putUserData(INTRODUCE_RESTART, true);
        try {
          final TextRange range = templateState.getCurrentVariableRange();
          if (range != null && range.isEmpty()) {
            final String[] names = suggestNames(isReplaceAllOccurrences(), getLocalVariable());
            ApplicationManager.getApplication().runWriteAction(new Runnable() {
              @Override
              public void run() {
                myEditor.getDocument().insertString(myEditor.getCaretModel().getOffset(), names[0]);
              }
            });
          }
          templateState.gotoEnd(true);
          try {
            myShouldSelect = false;
            startInplaceIntroduceTemplate();
          }
          finally {
            myShouldSelect = true;
          }
        }
        finally {
          myEditor.putUserData(INTRODUCE_RESTART, false);
        }
      }
      updateTitle(getVariable());
    }
  };
  CommandProcessor.getInstance().executeCommand(myProject, restartTemplateRunnable, getCommandName(), getCommandName());
}
 
Example 17
Source File: CompletionContributorForInplaceRename.java    From consulo with Apache License 2.0 5 votes vote down vote up
@RequiredReadAction
@Override
public void fillCompletionVariants(@Nonnull CompletionParameters parameters, @Nonnull CompletionResultSet result) {
  final Editor editor = parameters.getEditor();
  final TemplateState state = TemplateManagerImpl.getTemplateState(editor);
  if (state != null) {
    if (editor.getUserData(InplaceRefactoring.INPLACE_RENAMER) != null && parameters.getInvocationCount() == 0) {
      result.stopHere();
    }
  }
}
 
Example 18
Source File: ShowIntentionsPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doCollectInformation(@Nonnull ProgressIndicator progress) {
  if (!ApplicationManager.getApplication().isHeadlessEnvironment() && !myEditor.getContentComponent().hasFocus()) return;
  TemplateState state = TemplateManagerImpl.getTemplateState(myEditor);
  if (state != null && !state.isFinished()) return;
  getActionsToShow(myEditor, myFile, myIntentionsInfo, myPassIdToShowIntentionsFor, myQueryIntentionActions);
  myCachedIntentions = IntentionsUI.getInstance(myProject).getCachedIntentions(myEditor, myFile);
  myActionsChanged = myCachedIntentions.wrapAndUpdateActions(myIntentionsInfo, false);
}
 
Example 19
Source File: PreviousVariableAction.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
protected boolean isEnabledForCaret(@Nonnull Editor editor, @Nonnull Caret caret, DataContext dataContext) {
  final TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  return templateState != null && !templateState.isFinished();
}
 
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);
}