private static void checkEqualFunctionNames(
     @NotNull PsiNamedElement namedElement, @NotNull JavaMethod method) {
   if (!ComparatorUtil.equalsNullable(method.getName().asString(), namedElement.getName())) {
     throw new AlternativeSignatureMismatchException(
         "Function names mismatch, original: %s, alternative: %s",
         method.getName().asString(), namedElement.getName());
   }
 }
 @Override
 public PsiElement handleElementRename(String name) {
   if (myElement instanceof PsiNamedElement) {
     PsiNamedElement psiNamedElement = (PsiNamedElement) myElement;
     return psiNamedElement.setName(RobotPsiUtil.methodToRobotKeyword(name));
   }
   return myElement;
 }
 @Nullable
 public PsiElement bindToElement(@NotNull PsiElement element) throws IncorrectOperationException {
   if (element instanceof AntTarget) {
     final PsiNamedElement psiNamedElement = (PsiNamedElement) element;
     return handleElementRename(psiNamedElement.getName());
   }
   throw new IncorrectOperationException("Can bind only to ant targets.");
 }
    private void handleNamedElement(final PsiNamedElement named) {
      String name = named.getName();

      assert name != null;

      if (StructuralSearchUtil.isTypedVariable(name)) {
        name = name.substring(1, name.length() - 1);
      }

      if (!namedElements.containsKey(name)) namedElements.put(name, named);
      named.acceptChildren(this);
    }
Esempio n. 5
0
 private static String getParentDeclarationDescription(DLanguageIdentifier o) {
   PsiNamedElement funcDecl =
       (PsiNamedElement) findParentOfType(o, DLanguageFuncDeclaration.class);
   PsiNamedElement classDecl =
       (PsiNamedElement) findParentOfType(o, DLanguageClassDeclaration.class);
   String description = "";
   if (funcDecl != null) {
     description = " [Function] (" + funcDecl.getName() + ")";
   }
   if (classDecl != null) {
     description = " [Class] (" + classDecl.getName() + ")";
   }
   return description;
 }
  protected void restoreState(@NotNull final V psiField) {
    if (!ReadonlyStatusHandler.ensureDocumentWritable(
        myProject, InjectedLanguageUtil.getTopLevelEditor(myEditor).getDocument())) return;
    ApplicationManager.getApplication()
        .runWriteAction(
            () -> {
              final PsiFile containingFile = psiField.getContainingFile();
              final RangeMarker exprMarker = getExprMarker();
              if (exprMarker != null) {
                myExpr = restoreExpression(containingFile, psiField, exprMarker, myExprText);
              }

              if (myLocalMarker != null) {
                final PsiElement refVariableElement =
                    containingFile.findElementAt(myLocalMarker.getStartOffset());
                if (refVariableElement != null) {
                  final PsiElement parent = refVariableElement.getParent();
                  if (parent instanceof PsiNamedElement) {
                    ((PsiNamedElement) parent).setName(myLocalName);
                  }
                }

                final V localVariable = getLocalVariable();
                if (localVariable != null && localVariable.isPhysical()) {
                  myLocalVariable = localVariable;
                  final PsiElement nameIdentifier = localVariable.getNameIdentifier();
                  if (nameIdentifier != null) {
                    myLocalMarker = createMarker(nameIdentifier);
                  }
                }
              }
              final List<RangeMarker> occurrenceMarkers = getOccurrenceMarkers();
              for (int i = 0, occurrenceMarkersSize = occurrenceMarkers.size();
                  i < occurrenceMarkersSize;
                  i++) {
                RangeMarker marker = occurrenceMarkers.get(i);
                if (getExprMarker() != null
                    && marker.getStartOffset() == getExprMarker().getStartOffset()
                    && myExpr != null) {
                  myOccurrences[i] = myExpr;
                  continue;
                }
                final E psiExpression =
                    restoreExpression(
                        containingFile,
                        psiField,
                        marker,
                        getLocalVariable() != null ? myLocalName : myExprText);
                if (psiExpression != null) {
                  myOccurrences[i] = psiExpression;
                }
              }

              if (myExpr != null && myExpr.isPhysical()) {
                myExprMarker = createMarker(myExpr);
              }
              myOccurrenceMarkers = null;
              deleteTemplateField(psiField);
            });
  }
Esempio n. 7
0
 public static boolean processElement(PsiScopeProcessor processor, PsiNamedElement namedElement) {
   if (namedElement == null) return true;
   NameHint nameHint = processor.getHint(NameHint.KEY);
   String name = nameHint == null ? null : nameHint.getName(ResolveState.initial());
   if (name == null || name.equals(namedElement.getName())) {
     return processor.execute(namedElement, ResolveState.initial());
   }
   return true;
 }
 protected void suggestAllNames(final String oldClassName, String newClassName) {
   final NameSuggester suggester = new NameSuggester(oldClassName, newClassName);
   for (int varIndex = myElements.size() - 1; varIndex >= 0; varIndex--) {
     final PsiNamedElement element = myElements.get(varIndex);
     final String name = element.getName();
     if (!myRenames.containsKey(element)) {
       String newName = suggestNameForElement(element, suggester, newClassName, oldClassName);
       if (!newName.equals(name)) {
         myRenames.put(element, newName);
       } else {
         myRenames.put(element, null);
       }
     }
     if (myRenames.get(element) == null) {
       myElements.remove(varIndex);
     }
   }
 }
 public boolean execute(
     ReferencesSearch.SearchParameters params, final Processor<PsiReference> consumer) {
   final PsiElement elem = params.getElementToSearch();
   SearchScope scope = params.getEffectiveSearchScope();
   if (elem instanceof PsiNamedElement
       /* An optimization for Java refactorings */
       && !(elem instanceof PsiVariable)) {
     final PsiNamedElement symbolToSearch = (PsiNamedElement) elem;
     final String name = symbolToSearch.getName();
     if (name != null) {
       RequestResultProcessor processor =
           new RequestResultProcessor() {
             @Override
             public boolean processTextOccurrence(
                 @NotNull PsiElement element,
                 int offsetInElement,
                 @NotNull Processor<PsiReference> consumer) {
               if (element instanceof ClSymbol) {
                 ClSymbol refSymbol = (ClSymbol) element;
                 for (PsiReference ref : refSymbol.getReferences()) {
                   if (ref.getRangeInElement().contains(offsetInElement)
                       &&
                       // atom may refer to definition or to the symbol in it
                       (ref.resolve() == symbolToSearch
                           || ref.resolve() == symbolToSearch.getParent())) {
                     if (!consumer.process(ref)) return false;
                   }
                 }
               }
               return true;
             }
           };
       if (scope instanceof GlobalSearchScope) {
         scope =
             GlobalSearchScope.getScopeRestrictedByFileTypes(
                 (GlobalSearchScope) scope, ClojureFileType.CLOJURE_FILE_TYPE);
       }
       for (String word : StringUtil.getWordsIn(name)) {
         params.getOptimizer().searchWord(word, scope, UsageSearchContext.ANY, true, processor);
       }
     }
   }
   return true;
 }
 public static boolean isTooExpensiveToSearch(PsiNamedElement element, boolean zeroResult) {
   final String name = element.getName();
   if (name == null) {
     return true;
   }
   final ProgressManager progressManager = ProgressManager.getInstance();
   final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(element.getProject());
   final SearchScope useScope = element.getUseScope();
   if (!(useScope instanceof GlobalSearchScope)) {
     return zeroResult;
   }
   final PsiSearchHelper.SearchCostResult cost =
       searchHelper.isCheapEnoughToSearch(
           name, (GlobalSearchScope) useScope, null, progressManager.getProgressIndicator());
   if (cost == PsiSearchHelper.SearchCostResult.ZERO_OCCURRENCES) {
     return zeroResult;
   }
   return cost == PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES;
 }
  private PsiElement handleSymbolReplacement(PsiElement replacement, final PsiElement el)
      throws IncorrectOperationException {
    PsiNamedElement nameElement = getSymbolReplacementTarget(el);
    if (nameElement != null) {
      PsiElement oldReplacement = replacement;
      replacement = el.copy();
      ((PsiNamedElement) replacement).setName(oldReplacement.getText());
    }

    return replacement;
  }
  @Override
  protected void performRefactoringRename(final String newName, final StartMarkAction markAction) {
    try {
      final PsiNamedElement variable = getVariable();
      if (variable != null && !newName.equals(myOldName)) {
        if (isIdentifier(newName, variable.getLanguage())) {
          final PsiElement substituted = getSubstituted();
          if (substituted == null) {
            return;
          }

          final String commandName =
              RefactoringBundle.message(
                  "renaming.0.1.to.2",
                  UsageViewUtil.getType(variable),
                  UsageViewUtil.getDescriptiveName(variable),
                  newName);
          CommandProcessor.getInstance()
              .executeCommand(
                  myProject,
                  new Runnable() {
                    @Override
                    public void run() {
                      performRenameInner(substituted, newName);
                      PsiDocumentManager.getInstance(myProject).commitAllDocuments();
                    }
                  },
                  commandName,
                  null);
        }
      }
    } finally {
      try {
        ((EditorImpl) InjectedLanguageUtil.getTopLevelEditor(myEditor)).stopDumbLater();
      } finally {
        FinishMarkAction.finish(myProject, myEditor, markAction);
      }
    }
  }
Esempio n. 13
0
  private static ProblemDescriptor runLocalTool(
      @NotNull PsiElement psiElement,
      @NotNull InspectionManager inspectionManager,
      @NotNull OfflineProblemDescriptor offlineProblemDescriptor,
      @NotNull LocalInspectionToolWrapper toolWrapper) {
    PsiFile containingFile = psiElement.getContainingFile();
    final ProblemsHolder holder = new ProblemsHolder(inspectionManager, containingFile, false);
    final LocalInspectionTool localTool = toolWrapper.getTool();
    final int startOffset = psiElement.getTextRange().getStartOffset();
    final int endOffset = psiElement.getTextRange().getEndOffset();
    LocalInspectionToolSession session =
        new LocalInspectionToolSession(containingFile, startOffset, endOffset);
    final PsiElementVisitor visitor = localTool.buildVisitor(holder, false, session);
    localTool.inspectionStarted(session, false);
    final PsiElement[] elementsInRange =
        getElementsIntersectingRange(containingFile, startOffset, endOffset);
    for (PsiElement element : elementsInRange) {
      element.accept(visitor);
    }
    localTool.inspectionFinished(session, holder);
    if (holder.hasResults()) {
      final List<ProblemDescriptor> list = holder.getResults();
      final int idx = offlineProblemDescriptor.getProblemIndex();
      int curIdx = 0;
      for (ProblemDescriptor descriptor : list) {
        final PsiNamedElement member = localTool.getProblemElement(descriptor.getPsiElement());
        if (psiElement instanceof PsiFile || member != null && member.equals(psiElement)) {
          if (curIdx == idx) {
            return descriptor;
          }
          curIdx++;
        }
      }
    }

    return null;
  }
  public MemberInplaceRenamer(
      @NotNull PsiNamedElement elementToRename,
      PsiElement substituted,
      Editor editor,
      String initialName,
      String oldName) {
    super(elementToRename, editor, elementToRename.getProject(), initialName, oldName);
    mySubstituted = substituted;
    if (mySubstituted != null
        && mySubstituted != myElementToRename
        && mySubstituted.getTextRange() != null) {
      final PsiFile containingFile = mySubstituted.getContainingFile();
      if (!notSameFile(containingFile.getVirtualFile(), containingFile)) {
        mySubstitutedRange = myEditor.getDocument().createRangeMarker(mySubstituted.getTextRange());
      }
    } else {
      mySubstitutedRange = null;
    }

    showDialogAdvertisement("RenameElement");
  }
 protected String suggestNameForElement(
     PsiNamedElement element, NameSuggester suggester, String newClassName, String oldClassName) {
   String name = element.getName();
   if (oldClassName.equals(name)) {
     return newClassName;
   }
   String canonicalName = nameToCanonicalName(name, element);
   final String newCanonicalName = suggester.suggestName(canonicalName);
   if (newCanonicalName.length() == 0) {
     LOG.error(
         "oldClassName = "
             + oldClassName
             + ", newClassName = "
             + newClassName
             + ", name = "
             + name
             + ", canonicalName = "
             + canonicalName
             + ", newCanonicalName = "
             + newCanonicalName);
   }
   return canonicalNameToName(newCanonicalName, element);
 }
  @SuppressWarnings({"unchecked", "ConstantConditions"})
  private void handleModifierList(final PsiElement el, final PsiElement replacement)
      throws IncorrectOperationException {
    // We want to copy all comments, including doc comments and modifier lists
    // that are present in matched nodes but not present in search/replace

    Map<String, String> newNameToSearchPatternNameMap = myContext.getNewName2PatternNameMap();

    ModifierListOwnerCollector collector = new ModifierListOwnerCollector();
    el.accept(collector);
    Map<String, PsiNamedElement> originalNamedElements =
        (Map<String, PsiNamedElement>) collector.namedElements.clone();
    collector.namedElements.clear();

    replacement.accept(collector);
    Map<String, PsiNamedElement> replacedNamedElements =
        (Map<String, PsiNamedElement>) collector.namedElements.clone();
    collector.namedElements.clear();

    if (originalNamedElements.size() == 0 && replacedNamedElements.size() == 0) {
      Replacer.handleComments(el, replacement, myContext);
      return;
    }

    final PsiStatement[] statements = getCodeBlock().getStatements();
    if (statements.length > 0) {
      statements[0].getParent().accept(collector);
    }

    Map<String, PsiNamedElement> searchedNamedElements =
        (Map<String, PsiNamedElement>) collector.namedElements.clone();
    collector.namedElements.clear();

    for (String name : originalNamedElements.keySet()) {
      PsiNamedElement originalNamedElement = originalNamedElements.get(name);
      PsiNamedElement replacementNamedElement = replacedNamedElements.get(name);
      String key = newNameToSearchPatternNameMap.get(name);
      if (key == null) key = name;
      PsiNamedElement searchNamedElement = searchedNamedElements.get(key);

      if (replacementNamedElement == null
          && originalNamedElements.size() == 1
          && replacedNamedElements.size() == 1) {
        replacementNamedElement = replacedNamedElements.entrySet().iterator().next().getValue();
      }

      PsiElement comment = null;

      if (originalNamedElement instanceof PsiDocCommentOwner) {
        comment = ((PsiDocCommentOwner) originalNamedElement).getDocComment();
        if (comment == null) {
          PsiElement prevElement = originalNamedElement.getPrevSibling();
          if (prevElement instanceof PsiWhiteSpace) {
            prevElement = prevElement.getPrevSibling();
          }
          if (prevElement instanceof PsiComment) {
            comment = prevElement;
          }
        }
      }

      if (replacementNamedElement != null && searchNamedElement != null) {
        Replacer.handleComments(originalNamedElement, replacementNamedElement, myContext);
      }

      if (comment != null
          && replacementNamedElement instanceof PsiDocCommentOwner
          && !(replacementNamedElement.getFirstChild() instanceof PsiDocComment)) {
        final PsiElement nextSibling = comment.getNextSibling();
        PsiElement prevSibling = comment.getPrevSibling();
        replacementNamedElement.addRangeBefore(
            prevSibling instanceof PsiWhiteSpace ? prevSibling : comment,
            nextSibling instanceof PsiWhiteSpace ? nextSibling : comment,
            replacementNamedElement.getFirstChild());
      }

      if (originalNamedElement instanceof PsiModifierListOwner
          && replacementNamedElement instanceof PsiModifierListOwner) {
        PsiModifierList modifierList =
            ((PsiModifierListOwner) originalNamedElements.get(name)).getModifierList();

        if (searchNamedElement instanceof PsiModifierListOwner) {
          PsiModifierList modifierListOfSearchedElement =
              ((PsiModifierListOwner) searchNamedElement).getModifierList();
          final PsiModifierListOwner modifierListOwner =
              ((PsiModifierListOwner) replacementNamedElement);
          PsiModifierList modifierListOfReplacement = modifierListOwner.getModifierList();

          if (modifierListOfSearchedElement.getTextLength() == 0
              && modifierListOfReplacement.getTextLength() == 0
              && modifierList.getTextLength() > 0) {
            PsiElement space = modifierList.getNextSibling();
            if (!(space instanceof PsiWhiteSpace)) {
              space = createWhiteSpace(space);
            }

            modifierListOfReplacement.replace(modifierList);
            // copy space after modifier list
            if (space instanceof PsiWhiteSpace) {
              modifierListOwner.addRangeAfter(space, space, modifierListOwner.getModifierList());
            }
          } else if (modifierListOfSearchedElement.getTextLength() == 0
              && modifierList.getTextLength() > 0) {
            modifierListOfReplacement.addRange(
                modifierList.getFirstChild(), modifierList.getLastChild());
          }
        }
      }
    }
  }
  @Override
  public Object[] getFileReferenceCompletionVariants(final FileReference reference) {
    final String s = reference.getText();
    if (s != null && s.equals("/")) {
      return ArrayUtil.EMPTY_OBJECT_ARRAY;
    }

    final CommonProcessors.CollectUniquesProcessor<PsiFileSystemItem> collector =
        new CommonProcessors.CollectUniquesProcessor<PsiFileSystemItem>();
    final PsiElementProcessor<PsiFileSystemItem> processor =
        new PsiElementProcessor<PsiFileSystemItem>() {
          @Override
          public boolean execute(@NotNull PsiFileSystemItem fileSystemItem) {
            return new FilteringProcessor<PsiFileSystemItem>(
                    reference.getFileReferenceSet().getReferenceCompletionFilter(), collector)
                .process(FileReference.getOriginalFile(fileSystemItem));
          }
        };

    List<Object> additionalItems = ContainerUtil.newArrayList();
    for (PsiFileSystemItem context : reference.getContexts()) {
      for (final PsiElement child : context.getChildren()) {
        if (child instanceof PsiFileSystemItem) {
          processor.execute((PsiFileSystemItem) child);
        }
      }
      if (context instanceof FileReferenceResolver) {
        additionalItems.addAll(((FileReferenceResolver) context).getVariants(reference));
      }
    }

    final FileType[] types = reference.getFileReferenceSet().getSuitableFileTypes();
    final THashSet<PsiElement> set =
        new THashSet<PsiElement>(collector.getResults(), VARIANTS_HASHING_STRATEGY);
    final PsiElement[] candidates = PsiUtilCore.toPsiElementArray(set);

    final Object[] variants = new Object[candidates.length + additionalItems.size()];
    for (int i = 0; i < candidates.length; i++) {
      PsiElement candidate = candidates[i];
      Object item = reference.createLookupItem(candidate);
      if (item == null) {
        item = FileInfoManager.getFileLookupItem(candidate);
      }
      if (candidate instanceof PsiFile
          && item instanceof LookupElement
          && types.length > 0
          && ArrayUtil.contains(((PsiFile) candidate).getFileType(), types)) {
        item = PrioritizedLookupElement.withPriority((LookupElement) item, Double.MAX_VALUE);
      }
      variants[i] = item;
    }

    for (int i = 0; i < additionalItems.size(); i++) {
      variants[i + candidates.length] = additionalItems.get(i);
    }
    if (!reference.getFileReferenceSet().isUrlEncoded()) {
      return variants;
    }
    List<Object> encodedVariants = new ArrayList<Object>(variants.length + additionalItems.size());
    for (int i = 0; i < candidates.length; i++) {
      final PsiElement element = candidates[i];
      if (element instanceof PsiNamedElement) {
        final PsiNamedElement psiElement = (PsiNamedElement) element;
        String name = psiElement.getName();
        final String encoded = reference.encode(name, psiElement);
        if (encoded == null) continue;
        if (!encoded.equals(name)) {
          final Icon icon =
              psiElement.getIcon(Iconable.ICON_FLAG_READ_STATUS | Iconable.ICON_FLAG_VISIBILITY);
          LookupElementBuilder item =
              FileInfoManager.getFileLookupItem(candidates[i], encoded, icon);
          encodedVariants.add(item.withTailText(" (" + name + ")"));
        } else {
          encodedVariants.add(variants[i]);
        }
      }
    }
    encodedVariants.addAll(additionalItems);
    return ArrayUtil.toObjectArray(encodedVariants);
  }
Esempio n. 18
0
  public boolean checkAvailable(
      @NotNull final Editor editor,
      @NotNull final PsiFile file,
      @NotNull final MoveInfo info,
      final boolean down) {
    if (!(file instanceof XmlFile)) {
      return false;
    }
    boolean available = super.checkAvailable(editor, file, info, down);
    if (!available) return false;

    // updated moved range end to cover multiline tag start
    final Document document = editor.getDocument();
    int movedLineStart = document.getLineStartOffset(info.toMove.startLine);
    final int movedLineEnd = document.getLineEndOffset(info.toMove.endLine - 1);

    PsiElement movedEndElement = file.findElementAt(movedLineEnd);
    if (movedEndElement instanceof PsiWhiteSpace)
      movedEndElement = PsiTreeUtil.prevLeaf(movedEndElement);
    PsiElement movedStartElement = file.findElementAt(movedLineStart);
    if (movedStartElement instanceof PsiWhiteSpace)
      movedStartElement = PsiTreeUtil.nextLeaf(movedStartElement);

    if (movedEndElement == null || movedStartElement == null) return false;
    final PsiNamedElement namedParentAtEnd =
        PsiTreeUtil.getParentOfType(movedEndElement, PsiNamedElement.class);
    final PsiNamedElement namedParentAtStart =
        PsiTreeUtil.getParentOfType(movedStartElement, PsiNamedElement.class);

    final XmlText text = PsiTreeUtil.getParentOfType(movedStartElement, XmlText.class);
    final XmlText text2 = PsiTreeUtil.getParentOfType(movedEndElement, XmlText.class);

    // Let's do not care about injections for this mover
    if ((text != null && InjectedLanguageUtil.getInjectedPsiFiles(text) != null)
        || (text2 != null && InjectedLanguageUtil.getInjectedPsiFiles(text2) != null)) {
      return false;
    }

    XmlTag nearestTag = PsiTreeUtil.getParentOfType(movedStartElement, XmlTag.class);
    if (nearestTag != null
        && ("script".equals(nearestTag.getLocalName())
            || (nearestTag instanceof HtmlTag
                && "script".equalsIgnoreCase(nearestTag.getLocalName())))) {
      return false;
    }

    PsiNamedElement movedParent = null;

    if (namedParentAtEnd == namedParentAtStart) movedParent = namedParentAtEnd;
    else if (namedParentAtEnd instanceof XmlAttribute
        && namedParentAtStart instanceof XmlTag
        && namedParentAtEnd.getParent() == namedParentAtStart) {
      movedParent = namedParentAtStart;
    } else if (namedParentAtStart instanceof XmlAttribute
        && namedParentAtEnd instanceof XmlTag
        && namedParentAtStart.getParent() == namedParentAtEnd) {
      movedParent = namedParentAtEnd;
    }

    if (movedParent == null) {
      return false;
    }

    final TextRange textRange = movedParent.getTextRange();

    if (movedParent instanceof XmlTag) {
      final XmlTag tag = (XmlTag) movedParent;
      final TextRange valueRange = tag.getValue().getTextRange();
      final int valueStart = valueRange.getStartOffset();

      if (movedLineStart < valueStart && valueStart + 1 < document.getTextLength()) {
        movedLineStart = updateMovedRegionEnd(document, movedLineStart, valueStart + 1, info, down);
      }
      if (movedLineStart < valueStart) {
        movedLineStart =
            updatedMovedRegionStart(
                document, movedLineStart, tag.getTextRange().getStartOffset(), info, down);
      }
    } else if (movedParent instanceof XmlAttribute) {
      final int endOffset = textRange.getEndOffset() + 1;
      if (endOffset < document.getTextLength())
        movedLineStart = updateMovedRegionEnd(document, movedLineStart, endOffset, info, down);
      movedLineStart =
          updatedMovedRegionStart(document, movedLineStart, textRange.getStartOffset(), info, down);
    }

    final TextRange moveDestinationRange =
        new TextRange(
            document.getLineStartOffset(info.toMove2.startLine),
            document.getLineStartOffset(info.toMove2.endLine));

    if (movedParent instanceof XmlAttribute) {
      final XmlTag parent = ((XmlAttribute) movedParent).getParent();

      if (parent != null) {
        final TextRange valueRange = parent.getValue().getTextRange();

        // Do not move attributes out of tags
        if ((down && moveDestinationRange.getEndOffset() >= valueRange.getStartOffset())
            || (!down
                && moveDestinationRange.getStartOffset()
                    <= parent.getTextRange().getStartOffset())) {
          info.toMove2 = null;
        }
      }
    }

    if (down) {
      PsiElement updatedElement = file.findElementAt(moveDestinationRange.getEndOffset());
      if (updatedElement instanceof PsiWhiteSpace)
        updatedElement = PsiTreeUtil.prevLeaf(updatedElement);

      if (updatedElement != null) {
        final PsiNamedElement namedParent =
            PsiTreeUtil.getParentOfType(updatedElement, movedParent.getClass());

        if (namedParent instanceof XmlTag) {
          final XmlTag tag = (XmlTag) namedParent;
          final int offset =
              tag.isEmpty()
                  ? tag.getTextRange().getStartOffset()
                  : tag.getValue().getTextRange().getStartOffset();
          updatedMovedIntoEnd(document, info, offset);
        } else if (namedParent instanceof XmlAttribute) {
          updatedMovedIntoEnd(document, info, namedParent.getTextRange().getEndOffset());
        }
      }
    } else {
      PsiElement updatedElement = file.findElementAt(moveDestinationRange.getStartOffset());
      if (updatedElement instanceof PsiWhiteSpace)
        updatedElement = PsiTreeUtil.nextLeaf(updatedElement);

      if (updatedElement != null) {
        final PsiNamedElement namedParent =
            PsiTreeUtil.getParentOfType(updatedElement, movedParent.getClass());

        if (namedParent instanceof XmlTag) {
          final XmlTag tag = (XmlTag) namedParent;
          final TextRange tagValueRange = tag.getValue().getTextRange();

          // We need to update destination range to jump over tag start
          final XmlTag[] subtags = tag.getSubTags();
          if ((tagValueRange.contains(movedLineStart)
                  && subtags.length > 0
                  && subtags[0] == movedParent)
              || (tagValueRange.getLength() == 0
                  && tag.getTextRange().intersects(moveDestinationRange))) {
            final int line = document.getLineNumber(tag.getTextRange().getStartOffset());
            final LineRange toMove2 = info.toMove2;
            info.toMove2 = new LineRange(Math.min(line, toMove2.startLine), toMove2.endLine);
          }
        } else if (namedParent instanceof XmlAttribute) {
          final int line = document.getLineNumber(namedParent.getTextRange().getStartOffset());
          final LineRange toMove2 = info.toMove2;
          info.toMove2 = new LineRange(Math.min(line, toMove2.startLine), toMove2.endLine);
        }
      }
    }

    return true;
  }
 @NotNull
 private static AngularBindingDescriptor createBinding(PsiNamedElement field) {
   return new AngularBindingDescriptor(field, "[" + field.getName() + "]");
 }
 @NotNull
 private static AngularEventHandlerDescriptor createEvenHandler(PsiNamedElement field) {
   return new AngularEventHandlerDescriptor(field, "(" + field.getName() + ")");
 }
 public MemberInplaceRenamer(
     @NotNull PsiNamedElement elementToRename, PsiElement substituted, Editor editor) {
   this(
       elementToRename, substituted, editor, elementToRename.getName(), elementToRename.getName());
 }
  /**
   * Tries to produce signature for the exact given PSI element.
   *
   * @param element target element
   * @param buffer buffer to store the signature in
   * @return buffer that contains signature of the given element if it was produced; <code>null
   *     </code> as an indication that signature for the given element was not produced
   */
  @SuppressWarnings("unchecked")
  @Nullable
  private static StringBuilder getSignature(
      @NotNull PsiElement element, @Nullable StringBuilder buffer) {
    if (element instanceof PsiNamedElement) {
      PsiNamedElement named = (PsiNamedElement) element;
      final String name = named.getName();
      if (StringUtil.isEmpty(name)) {
        return null;
      }
      int index = getChildIndex(named, element.getParent(), name, PsiNamedElement.class);
      StringBuilder bufferToUse = buffer;
      if (bufferToUse == null) {
        bufferToUse = new StringBuilder();
      }
      bufferToUse
          .append(TYPE_MARKER)
          .append(ELEMENT_TOKENS_SEPARATOR)
          .append(escape(name))
          .append(ELEMENT_TOKENS_SEPARATOR)
          .append(index);
      return bufferToUse;
    }
    if (element instanceof PsiComment) {
      PsiElement parent = element.getParent();
      boolean nestedComment = false;
      if (parent instanceof PsiComment && parent.getTextRange().equals(element.getTextRange())) {
        parent = parent.getParent();
        nestedComment = true;
      }
      if (parent instanceof PsiNamedElement
          && (nestedComment || parent.getFirstChild() == element)) {
        // Consider doc comment element that is the first child of named element to be a doc
        // comment.
        StringBuilder bufferToUse = buffer;
        if (bufferToUse == null) {
          bufferToUse = new StringBuilder();
        }
        bufferToUse.append(TYPE_MARKER).append(ELEMENT_TOKENS_SEPARATOR).append(DOC_COMMENT_MARKER);
        return bufferToUse;
      }
    }

    PsiElement parent = element.getParent();
    if (parent instanceof PsiNamedElement && !(parent instanceof PsiFile)) {
      if (isBlockElement(element)) {
        int index = getBlockElementIndex(element);
        StringBuilder bufferToUse = buffer;
        if (bufferToUse == null) {
          bufferToUse = new StringBuilder();
        }
        bufferToUse.append(TYPE_MARKER).append(ELEMENT_TOKENS_SEPARATOR).append(CODE_BLOCK_MARKER);
        if (index > 0) {
          bufferToUse.append(ELEMENT_TOKENS_SEPARATOR).append(index);
        }
        return bufferToUse;
      }
    }

    return null;
  }
 protected TLSchemaNamedElementReferenceBase(PsiNamedElement element, TextRange rangeInElement) {
   super(element, rangeInElement);
   myName = element.getName();
 }
Esempio n. 24
0
 public DReference(@NotNull PsiNamedElement element, TextRange textRange) {
   super(element, textRange);
   name = element.getName();
 }