public static void initOffsets(final PsiFile file, final OffsetMap offsetMap) {
    int offset =
        Math.max(
            offsetMap.getOffset(CompletionInitializationContext.SELECTION_END_OFFSET),
            offsetMap.getOffset(CompletionInitializationContext.IDENTIFIER_END_OFFSET));

    PsiElement element = file.findElementAt(offset);
    if (element instanceof PsiWhiteSpace
        && (!element.textContains('\n')
            || CodeStyleSettingsManager.getSettings(file.getProject())
                .getCommonSettings(JavaLanguage.INSTANCE)
                .METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE)) {
      element = file.findElementAt(element.getTextRange().getEndOffset());
    }
    if (element == null) return;

    if (LEFT_PAREN.accepts(element)) {
      offsetMap.addOffset(LPAREN_OFFSET, element.getTextRange().getStartOffset());
      PsiElement list = element.getParent();
      PsiElement last = list.getLastChild();
      if (last instanceof PsiJavaToken
          && ((PsiJavaToken) last).getTokenType() == JavaTokenType.RPARENTH) {
        offsetMap.addOffset(RPAREN_OFFSET, last.getTextRange().getStartOffset());
      }

      offsetMap.addOffset(ARG_LIST_END_OFFSET, list.getTextRange().getEndOffset());
    }
  }
  @Override
  public boolean isInContext(@NotNull final PsiFile file, final int offset) {
    PsiElement at = file.findElementAt(offset);
    if (at == null && offset == file.getTextLength()) {
      at = file.findElementAt(offset - 1);
    }
    Language language = at != null ? at.getParent().getLanguage() : null;

    if (language instanceof XMLLanguage) {
      final PsiLanguageInjectionHost host =
          PsiTreeUtil.getParentOfType(at, PsiLanguageInjectionHost.class, false);

      if (host != null) {
        final Ref<Boolean> hasJsInjection = new Ref<Boolean>(Boolean.FALSE);

        InjectedLanguageUtil.enumerate(
            host,
            new JSResolveUtil.JSInjectedFilesVisitor() {
              @Override
              protected void process(final JSFile file) {
                hasJsInjection.set(Boolean.TRUE);
              }
            });

        if (hasJsInjection.get()) {
          language = JavaScriptSupportLoader.JAVASCRIPT.getLanguage();
        }
      }
    }
    return language != null && language.isKindOf(JavaScriptSupportLoader.JAVASCRIPT.getLanguage());
  }
 @Nullable
 private static PsiElement getSelectedPsiElement(
     final DataContext dataContext, final Project project) {
   PsiElement element = null;
   final Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
   if (editor != null) {
     final PsiFile psiFile =
         PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
     if (psiFile != null) {
       final int offset = editor.getCaretModel().getOffset();
       element = psiFile.findElementAt(offset);
       if (element == null && offset > 0 && offset == psiFile.getTextLength()) {
         element = psiFile.findElementAt(offset - 1);
       }
     }
   }
   if (element == null) {
     final PsiElement[] elements = LangDataKeys.PSI_ELEMENT_ARRAY.getData(dataContext);
     element = elements != null && elements.length > 0 ? elements[0] : null;
   }
   if (element == null) {
     final VirtualFile[] files = CommonDataKeys.VIRTUAL_FILE_ARRAY.getData(dataContext);
     if (files != null && files.length > 0) {
       element = PsiManager.getInstance(project).findFile(files[0]);
     }
   }
   return element;
 }
  @Override
  public PsiElement getPsiElement() {
    PsiFile file = getPsiFile();
    if (file == null) return null;

    int offset = getLookupStart();
    if (offset > 0) return file.findElementAt(offset - 1);

    return file.findElementAt(0);
  }
  public static void handleError(
      SAXParseException ex, PsiFile file, Document document, ValidationMessageConsumer consumer) {
    final String systemId = ex.getSystemId();
    if (LOG.isDebugEnabled()) {
      LOG.debug("RNG Schema error: " + ex.getMessage() + " [" + systemId + "]");
    }

    if (systemId != null) {
      final VirtualFile virtualFile = findVirtualFile(systemId);
      if (!Comparing.equal(virtualFile, file.getVirtualFile())) {
        return;
      }
    }

    final PsiElement at;
    final int line = ex.getLineNumber();
    if (line > 0) {
      final int column = ex.getColumnNumber();
      final int startOffset = document.getLineStartOffset(line - 1);

      if (column > 0) {
        if (file.getFileType() == RncFileType.getInstance()) {
          final PsiElement e = file.findElementAt(startOffset + column);
          if (e == null) {
            at = e;
          } else {
            at = file.findElementAt(startOffset + column - 1);
          }
        } else {
          at = file.findElementAt(startOffset + column - 2);
        }
      } else {
        final PsiElement e = file.findElementAt(startOffset);
        at = e != null ? PsiTreeUtil.nextLeaf(e) : null;
      }
    } else {
      final XmlDocument d = ((XmlFile) file).getDocument();
      assert d != null;
      final XmlTag rootTag = d.getRootTag();
      assert rootTag != null;
      at = rootTag.getFirstChild();
    }

    final PsiElement host;
    if (file instanceof RncFile) {
      host = at;
    } else {
      host = PsiTreeUtil.getParentOfType(at, XmlAttribute.class, XmlTag.class);
    }
    if (at != null && host != null) {
      consumer.onMessage(host, ex.getMessage());
    } else {
      consumer.onMessage(file, ex.getMessage());
    }
  }
    @Nullable
    private PsiComment createComment(final CharSequence buffer, final CodeInsightSettings settings)
        throws IncorrectOperationException {
      myDocument.insertString(myOffset, buffer);

      PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
      CodeStyleManager.getInstance(getProject())
          .adjustLineIndent(myFile, myOffset + buffer.length() - 2);

      PsiComment comment =
          PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);

      comment = createJavaDocStub(settings, comment, getProject());
      if (comment == null) {
        return null;
      }

      CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(getProject());
      CodeStyleSettings codeStyleSettings = CodeStyleSettingsManager.getSettings(getProject());
      boolean old = codeStyleSettings.ENABLE_JAVADOC_FORMATTING;
      codeStyleSettings.ENABLE_JAVADOC_FORMATTING = false;

      try {
        comment = (PsiComment) codeStyleManager.reformat(comment);
      } finally {
        codeStyleSettings.ENABLE_JAVADOC_FORMATTING = old;
      }
      PsiElement next = comment.getNextSibling();
      if (next == null && comment.getParent().getClass() == comment.getClass()) {
        next =
            comment
                .getParent()
                .getNextSibling(); // expanding chameleon comment produces comment under comment
      }
      if (next != null) {
        next =
            myFile.findElementAt(
                next.getTextRange().getStartOffset()); // maybe switch to another tree
      }
      if (next != null
          && (!FormatterUtil.containsWhiteSpacesOnly(next.getNode())
              || !next.getText().contains(LINE_SEPARATOR))) {
        int lineBreakOffset = comment.getTextRange().getEndOffset();
        myDocument.insertString(lineBreakOffset, LINE_SEPARATOR);
        PsiDocumentManager.getInstance(getProject()).commitAllDocuments();
        codeStyleManager.adjustLineIndent(myFile, lineBreakOffset + 1);
        comment =
            PsiTreeUtil.getNonStrictParentOfType(myFile.findElementAt(myOffset), PsiComment.class);
      }
      return comment;
    }
  private int computeIndentCount(IDocument document, int offset) {
    try {
      if (offset == document.getLength()) {
        return 0;
      }

      IFile file = EditorUtil.getFile(editor);
      if (file == null) {
        KotlinLogger.logError("Failed to retrieve IFile from editor " + editor, null);
        return 0;
      }

      if (document.get().contains(LineEndUtil.CARRIAGE_RETURN_STRING)) {
        offset -= document.getLineOfOffset(offset);
      }

      PsiFile parsedDocument = KotlinPsiManager.getKotlinFileIfExist(file, document.get());
      if (parsedDocument == null) {
        return 0;
      }

      PsiElement leaf = parsedDocument.findElementAt(offset);
      if (leaf == null) {
        return 0;
      }

      if (leaf.getNode().getElementType() != JetTokens.WHITE_SPACE) {
        leaf = parsedDocument.findElementAt(offset - 1);
      }

      int indent = 0;

      ASTNode node = null;
      if (leaf != null) {
        node = leaf.getNode();
      }
      while (node != null) {
        indent = AlignmentStrategy.updateIndent(node, indent);
        node = node.getTreeParent();
      }

      return indent;
    } catch (BadLocationException e) {
      KotlinLogger.logAndThrow(e);
    }

    return 0;
  }
  @Override
  @Nullable
  public PsiElement restoreElement() {
    long typeAndId = myStubElementTypeAndId;
    int stubId = (int) typeAndId;
    if (stubId != -1) {
      PsiFile file = restoreFile();
      if (!(file instanceof PsiFileWithStubSupport)) return null;
      short index = (short) (typeAndId >> 32);
      IStubElementType stubElementType = (IStubElementType) IElementType.find(index);
      return PsiAnchor.restoreFromStubIndex(
          (PsiFileWithStubSupport) file, stubId, stubElementType, false);
    }

    Segment psiRange = getPsiRange();
    if (psiRange == null) return null;

    PsiFile file = restoreFile();
    if (file == null) return null;
    PsiElement anchor = file.findElementAt(psiRange.getStartOffset());
    if (anchor == null) return null;

    TextRange range = anchor.getTextRange();
    if (range.getStartOffset() != psiRange.getStartOffset()
        || range.getEndOffset() != psiRange.getEndOffset()) return null;

    for (SmartPointerAnchorProvider provider : SmartPointerAnchorProvider.EP_NAME.getExtensions()) {
      final PsiElement element = provider.restoreElement(anchor);
      if (element != null) return element;
    }
    return null;
  }
  public void invoke(
      @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
    int offset = editor.getCaretModel().getOffset();
    editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
    PsiElement element = file.findElementAt(offset);

    while (true) {
      if (element == null || element instanceof PsiFile) {
        String message =
            RefactoringBundle.getCannotRefactorMessage(
                RefactoringBundle.message(
                    "the.caret.should.be.positioned.inside.a.class.to.push.members.from"));
        CommonRefactoringUtil.showErrorHint(
            project, editor, message, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
        return;
      }

      if (element instanceof PsiClass
          || element instanceof PsiField
          || element instanceof PsiMethod) {
        if (element instanceof JspClass) {
          RefactoringMessageUtil.showNotSupportedForJspClassesError(
              project, editor, REFACTORING_NAME, HelpID.MEMBERS_PUSH_DOWN);
          return;
        }
        invoke(project, new PsiElement[] {element}, dataContext);
        return;
      }
      element = element.getParent();
    }
  }
  @Override
  public void checkFile(
      @NotNull PsiFile originalFile,
      @NotNull final InspectionManager manager,
      @NotNull ProblemsHolder problemsHolder,
      @NotNull final GlobalInspectionContext globalContext,
      @NotNull final ProblemDescriptionsProcessor problemDescriptionsProcessor) {
    for (Pair<PsiFile, HighlightInfo> pair :
        runGeneralHighlighting(originalFile, highlightErrorElements, runAnnotators)) {
      PsiFile file = pair.first;
      HighlightInfo info = pair.second;
      TextRange range = new TextRange(info.startOffset, info.endOffset);
      PsiElement element = file.findElementAt(info.startOffset);

      while (element != null && !element.getTextRange().contains(range)) {
        element = element.getParent();
      }

      if (element == null) {
        element = file;
      }

      GlobalInspectionUtil.createProblem(
          element,
          info,
          range.shiftRight(-element.getNode().getStartOffset()),
          info.getProblemGroup(),
          manager,
          problemDescriptionsProcessor,
          globalContext);
    }
  }
  @Nullable
  public PsiElement getSubstituted() {
    if (mySubstituted != null && mySubstituted.isValid()) {
      if (mySubstituted instanceof PsiNameIdentifierOwner) {
        if (Comparing.strEqual(myOldName, ((PsiNameIdentifierOwner) mySubstituted).getName()))
          return mySubstituted;

        final RangeMarker rangeMarker =
            mySubstitutedRange != null ? mySubstitutedRange : myRenameOffset;
        if (rangeMarker != null)
          return PsiTreeUtil.getParentOfType(
              mySubstituted.getContainingFile().findElementAt(rangeMarker.getStartOffset()),
              PsiNameIdentifierOwner.class);
      }
      return mySubstituted;
    }
    if (mySubstitutedRange != null) {
      final PsiFile psiFile =
          PsiDocumentManager.getInstance(myProject).getPsiFile(myEditor.getDocument());
      if (psiFile != null) {
        return PsiTreeUtil.getParentOfType(
            psiFile.findElementAt(mySubstitutedRange.getStartOffset()),
            PsiNameIdentifierOwner.class);
      }
    }
    return getVariable();
  }
  @Override
  public boolean accept(@NotNull HighlightInfo highlightInfo, @Nullable PsiFile file) {
    if (null != file && HighlightSeverity.ERROR.equals(highlightInfo.getSeverity())) {
      final String description = StringUtil.notNullize(highlightInfo.getDescription());

      if (HighlightInfoType.UNHANDLED_EXCEPTION.equals(highlightInfo.type)
          && (StringUtil.startsWith(description, UNHANDLED_EXCEPTION_PREFIX_TEXT)
              || StringUtil.startsWith(description, UNHANDLED_EXCEPTIONS_PREFIX_TEXT)
              || StringUtil.startsWith(
                  description, UNHANDLED_AUTOCLOSABLE_EXCEPTIONS_PREFIX_TEXT))) {
        final String unhandledExceptions =
            description.substring(description.indexOf(':') + 1).trim();
        final String[] exceptionFQNs = unhandledExceptions.split(",");
        if (exceptionFQNs.length > 0) {
          final PsiMethod psiMethod =
              PsiTreeUtil.getParentOfType(
                  file.findElementAt(highlightInfo.getStartOffset()), PsiMethod.class);
          if (null != psiMethod) {
            return !SneakyTrowsExceptionHandler.isExceptionHandled(psiMethod, exceptionFQNs);
          }
        }
      }
    }
    return true;
  }
Esempio n. 13
0
  @Nullable
  public static I18nQuickFixHandler getHandler(final AnActionEvent e) {
    final Editor editor = getEditor(e);
    if (editor == null) return null;

    PsiFile psiFile = e.getData(LangDataKeys.PSI_FILE);
    if (psiFile == null) return null;

    TextRange range = JavaI18nUtil.getSelectedRange(editor, psiFile);
    if (range == null) return null;

    final PsiLiteralExpression literalExpression = getEnclosingStringLiteral(psiFile, editor);
    PsiElement element = psiFile.findElementAt(editor.getCaretModel().getOffset());
    if (element == null) return null;
    if (I18nizeConcatenationQuickFix.getEnclosingLiteralConcatenation(element) != null) {
      return new I18nizeConcatenationQuickFix();
    } else if (literalExpression != null && literalExpression.getTextRange().contains(range)) {
      return new I18nizeQuickFix();
    }

    for (I18nizeHandlerProvider handlerProvider : I18nizeHandlerProvider.EP_NAME.getExtensions()) {
      I18nQuickFixHandler handler = handlerProvider.getHandler(psiFile, editor, range);
      if (handler != null) {
        return handler;
      }
    }

    return null;
  }
  public static String findUrl(PsiFile file, int offset, String uri) {
    final PsiElement currentElement = file.findElementAt(offset);
    final XmlAttribute attribute = PsiTreeUtil.getParentOfType(currentElement, XmlAttribute.class);

    if (attribute != null) {
      final XmlTag tag = PsiTreeUtil.getParentOfType(currentElement, XmlTag.class);

      if (tag != null) {
        final String prefix = tag.getPrefixByNamespace(XmlUtil.XML_SCHEMA_INSTANCE_URI);
        if (prefix != null) {
          final String attrValue =
              tag.getAttributeValue(XmlUtil.SCHEMA_LOCATION_ATT, XmlUtil.XML_SCHEMA_INSTANCE_URI);
          if (attrValue != null) {
            final StringTokenizer tokenizer = new StringTokenizer(attrValue);

            while (tokenizer.hasMoreElements()) {
              if (uri.equals(tokenizer.nextToken())) {
                if (!tokenizer.hasMoreElements()) return uri;
                final String url = tokenizer.nextToken();

                return url.startsWith(HTTP_PROTOCOL) ? url : uri;
              }

              if (!tokenizer.hasMoreElements()) return uri;
              tokenizer.nextToken(); // skip file location
            }
          }
        }
      }
    }
    return uri;
  }
  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);
            });
  }
  @Override
  @Nullable
  protected TextRange surroundStatement(
      @NotNull Project project, @NotNull Editor editor, @NotNull PsiElement[] elements)
      throws IncorrectOperationException {
    PyTryExceptStatement tryStatement =
        PyElementGenerator.getInstance(project)
            .createFromText(LanguageLevel.getDefault(), PyTryExceptStatement.class, getTemplate());
    final PsiElement parent = elements[0].getParent();
    final PyStatementList statementList = tryStatement.getTryPart().getStatementList();
    statementList.addRange(elements[0], elements[elements.length - 1]);
    statementList.getFirstChild().delete();
    tryStatement = (PyTryExceptStatement) parent.addBefore(tryStatement, elements[0]);
    parent.deleteChildRange(elements[0], elements[elements.length - 1]);

    final PsiFile psiFile = parent.getContainingFile();
    final Document document = psiFile.getViewProvider().getDocument();
    final TextRange range = tryStatement.getTextRange();
    assert document != null;
    final RangeMarker rangeMarker = document.createRangeMarker(range);

    final PsiElement element = psiFile.findElementAt(rangeMarker.getStartOffset());
    tryStatement = PsiTreeUtil.getParentOfType(element, PyTryExceptStatement.class);
    if (tryStatement != null) {
      return getResultRange(tryStatement);
    }
    return null;
  }
  @NotNull
  @Override
  public CharSequence adjustWhiteSpaceIfNecessary(
      @NotNull CharSequence whiteSpaceText,
      int startOffset,
      int endOffset,
      ASTNode nodeAfter,
      boolean changedViaPsi) {
    if (!changedViaPsi) {
      return myWhiteSpaceStrategy.adjustWhiteSpaceIfNecessary(
          whiteSpaceText,
          myDocument.getCharsSequence(),
          startOffset,
          endOffset,
          mySettings,
          nodeAfter);
    }

    final PsiElement element = myFile.findElementAt(startOffset);
    if (element == null) {
      return whiteSpaceText;
    } else {
      return myWhiteSpaceStrategy.adjustWhiteSpaceIfNecessary(
          whiteSpaceText, element, startOffset, endOffset, mySettings);
    }
  }
  protected boolean shouldParenthesizeQualifier(
      final PsiFile file, final int startOffset, final int endOffset) {
    PsiElement element = file.findElementAt(startOffset);
    if (element == null) {
      return false;
    }

    PsiElement last = element;
    while (element != null
        && element.getTextRange().getStartOffset() >= startOffset
        && element.getTextRange().getEndOffset() <= endOffset
        && !(element instanceof PsiExpressionStatement)) {
      last = element;
      element = element.getParent();
    }
    PsiExpression expr =
        PsiTreeUtil.getParentOfType(last, PsiExpression.class, false, PsiClass.class);
    if (expr == null) {
      return false;
    }
    if (expr.getTextRange().getEndOffset() > endOffset) {
      return true;
    }

    if (expr instanceof PsiJavaCodeReferenceElement
        || expr instanceof PsiMethodCallExpression
        || expr instanceof PsiArrayAccessExpression) {
      return false;
    }

    return true;
  }
 private static boolean navigateInCurrentEditor(
     @NotNull PsiElement element, @NotNull PsiFile currentFile, @NotNull Editor currentEditor) {
   if (element.getContainingFile() == currentFile) {
     int offset = element.getTextOffset();
     PsiElement leaf = currentFile.findElementAt(offset);
     // check that element is really physically inside the file
     // there are fake elements with custom navigation (e.g. opening URL in browser) that override
     // getContainingFile for various reasons
     if (leaf != null && PsiTreeUtil.isAncestor(element, leaf, false)) {
       Project project = element.getProject();
       CommandProcessor.getInstance()
           .executeCommand(
               project,
               () -> {
                 IdeDocumentHistory.getInstance(project).includeCurrentCommandAsNavigation();
                 new OpenFileDescriptor(
                         project, currentFile.getViewProvider().getVirtualFile(), offset)
                     .navigateIn(currentEditor);
               },
               "",
               null);
       return true;
     }
   }
   return false;
 }
 @NotNull
 private static Collection<PsiLanguageInjectionHost> collectInjectionHosts(
     @NotNull PsiFile file, @NotNull TextRange range) {
   Stack<PsiElement> toProcess = new Stack<PsiElement>();
   for (PsiElement e = file.findElementAt(range.getStartOffset());
       e != null;
       e = e.getNextSibling()) {
     if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
       break;
     }
     toProcess.push(e);
   }
   if (toProcess.isEmpty()) {
     return Collections.emptySet();
   }
   Set<PsiLanguageInjectionHost> result = null;
   while (!toProcess.isEmpty()) {
     PsiElement e = toProcess.pop();
     if (e instanceof PsiLanguageInjectionHost) {
       if (result == null) {
         result = ContainerUtilRt.newHashSet();
       }
       result.add((PsiLanguageInjectionHost) e);
     } else {
       for (PsiElement child = e.getFirstChild(); child != null; child = child.getNextSibling()) {
         if (e.getTextRange().getStartOffset() >= range.getEndOffset()) {
           break;
         }
         toProcess.push(child);
       }
     }
   }
   return result == null ? Collections.<PsiLanguageInjectionHost>emptySet() : result;
 }
Esempio n. 21
0
  public static TextWithImports getEditorText(final Editor editor) {
    if (editor == null) {
      return null;
    }
    final Project project = editor.getProject();
    if (project == null) return null;

    String defaultExpression = editor.getSelectionModel().getSelectedText();
    if (defaultExpression == null) {
      int offset = editor.getCaretModel().getOffset();
      PsiFile psiFile = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (psiFile != null) {
        PsiElement elementAtCursor = psiFile.findElementAt(offset);
        if (elementAtCursor != null) {
          final EditorTextProvider textProvider =
              EditorTextProvider.EP.forLanguage(elementAtCursor.getLanguage());
          if (textProvider != null) {
            final TextWithImports editorText = textProvider.getEditorText(elementAtCursor);
            if (editorText != null) return editorText;
          }
        }
      }
    } else {
      return new TextWithImportsImpl(CodeFragmentKind.EXPRESSION, defaultExpression);
    }
    return null;
  }
Esempio n. 22
0
    public PsiFile resolve() {
      final PsiFile referencedFile = getReferencedFile();
      if (referencedFile != null) {
        return referencedFile;
      }

      if (myPsiFile != null) {
        final PsiElement psiElement = myPsiFile.findElementAt(myLinkInfo.offset);
        if (psiElement != null) {
          final PsiElement parent = psiElement.getParent();
          if (parent instanceof XmlTag) {
            final XmlAttribute attribute = ((XmlTag) parent).getAttribute(HREF_ATTR);
            if (attribute != null) {
              final XmlAttributeValue value = attribute.getValueElement();
              if (value != null) {
                final PsiReference[] references = value.getReferences();
                for (PsiReference reference : references) {
                  final PsiElement element = reference.resolve();
                  if (element instanceof PsiFile) {
                    return (PsiFile) element;
                  }
                }
              }
            }
          }
        }
      }

      return null;
    }
  protected void moveCaretInsideBracesIfAny(
      @NotNull final Editor editor, @NotNull final PsiFile file)
      throws IncorrectOperationException {
    int caretOffset = editor.getCaretModel().getOffset();
    final CharSequence chars = editor.getDocument().getCharsSequence();

    if (CharArrayUtil.regionMatches(chars, caretOffset, "{}")) {
      caretOffset += 2;
    } else if (CharArrayUtil.regionMatches(chars, caretOffset, "{\n}")) {
      caretOffset += 3;
    }

    caretOffset = CharArrayUtil.shiftBackward(chars, caretOffset - 1, " \t") + 1;

    if (CharArrayUtil.regionMatches(chars, caretOffset - "{}".length(), "{}")
        || CharArrayUtil.regionMatches(chars, caretOffset - "{\n}".length(), "{\n}")) {
      commit(editor);
      final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(file.getProject());
      final boolean old = settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE;
      settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = false;
      PsiElement elt =
          PsiTreeUtil.getParentOfType(file.findElementAt(caretOffset - 1), PsiCodeBlock.class);
      reformat(elt);
      settings.KEEP_SIMPLE_BLOCKS_IN_ONE_LINE = old;
      editor.getCaretModel().moveToOffset(caretOffset - 1);
    }
  }
 public void invoke(
     @NotNull Project project, Editor editor, PsiFile file, DataContext dataContext) {
   editor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
   final int offset =
       TargetElementUtil.adjustOffset(
           file, editor.getDocument(), editor.getCaretModel().getOffset());
   final PsiElement element = file.findElementAt(offset);
   PsiTypeElement typeElement = PsiTreeUtil.getParentOfType(element, PsiTypeElement.class);
   while (typeElement != null) {
     final PsiElement parent = typeElement.getParent();
     PsiElement[] toMigrate = null;
     if (parent instanceof PsiVariable) {
       toMigrate = extractReferencedVariables(typeElement);
     } else if ((parent instanceof PsiMember && !(parent instanceof PsiClass))
         || isClassArgument(parent)) {
       toMigrate = new PsiElement[] {parent};
     }
     if (toMigrate != null && toMigrate.length > 0) {
       invoke(project, toMigrate, null, null, editor);
       return;
     }
     typeElement = PsiTreeUtil.getParentOfType(parent, PsiTypeElement.class, false);
   }
   CommonRefactoringUtil.showErrorHint(
       project,
       editor,
       "The caret should be positioned on type of field, variable, method or method parameter to be refactored",
       REFACTORING_NAME,
       "refactoring.migrateType");
 }
Esempio n. 25
0
  public static PsiElement[] parsePattern(
      Project project,
      String context,
      String pattern,
      FileType fileType,
      Language language,
      String extension,
      boolean physical) {
    int offset = context.indexOf(PATTERN_PLACEHOLDER);

    final int patternLength = pattern.length();
    final String patternInContext = context.replace(PATTERN_PLACEHOLDER, pattern);

    final String ext = extension != null ? extension : fileType.getDefaultExtension();
    final String name = "__dummy." + ext;
    final PsiFileFactory factory = PsiFileFactory.getInstance(project);

    final PsiFile file =
        language == null
            ? factory.createFileFromText(
                name, fileType, patternInContext, LocalTimeCounter.currentTime(), physical, true)
            : factory.createFileFromText(name, language, patternInContext, physical, true);
    if (file == null) {
      return PsiElement.EMPTY_ARRAY;
    }

    final List<PsiElement> result = new ArrayList<PsiElement>();

    PsiElement element = file.findElementAt(offset);
    if (element == null) {
      return PsiElement.EMPTY_ARRAY;
    }

    PsiElement topElement = element;
    element = element.getParent();

    while (element != null) {
      if (element.getTextRange().getStartOffset() == offset
          && element.getTextLength() <= patternLength) {
        topElement = element;
      }
      element = element.getParent();
    }

    if (topElement instanceof PsiFile) {
      return topElement.getChildren();
    }

    final int endOffset = offset + patternLength;
    result.add(topElement);
    topElement = topElement.getNextSibling();

    while (topElement != null && topElement.getTextRange().getEndOffset() <= endOffset) {
      result.add(topElement);
      topElement = topElement.getNextSibling();
    }

    return result.toArray(new PsiElement[result.size()]);
  }
Esempio n. 26
0
 /** Decompiler aware version */
 @Nullable
 public static PsiElement findElementAt(@Nullable PsiFile file, int offset) {
   if (file instanceof PsiCompiledFile) {
     file = ((PsiCompiledFile) file).getDecompiledPsiFile();
   }
   if (file == null) return null;
   return file.findElementAt(offset);
 }
 private static PsiElement getTargetElement(final Editor editor, final Project project) {
   int offset = editor.getCaretModel().getOffset();
   PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
   if (file == null) return null;
   PsiElement element = file.findElementAt(offset);
   if (element == null) element = file;
   return element;
 }
 @Nullable
 private static PsiClass findTargetClass(@NotNull Editor editor, @NotNull PsiFile file) {
   int offset = editor.getCaretModel().getOffset();
   PsiElement element = file.findElementAt(offset);
   return PsiTreeUtil.getParentOfType(element, PsiClass.class, false) == null
       ? null
       : TestIntegrationUtils.findOuterClass(element);
 }
  // returns editor,file where the action is available or null if there are none
  public static boolean availableFor(
      @NotNull PsiFile file, @NotNull Editor editor, @NotNull IntentionAction action) {
    if (!file.isValid()) return false;

    int offset = editor.getCaretModel().getOffset();
    PsiElement element = file.findElementAt(offset);
    boolean inProject = file.getManager().isInProject(file);
    return isAvailableHere(editor, file, element, inProject, action);
  }
 @Nullable
 private static XmlTag getEditorTag(Editor editor, PsiFile file) {
   final int offset = editor.getCaretModel().getOffset();
   final PsiElement psiElement = file.findElementAt(offset);
   if (psiElement != null) {
     return PsiTreeUtil.getParentOfType(psiElement, XmlTag.class, false);
   }
   return null;
 }