com.intellij.codeInsight.template.impl.TemplateState Java Examples

The following examples show how to use com.intellij.codeInsight.template.impl.TemplateState. 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: 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 #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: 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 #4
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 #5
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 #6
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 #7
Source File: MyLookupExpression.java    From consulo with Apache License 2.0 5 votes vote down vote up
private static LookupElement[] initLookupItems(LinkedHashSet<String> names,
                                               PsiNamedElement elementToRename, 
                                               PsiElement nameSuggestionContext,
                                               final boolean shouldSelectAll) {
  if (names == null) {
    names = new LinkedHashSet<String>();
    for (NameSuggestionProvider provider : Extensions.getExtensions(NameSuggestionProvider.EP_NAME)) {
      final SuggestedNameInfo suggestedNameInfo = provider.getSuggestedNames(elementToRename, nameSuggestionContext, names);
      if (suggestedNameInfo != null &&
          provider instanceof PreferrableNameSuggestionProvider &&
          !((PreferrableNameSuggestionProvider)provider).shouldCheckOthers()) {
        break;
      }
    }
  }
  final LookupElement[] lookupElements = new LookupElement[names.size()];
  final Iterator<String> iterator = names.iterator();
  for (int i = 0; i < lookupElements.length; i++) {
    final String suggestion = iterator.next();
    lookupElements[i] = LookupElementBuilder.create(suggestion).withInsertHandler(new InsertHandler<LookupElement>() {
      @Override
      public void handleInsert(InsertionContext context, LookupElement item) {
        if (shouldSelectAll) return;
        final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(context.getEditor());
        final TemplateState templateState = TemplateManagerImpl.getTemplateState(topLevelEditor);
        if (templateState != null) {
          final TextRange range = templateState.getCurrentVariableRange();
          if (range != null) {
            topLevelEditor.getDocument().replaceString(range.getStartOffset(), range.getEndOffset(), suggestion);
          }
        }
      }
    });
  }
  return lookupElements;
}
 
Example #8
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 #9
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 #10
Source File: ShowIntentionActionsHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
public void invoke(@Nonnull final Project project, @Nonnull Editor editor, @Nonnull PsiFile file, boolean showFeedbackOnEmptyMenu) {
  PsiDocumentManager.getInstance(project).commitAllDocuments();
  if (editor instanceof EditorWindow) {
    editor = ((EditorWindow)editor).getDelegate();
    file = InjectedLanguageManager.getInstance(file.getProject()).getTopLevelFile(file);
  }

  final LookupEx lookup = LookupManager.getActiveLookup(editor);
  if (lookup != null) {
    lookup.showElementActions(null);
    return;
  }

  final DaemonCodeAnalyzerImpl codeAnalyzer = (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project);
  letAutoImportComplete(editor, file, codeAnalyzer);

  ShowIntentionsPass.IntentionsInfo intentions = ShowIntentionsPass.getActionsToShow(editor, file, true);
  IntentionsUI.getInstance(project).hide();

  if (HintManagerImpl.getInstanceImpl().performCurrentQuestionAction()) return;

  //intentions check isWritable before modification: if (!file.isWritable()) return;

  TemplateState state = TemplateManagerImpl.getTemplateState(editor);
  if (state != null && !state.isFinished()) {
    return;
  }

  editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
  Editor finalEditor = editor;
  PsiFile finalFile = file;
  showIntentionHint(project, finalEditor, finalFile, intentions, showFeedbackOnEmptyMenu);
}
 
Example #11
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 #12
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 #13
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 #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;
  }
  return myOriginalHandler.isEnabled(editor, dataContext);
}
 
Example #15
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 #16
Source File: SelectAllHandler.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void execute(Editor editor, 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 && range.getStartOffset() <= caretOffset && caretOffset <= range.getEndOffset()) {
      editor.getSelectionModel().setSelection(range.getStartOffset(), range.getEndOffset());
      return;
    }
  }
  myOriginalHandler.execute(editor, dataContext);
}
 
Example #17
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 #18
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 #19
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 #20
Source File: ShowIntentionsPass.java    From consulo with Apache License 2.0 5 votes vote down vote up
@Override
public void doApplyInformationToEditor() {
  ApplicationManager.getApplication().assertIsDispatchThread();

  CachedIntentions cachedIntentions = myCachedIntentions;
  boolean actionsChanged = myActionsChanged;
  TemplateState state = TemplateManagerImpl.getTemplateState(myEditor);
  if ((state == null || state.isFinished()) && cachedIntentions != null) {
    IntentionsInfo syncInfo = new IntentionsInfo();
    getActionsToShowSync(myEditor, myFile, syncInfo, myPassIdToShowIntentionsFor);
    actionsChanged |= cachedIntentions.addActions(syncInfo);

    IntentionsUI.getInstance(myProject).update(cachedIntentions, actionsChanged);
  }
}
 
Example #21
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 #22
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 #23
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 #24
Source File: AbstractInplaceIntroducer.java    From consulo with Apache License 2.0 4 votes vote down vote up
/**
 * Begins the in-place refactoring operation.
 *
 * @return true if the in-place refactoring was successfully started, false if it failed to start and a dialog should be shown instead.
 */
public boolean startInplaceIntroduceTemplate() {
  final boolean replaceAllOccurrences = isReplaceAllOccurrences();
  final Ref<Boolean> result = new Ref<Boolean>();
  CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
    @Override
    public void run() {
      final String[] names = suggestNames(replaceAllOccurrences, getLocalVariable());
      final V variable = createFieldToStartTemplateOn(replaceAllOccurrences, names);
      boolean started = false;
      if (variable != null) {
        int caretOffset = getCaretOffset();
        myEditor.getCaretModel().moveToOffset(caretOffset);
        myEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);

        final LinkedHashSet<String> nameSuggestions = new LinkedHashSet<String>();
        nameSuggestions.add(variable.getName());
        nameSuggestions.addAll(Arrays.asList(names));
        initOccurrencesMarkers();
        setElementToRename(variable);
        updateTitle(getVariable());
        started = AbstractInplaceIntroducer.super.performInplaceRefactoring(nameSuggestions);
        if (started) {
          myDocumentAdapter = new DocumentAdapter() {
            @Override
            public void documentChanged(DocumentEvent e) {
              if (myPreview == null) return;
              final TemplateState templateState = TemplateManagerImpl.getTemplateState(myEditor);
              if (templateState != null) {
                final TextResult value = templateState.getVariableValue(InplaceRefactoring.PRIMARY_VARIABLE_NAME);
                if (value != null) {
                  updateTitle(getVariable(), value.getText());
                }
              }
            }
          };
          myEditor.getDocument().addDocumentListener(myDocumentAdapter);
          updateTitle(getVariable());
          if (TemplateManagerImpl.getTemplateState(myEditor) != null) {
            myEditor.putUserData(ACTIVE_INTRODUCE, AbstractInplaceIntroducer.this);
          }
        }
      }
      result.set(started);
      if (!started) {
        finish(true);
      }
    }

  }, getCommandName(), getCommandName());
  return result.get();
}
 
Example #25
Source File: CSharpIntroduceHandler.java    From consulo-csharp with Apache License 2.0 4 votes vote down vote up
@RequiredReadAction
public void performAction(CSharpIntroduceOperation 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);
		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);
		}
	}
	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);
		}
	}
	final Project project = operation.getProject();
	if(element1 == null || element2 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	element1 = CSharpRefactoringUtil.getSelectedExpression(project, file, element1, element2);
	if(element1 == null)
	{
		showCannotPerformError(project, editor);
		return;
	}

	if(!checkIntroduceContext(file, editor, element1))
	{
		return;
	}
	operation.setElement(element1);
	performActionOnElement(operation);
}
 
Example #26
Source File: InplaceRefactoring.java    From consulo with Apache License 2.0 4 votes vote down vote up
protected boolean buildTemplateAndStart(final Collection<PsiReference> refs,
                                        final Collection<Pair<PsiElement, TextRange>> stringUsages,
                                        final PsiElement scope,
                                        final PsiFile containingFile) {
  final PsiElement context = InjectedLanguageManager.getInstance(containingFile.getProject()).getInjectionHost(containingFile);
  myScope = context != null ? context.getContainingFile() : scope;
  final TemplateBuilderImpl builder = new TemplateBuilderImpl(myScope);

  PsiElement nameIdentifier = getNameIdentifier();
  int offset = myEditor.getCaretModel().getOffset();
  PsiElement selectedElement = getSelectedInEditorElement(nameIdentifier, refs, stringUsages, offset);

  boolean subrefOnPrimaryElement = false;
  boolean hasReferenceOnNameIdentifier = false;
  for (PsiReference ref : refs) {
    if (isReferenceAtCaret(selectedElement, ref)) {
      builder.replaceElement(ref, PRIMARY_VARIABLE_NAME, createLookupExpression(selectedElement), true);
      subrefOnPrimaryElement = true;
      continue;
    }
    addVariable(ref, selectedElement, builder, offset);
    hasReferenceOnNameIdentifier |= isReferenceAtCaret(nameIdentifier, ref);
  }
  if (nameIdentifier != null) {
    hasReferenceOnNameIdentifier |= selectedElement.getTextRange().contains(nameIdentifier.getTextRange());
    if (!subrefOnPrimaryElement || !hasReferenceOnNameIdentifier){
      addVariable(nameIdentifier, selectedElement, builder);
    }
  }
  for (Pair<PsiElement, TextRange> usage : stringUsages) {
    addVariable(usage.first, usage.second, selectedElement, builder);
  }
  addAdditionalVariables(builder);
  try {
    myMarkAction = startRename();
  }
  catch (final StartMarkAction.AlreadyStartedException e) {
    final Document oldDocument = e.getDocument();
    if (oldDocument != myEditor.getDocument()) {
      final int exitCode = Messages.showYesNoCancelDialog(myProject, e.getMessage(), getCommandName(),
                                                          "Navigate to Started", "Cancel Started", "Cancel", Messages.getErrorIcon());
      if (exitCode == Messages.CANCEL) return true;
      navigateToAlreadyStarted(oldDocument, exitCode);
      return true;
    }
    else {

      if (!ourRenamersStack.isEmpty() && ourRenamersStack.peek() == this) {
        ourRenamersStack.pop();
        if (!ourRenamersStack.empty()) {
          myOldName = ourRenamersStack.peek().myOldName;
        }
      }

      revertState();
      final TemplateState templateState = TemplateManagerImpl.getTemplateState(InjectedLanguageUtil.getTopLevelEditor(myEditor));
      if (templateState != null) {
        templateState.gotoEnd(true);
      }
    }
    return false;
  }

  beforeTemplateStart();

  new WriteCommandAction(myProject, getCommandName()) {
    @Override
    protected void run(com.intellij.openapi.application.Result result) throws Throwable {
      startTemplate(builder);
    }
  }.execute();

  if (myBalloon == null) {
    showBalloon();
  }
  return true;
}
 
Example #27
Source File: TemplateEditingListener.java    From consulo with Apache License 2.0 4 votes vote down vote up
default void beforeTemplateFinished(TemplateState state, Template template, boolean brokenOff) {
  beforeTemplateFinished(state, template);
}
 
Example #28
Source File: TemplateEditingAdapter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void currentVariableChanged(TemplateState templateState, Template template, int oldIndex, int newIndex) {
}
 
Example #29
Source File: TemplateEditingAdapter.java    From consulo with Apache License 2.0 4 votes vote down vote up
@Override
public void beforeTemplateFinished(final TemplateState state, final Template template) {
}
 
Example #30
Source File: NextVariableAction.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) {
  TemplateState templateState = TemplateManagerImpl.getTemplateState(editor);
  return templateState != null && !templateState.isFinished() && templateState.isToProcessTab();
}