summaryrefslogtreecommitdiff
path: root/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java
blob: db30a105865a97c187b14fefeb1eb9b4c038485a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
/*
 * Copyright 2000-2013 JetBrains s.r.o.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.intellij.refactoring.rename.inplace;

import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
import com.intellij.codeInsight.highlighting.HighlightManager;
import com.intellij.codeInsight.lookup.LookupManager;
import com.intellij.codeInsight.lookup.impl.LookupImpl;
import com.intellij.codeInsight.template.*;
import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
import com.intellij.codeInsight.template.impl.TemplateState;
import com.intellij.injected.editor.VirtualFileWindow;
import com.intellij.lang.Language;
import com.intellij.lang.LanguageNamesValidation;
import com.intellij.lang.injection.InjectedLanguageManager;
import com.intellij.lang.refactoring.NamesValidator;
import com.intellij.openapi.Disposable;
import com.intellij.openapi.actionSystem.Shortcut;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.application.Result;
import com.intellij.openapi.command.CommandProcessor;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.command.impl.FinishMarkAction;
import com.intellij.openapi.command.impl.StartMarkAction;
import com.intellij.openapi.diagnostic.Logger;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.RangeMarker;
import com.intellij.openapi.editor.ScrollType;
import com.intellij.openapi.editor.colors.EditorColors;
import com.intellij.openapi.editor.colors.EditorColorsManager;
import com.intellij.openapi.editor.impl.EditorImpl;
import com.intellij.openapi.editor.markup.RangeHighlighter;
import com.intellij.openapi.editor.markup.TextAttributes;
import com.intellij.openapi.fileEditor.FileEditor;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.fileEditor.OpenFileDescriptor;
import com.intellij.openapi.fileEditor.TextEditor;
import com.intellij.openapi.keymap.Keymap;
import com.intellij.openapi.keymap.KeymapManager;
import com.intellij.openapi.keymap.KeymapUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.ui.Messages;
import com.intellij.openapi.ui.popup.Balloon;
import com.intellij.openapi.ui.popup.BalloonBuilder;
import com.intellij.openapi.ui.popup.JBPopupFactory;
import com.intellij.openapi.util.*;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.*;
import com.intellij.psi.impl.source.resolve.reference.impl.PsiMultiReference;
import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
import com.intellij.psi.search.LocalSearchScope;
import com.intellij.psi.search.ProjectScope;
import com.intellij.psi.search.PsiSearchHelper;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.refactoring.RefactoringActionHandler;
import com.intellij.refactoring.RefactoringBundle;
import com.intellij.refactoring.util.CommonRefactoringUtil;
import com.intellij.ui.awt.RelativePoint;
import com.intellij.ui.popup.PopupFactoryImpl;
import com.intellij.util.CommonProcessors;
import com.intellij.util.Query;
import com.intellij.util.containers.Stack;
import com.intellij.util.ui.PositionTracker;
import org.jetbrains.annotations.NonNls;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;
import org.jetbrains.annotations.TestOnly;

import javax.swing.*;
import java.awt.*;
import java.util.*;
import java.util.List;

/**
 * User: anna
 * Date: 1/11/12
 */
public abstract class InplaceRefactoring {
  protected static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.rename.inplace.VariableInplaceRenamer");
  @NonNls protected static final String PRIMARY_VARIABLE_NAME = "PrimaryVariable";
  @NonNls protected static final String OTHER_VARIABLE_NAME = "OtherVariable";
  protected static final Stack<InplaceRefactoring> ourRenamersStack = new Stack<InplaceRefactoring>();
  public static final Key<InplaceRefactoring> INPLACE_RENAMER = Key.create("EditorInplaceRenamer");
  public static final Key<Boolean> INTRODUCE_RESTART = Key.create("INTRODUCE_RESTART");

  protected PsiNamedElement myElementToRename;
  protected final Editor myEditor;
  protected final Project myProject;
  protected RangeMarker myRenameOffset;
  protected String myAdvertisementText;
  private ArrayList<RangeHighlighter> myHighlighters;
  protected String myInitialName;
  protected String myOldName;
  protected RangeMarker myBeforeRevert = null;
  protected String myInsertedName;
  protected LinkedHashSet<String> myNameSuggestions;

  protected StartMarkAction myMarkAction;
  protected PsiElement myScope;

  protected RangeMarker myCaretRangeMarker;


  protected Balloon myBalloon;
  protected String myTitle;
  protected RelativePoint myTarget;

  public InplaceRefactoring(Editor editor, PsiNamedElement elementToRename, Project project) {
    this(editor, elementToRename, project, elementToRename != null ? elementToRename.getName() : null,
         elementToRename != null ? elementToRename.getName() : null);
  }

  public InplaceRefactoring(Editor editor, PsiNamedElement elementToRename, Project project, final String oldName) {
    this(editor, elementToRename, project, elementToRename != null ? elementToRename.getName() : null, oldName);
  }

  public InplaceRefactoring(
    Editor editor, PsiNamedElement elementToRename, Project project, String initialName, final String oldName) {
    myEditor = /*(editor instanceof EditorWindow)? ((EditorWindow)editor).getDelegate() : */editor;
    myElementToRename = elementToRename;
    myProject = project;
    myOldName = oldName;
    if (myElementToRename != null) {
      myInitialName = initialName;
      final PsiFile containingFile = myElementToRename.getContainingFile();
      if (!notSameFile(getTopLevelVirtualFile(containingFile.getViewProvider()), containingFile) &&
          myElementToRename != null && myElementToRename.getTextRange() != null) {
        myRenameOffset = myEditor.getDocument().createRangeMarker(myElementToRename.getTextRange());
        myRenameOffset.setGreedyToRight(true);
        myRenameOffset.setGreedyToLeft(true); // todo not sure if we need this
      }
    }
  }

  public static void unableToStartWarning(Project project, Editor editor) {
    final StartMarkAction startMarkAction = StartMarkAction.canStart(project);
    final String message = startMarkAction.getCommandName() + " is not finished yet.";
    final Document oldDocument = startMarkAction.getDocument();
    if (editor == null || oldDocument != editor.getDocument()) {
      final int exitCode = Messages.showYesNoDialog(project, message,
                                                    RefactoringBundle.getCannotRefactorMessage(null),
                                                    "Continue Started", "Cancel Started", Messages.getErrorIcon());
      navigateToStarted(oldDocument, project, exitCode);
    }
    else {
      CommonRefactoringUtil.showErrorHint(project, editor, message, RefactoringBundle.getCannotRefactorMessage(null), null);
    }
  }

  public void setAdvertisementText(String advertisementText) {
    myAdvertisementText = advertisementText;
  }


  public boolean performInplaceRefactoring(final LinkedHashSet<String> nameSuggestions) {
    myNameSuggestions = nameSuggestions;
    if (InjectedLanguageUtil.isInInjectedLanguagePrefixSuffix(myElementToRename)) {
      return false;
    }

    final FileViewProvider fileViewProvider = myElementToRename.getContainingFile().getViewProvider();
    VirtualFile file = getTopLevelVirtualFile(fileViewProvider);

    SearchScope referencesSearchScope = getReferencesSearchScope(file);

    final Collection<PsiReference> refs = collectRefs(referencesSearchScope);

    addReferenceAtCaret(refs);

    for (PsiReference ref : refs) {
      final PsiFile containingFile = ref.getElement().getContainingFile();

      if (notSameFile(file, containingFile)) {
        return false;
      }
    }

    final PsiElement scope = checkLocalScope();

    if (scope == null) {
      return false; // Should have valid local search scope for inplace rename
    }

    final PsiFile containingFile = scope.getContainingFile();
    if (containingFile == null) {
      return false; // Should have valid local search scope for inplace rename
    }
    //no need to process further when file is read-only
    if (!CommonRefactoringUtil.checkReadOnlyStatus(myProject, containingFile)) return true;

    myEditor.putUserData(INPLACE_RENAMER, this);
    ourRenamersStack.push(this);

    final List<Pair<PsiElement, TextRange>> stringUsages = new ArrayList<Pair<PsiElement, TextRange>>();
    collectAdditionalElementsToRename(stringUsages);
    return buildTemplateAndStart(refs, stringUsages, scope, containingFile);
  }

  protected boolean notSameFile(@Nullable VirtualFile file, @NotNull PsiFile containingFile) {
    return !Comparing.equal(getTopLevelVirtualFile(containingFile.getViewProvider()), file);
  }

  protected SearchScope getReferencesSearchScope(VirtualFile file) {
    return file == null || ProjectRootManager.getInstance(myProject).getFileIndex().isInContent(file)
           ? ProjectScope.getProjectScope(myElementToRename.getProject())
           : new LocalSearchScope(myElementToRename.getContainingFile());
  }

  @Nullable
  protected PsiElement checkLocalScope() {
    final SearchScope searchScope = PsiSearchHelper.SERVICE.getInstance(myElementToRename.getProject()).getUseScope(myElementToRename);
    if (searchScope instanceof LocalSearchScope) {
      final PsiElement[] elements = ((LocalSearchScope)searchScope).getScope();
      return PsiTreeUtil.findCommonParent(elements);
    }

    return null;
  }

  protected abstract void collectAdditionalElementsToRename(final List<Pair<PsiElement, TextRange>> stringUsages);

  protected abstract boolean shouldSelectAll();

  protected MyLookupExpression createLookupExpression(PsiElement selectedElement) {
    return new MyLookupExpression(getInitialName(), myNameSuggestions, myElementToRename, selectedElement, shouldSelectAll(), myAdvertisementText);
  }

  protected boolean acceptReference(PsiReference reference) {
    return true;
  }

  protected Collection<PsiReference> collectRefs(SearchScope referencesSearchScope) {
    final Query<PsiReference> search = ReferencesSearch.search(myElementToRename, referencesSearchScope, false);

    final CommonProcessors.CollectProcessor<PsiReference> processor = new CommonProcessors.CollectProcessor<PsiReference>() {
      @Override
      protected boolean accept(PsiReference reference) {
        return acceptReference(reference);
      }
    };

    search.forEach(processor);
    return processor.getResults();
  }

  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 = InjectedLanguageUtil.getTopLevelEditor(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(Result result) throws Throwable {
        startTemplate(builder);
      }
    }.execute();

    if (myBalloon == null) {
      showBalloon();
    }
    return true;
  }

  protected boolean isReferenceAtCaret(PsiElement selectedElement, PsiReference ref) {
    final TextRange textRange = ref.getRangeInElement().shiftRight(ref.getElement().getTextRange().getStartOffset());
    if (selectedElement != null){
      final TextRange selectedElementRange = selectedElement.getTextRange();
      LOG.assertTrue(selectedElementRange != null, selectedElement);
      if (selectedElementRange != null && selectedElementRange.contains(textRange)) return true;
    }
    return false;
  }

  protected void beforeTemplateStart() {
    myCaretRangeMarker = myEditor.getDocument()
          .createRangeMarker(new TextRange(myEditor.getCaretModel().getOffset(), myEditor.getCaretModel().getOffset()));
    myCaretRangeMarker.setGreedyToLeft(true);
    myCaretRangeMarker.setGreedyToRight(true);
  }

  private void startTemplate(final TemplateBuilderImpl builder) {
    final Disposable disposable = Disposer.newDisposable();
    DaemonCodeAnalyzer.getInstance(myProject).disableUpdateByTimer(disposable);

    final MyTemplateListener templateListener = new MyTemplateListener() {
      @Override
      protected void restoreDaemonUpdateState() {
        Disposer.dispose(disposable);
      }
    };

    final int offset = myEditor.getCaretModel().getOffset();

    Template template = builder.buildInlineTemplate();
    template.setToShortenLongNames(false);
    template.setToReformat(false);
    TextRange range = myScope.getTextRange();
    assert range != null;
    myHighlighters = new ArrayList<RangeHighlighter>();
    Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
    topLevelEditor.getCaretModel().moveToOffset(range.getStartOffset());

    TemplateManager.getInstance(myProject).startTemplate(topLevelEditor, template, templateListener);
    restoreOldCaretPositionAndSelection(offset);
    highlightTemplateVariables(template, topLevelEditor);
  }

  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));
    }
  }

  private void restoreOldCaretPositionAndSelection(final int offset) {
    //move to old offset
    Runnable runnable = new Runnable() {
      @Override
      public void run() {
        myEditor.getCaretModel().moveToOffset(restoreCaretOffset(offset));
        restoreSelection();
      }
    };

    final LookupImpl lookup = (LookupImpl)LookupManager.getActiveLookup(myEditor);
    if (lookup != null && lookup.getLookupStart() <= (restoreCaretOffset(offset))) {
      lookup.setFocusDegree(LookupImpl.FocusDegree.UNFOCUSED);
      lookup.performGuardedChange(runnable);
    }
    else {
      runnable.run();
    }
  }

  protected void restoreSelection() {
  }

  protected int restoreCaretOffset(int offset) {
    return myCaretRangeMarker.isValid() ? myCaretRangeMarker.getEndOffset() : offset;
  }

  protected void navigateToAlreadyStarted(Document oldDocument, @Messages.YesNoResult int exitCode) {
    navigateToStarted(oldDocument, myProject, exitCode);
  }

  private static void navigateToStarted(final Document oldDocument, final Project project, @Messages.YesNoResult 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 == Messages.YES) {
                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;
              }
            }
          }
        }
      }
    }
  }

  @Nullable
  protected PsiElement getNameIdentifier() {
    return myElementToRename instanceof PsiNameIdentifierOwner ? ((PsiNameIdentifierOwner)myElementToRename).getNameIdentifier() : null;
  }

  @Nullable
  protected StartMarkAction startRename() throws StartMarkAction.AlreadyStartedException {
    final StartMarkAction[] markAction = new StartMarkAction[1];
    final StartMarkAction.AlreadyStartedException[] ex = new StartMarkAction.AlreadyStartedException[1];
    CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
      @Override
      public void run() {
        try {
          markAction[0] = StartMarkAction.start(myEditor, myProject, getCommandName());
        }
        catch (StartMarkAction.AlreadyStartedException e) {
          ex[0] = e;
        }
      }
    }, getCommandName(), null);
    if (ex[0] != null) throw ex[0];
    return markAction[0];
  }

  @Nullable
  protected PsiNamedElement getVariable() {
    // todo we can use more specific class, shouldn't we?
    //Class clazz = myElementToRename != null? myElementToRename.getClass() : PsiNameIdentifierOwner.class; 
    if (myElementToRename != null && myElementToRename.isValid()) {
      if (Comparing.strEqual(myOldName, myElementToRename.getName())) return myElementToRename;
      if (myRenameOffset != null) return PsiTreeUtil.findElementOfClassAtRange(
        myElementToRename.getContainingFile(), myRenameOffset.getStartOffset(), myRenameOffset.getEndOffset(), PsiNameIdentifierOwner.class);
    }

    if (myRenameOffset != null) {
      final PsiFile psiFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
      if (psiFile != null) {
        return PsiTreeUtil.findElementOfClassAtRange(psiFile, myRenameOffset.getStartOffset(), myRenameOffset.getEndOffset(), PsiNameIdentifierOwner.class);
      }
    }
    return myElementToRename;
  }

  /**
   * Called after the completion of the refactoring, either a successful or a failed one.
   *
   * @param success true if the refactoring was accepted, false if it was cancelled (by undo or Esc)
   */
  protected void moveOffsetAfter(boolean success) {
    if (myCaretRangeMarker != null) {
      myCaretRangeMarker.dispose();
    }
  }

  protected void addAdditionalVariables(TemplateBuilderImpl builder) {
  }

  protected void addReferenceAtCaret(Collection<PsiReference> refs) {
    PsiFile myEditorFile = PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
    // Note, that myEditorFile can be different from myElement.getContainingFile() e.g. in injections: myElement declaration in one
    // file / usage in another !
    final PsiReference reference = (myEditorFile != null ?
                                    myEditorFile : myElementToRename.getContainingFile())
      .findReferenceAt(myEditor.getCaretModel().getOffset());
    if (reference instanceof PsiMultiReference) {
      final PsiReference[] references = ((PsiMultiReference)reference).getReferences();
      for (PsiReference ref : references) {
        addReferenceIfNeeded(refs, ref);
      }
    }
    else {
      addReferenceIfNeeded(refs, reference);
    }
  }

  private void addReferenceIfNeeded(@NotNull final Collection<PsiReference> refs, @Nullable final PsiReference reference) {
    if (reference != null && reference.isReferenceTo(myElementToRename) && !refs.contains(reference)) {
      refs.add(reference);
    }
  }

  protected void showDialogAdvertisement(final String actionId) {
    final Keymap keymap = KeymapManager.getInstance().getActiveKeymap();
    final Shortcut[] shortcuts = keymap.getShortcuts(actionId);
    if (shortcuts.length > 0) {
      setAdvertisementText("Press " + KeymapUtil.getShortcutText(shortcuts[0]) + " to show dialog with more options");
    }
  }

  public String getInitialName() {
    if (myInitialName == null) {
      final PsiNamedElement variable = getVariable();
      if (variable != null) {
        return variable.getName();
      }
    }
    return myInitialName;
  }

  protected void revertState() {
    if (myOldName == null) return;
    CommandProcessor.getInstance().executeCommand(myProject, new Runnable() {
      @Override
      public void run() {
        final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
        ApplicationManager.getApplication().runWriteAction(new Runnable() {
          @Override
          public void run() {
            final TemplateState state = TemplateManagerImpl.getTemplateState(topLevelEditor);
            assert state != null;
            final int segmentsCount = state.getSegmentsCount();
            final Document document = topLevelEditor.getDocument();
            for (int i = 0; i < segmentsCount; i++) {
              final TextRange segmentRange = state.getSegmentRange(i);
              document.replaceString(segmentRange.getStartOffset(), segmentRange.getEndOffset(), myOldName);
            }
          }
        });
        if (!myProject.isDisposed() && myProject.isOpen()) {
          PsiDocumentManager.getInstance(myProject).commitDocument(topLevelEditor.getDocument());
        }
      }
    }, getCommandName(), null);
  }

  /**
   * Returns the name of the command performed by the refactoring.
   *
   * @return command name
   */
  protected abstract String getCommandName();

  public void finish(boolean success) {
    if (!ourRenamersStack.isEmpty() && ourRenamersStack.peek() == this) {
      ourRenamersStack.pop();
    }
    if (myHighlighters != null) {
      if (!myProject.isDisposed()) {
        final HighlightManager highlightManager = HighlightManager.getInstance(myProject);
        for (RangeHighlighter highlighter : myHighlighters) {
          highlightManager.removeSegmentHighlighter(myEditor, highlighter);
        }
      }

      myHighlighters = null;
      myEditor.putUserData(INPLACE_RENAMER, null);
    }
    if (myBalloon != null) {
           if (!isRestart()) {
             myBalloon.hide();
           }
         }
  }

  protected void addHighlights(@NotNull Map<TextRange, TextAttributes> ranges,
                               @NotNull Editor editor,
                               @NotNull Collection<RangeHighlighter> highlighters,
                               @NotNull HighlightManager highlightManager) {
    for (Map.Entry<TextRange, TextAttributes> entry : ranges.entrySet()) {
      TextRange range = entry.getKey();
      TextAttributes attributes = entry.getValue();
      highlightManager.addOccurrenceHighlight(editor, range.getStartOffset(), range.getEndOffset(), attributes, 0, highlighters, null);
    }

    for (RangeHighlighter highlighter : highlighters) {
      highlighter.setGreedyToLeft(true);
      highlighter.setGreedyToRight(true);
    }
  }

  protected abstract boolean performRefactoring();

  private void addVariable(final PsiReference reference,
                           final PsiElement selectedElement,
                           final TemplateBuilderImpl builder,
                           int offset) {
    final PsiElement element = reference.getElement();
    if (element == selectedElement && checkRangeContainsOffset(offset, reference.getRangeInElement(), element)) {
      builder.replaceElement(reference, PRIMARY_VARIABLE_NAME, createLookupExpression(selectedElement), true);
    }
    else {
      builder.replaceElement(reference, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
    }
  }

  private void addVariable(final PsiElement element,
                           final PsiElement selectedElement,
                           final TemplateBuilderImpl builder) {
    addVariable(element, null, selectedElement, builder);
  }

  private void addVariable(final PsiElement element,
                           @Nullable final TextRange textRange,
                           final PsiElement selectedElement,
                           final TemplateBuilderImpl builder) {
    if (element == selectedElement) {
      builder.replaceElement(element, PRIMARY_VARIABLE_NAME, createLookupExpression(myElementToRename), true);
    }
    else if (textRange != null) {
      builder.replaceElement(element, textRange, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
    }
    else {
      builder.replaceElement(element, OTHER_VARIABLE_NAME, PRIMARY_VARIABLE_NAME, false);
    }
  }


  public void setElementToRename(PsiNamedElement elementToRename) {
    myElementToRename = elementToRename;
  }

  protected boolean isIdentifier(final String newName, final Language language) {
    final NamesValidator namesValidator = LanguageNamesValidation.INSTANCE.forLanguage(language);
    return namesValidator == null || namesValidator.isIdentifier(newName, myProject);
  }

  protected static VirtualFile getTopLevelVirtualFile(final FileViewProvider fileViewProvider) {
    VirtualFile file = fileViewProvider.getVirtualFile();
    if (file instanceof VirtualFileWindow) file = ((VirtualFileWindow)file).getDelegate();
    return file;
  }

  @TestOnly
  public static void checkCleared() {
    try {
      assert ourRenamersStack.isEmpty() : ourRenamersStack;
    }
    finally {
      ourRenamersStack.clear();
    }
  }

  private PsiElement getSelectedInEditorElement(@Nullable PsiElement nameIdentifier,
                                                final Collection<PsiReference> refs,
                                                Collection<Pair<PsiElement, TextRange>> stringUsages,
                                                final int offset) {
    //prefer reference in case of self-references
    for (PsiReference ref : refs) {
      final PsiElement element = ref.getElement();
      if (checkRangeContainsOffset(offset, ref.getRangeInElement(), element)) return element;
    }

    if (nameIdentifier != null) {
      final TextRange range = nameIdentifier.getTextRange();
      if (range != null && checkRangeContainsOffset(offset, range, nameIdentifier, 0)) return nameIdentifier;
    }

    for (Pair<PsiElement, TextRange> stringUsage : stringUsages) {
      if (checkRangeContainsOffset(offset, stringUsage.second, stringUsage.first)) return stringUsage.first;
    }

    LOG.error(nameIdentifier + " by " + this.getClass().getName());
    return null;
  }

  private boolean checkRangeContainsOffset(int offset, final TextRange textRange, PsiElement element) {
    return checkRangeContainsOffset(offset, textRange, element, element.getTextRange().getStartOffset());
  }

  private boolean checkRangeContainsOffset(int offset, final TextRange textRange, PsiElement element, int shiftOffset) {
    final InjectedLanguageManager injectedLanguageManager = InjectedLanguageManager.getInstance(myProject);
    final PsiLanguageInjectionHost injectionHost = injectedLanguageManager.getInjectionHost(element);
    if (injectionHost != null) {
      final PsiElement nameIdentifier = getNameIdentifier();
      final PsiLanguageInjectionHost initialInjectedHost = nameIdentifier != null ? injectedLanguageManager.getInjectionHost(nameIdentifier) : null;
      if (initialInjectedHost != null && initialInjectedHost != injectionHost) {
        return false;
      }
      return injectedLanguageManager.injectedToHost(element, textRange).shiftRight(shiftOffset).containsOffset(offset);
    }
    return textRange.shiftRight(shiftOffset).containsOffset(offset);
  }

  protected boolean isRestart() {
    final Boolean isRestart = myEditor.getUserData(INTRODUCE_RESTART);
    return isRestart != null && isRestart;
  }

  public static boolean canStartAnotherRefactoring(Editor editor, Project project, RefactoringActionHandler handler, PsiElement... element) {
    final InplaceRefactoring inplaceRefactoring = getActiveInplaceRenamer(editor);
    return StartMarkAction.canStart(project) == null ||
           (inplaceRefactoring != null && element.length == 1 && inplaceRefactoring.startsOnTheSameElement(handler, element[0]));
  }

  public static InplaceRefactoring getActiveInplaceRenamer(Editor editor) {
    return editor != null ? editor.getUserData(INPLACE_RENAMER) : null;
  }

  protected boolean startsOnTheSameElement(RefactoringActionHandler handler, PsiElement element) {
    return getVariable() == element;
  }

  protected void releaseResources() {
  }

  @Nullable
  protected JComponent getComponent() {
    return null;
  }

  protected void showBalloon() {
    final JComponent component = getComponent();
    if (component == null) return;
    if (ApplicationManager.getApplication().isHeadlessEnvironment()) return;
    final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createDialogBalloonBuilder(component, null).setSmallVariant(true);
    myBalloon = balloonBuilder.createBalloon();
    final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
    Disposer.register(myProject, myBalloon);
    Disposer.register(myBalloon, new Disposable() {
      @Override
      public void dispose() {
        releaseIfNotRestart();
        topLevelEditor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, null);
      }
    });
    topLevelEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
    myBalloon.show(new PositionTracker<Balloon>(topLevelEditor.getContentComponent()) {
      @Override
      public RelativePoint recalculateLocation(Balloon object) {
        if (myTarget != null && !popupFactory.isBestPopupLocationVisible(topLevelEditor)) {
          return myTarget;
        }
        if (myCaretRangeMarker != null && myCaretRangeMarker.isValid()) {
          topLevelEditor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION,
                                     topLevelEditor.offsetToVisualPosition(myCaretRangeMarker.getStartOffset()));
        }
        final RelativePoint target = popupFactory.guessBestPopupLocation(topLevelEditor);
        final Point screenPoint = target.getScreenPoint();
        int y = screenPoint.y;
        if (target.getPoint().getY() > topLevelEditor.getLineHeight() + myBalloon.getPreferredSize().getHeight()) {
          y -= topLevelEditor.getLineHeight();
        }
        myTarget = new RelativePoint(new Point(screenPoint.x, y));
        return myTarget;
      }
    }, Balloon.Position.above);
  }

  protected void releaseIfNotRestart() {
    if (!isRestart()) {
      releaseResources();
    }
  }

  private abstract class MyTemplateListener extends TemplateEditingAdapter {

    protected abstract void restoreDaemonUpdateState();

    @Override
    public void beforeTemplateFinished(final TemplateState templateState, Template template) {
      try {
        final TextResult value = templateState.getVariableValue(PRIMARY_VARIABLE_NAME);
        myInsertedName = value != null ? value.toString() : null;

        TextRange range = templateState.getCurrentVariableRange();
        final int currentOffset = myEditor.getCaretModel().getOffset();
        if (range == null && myRenameOffset != null) {
          range = new TextRange(myRenameOffset.getStartOffset(), myRenameOffset.getEndOffset());
        }
        myBeforeRevert =
          range != null && range.getEndOffset() >= currentOffset && range.getStartOffset() <= currentOffset
          ? myEditor.getDocument().createRangeMarker(range.getStartOffset(), currentOffset)
          : null;
        if (myBeforeRevert != null) {
          myBeforeRevert.setGreedyToRight(true);
        }
        finish(true);
      }
      finally {
        restoreDaemonUpdateState();
      }
    }

    @Override
    public void templateFinished(Template template, final boolean brokenOff) {
      boolean bind = false;
      try {
        super.templateFinished(template, brokenOff);
        if (!brokenOff) {
          bind = performRefactoring();
        }
        moveOffsetAfter(!brokenOff);
      }
      finally {
        if (!bind) {
          try {
            ((EditorImpl)InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
          }
          finally {
            FinishMarkAction.finish(myProject, myEditor, myMarkAction);
            if (myBeforeRevert != null) {
              myBeforeRevert.dispose();
            }
          }
        }
      }
    }

    @Override
    public void templateCancelled(Template template) {
      try {
        final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(myProject);
        documentManager.commitAllDocuments();
        finish(false);
        moveOffsetAfter(false);
      }
      finally {
        try {
          restoreDaemonUpdateState();
        }
        finally {
          FinishMarkAction.finish(myProject, myEditor, myMarkAction);
        }
      }
    }
  }
}