コード例 #1
0
  /**
   * Arranges given PSI root contents that belong to the given ranges.
   *
   * @param file target PSI root
   * @param ranges target ranges to use within the given root
   */
  @SuppressWarnings("MethodMayBeStatic")
  public void arrange(
      @NotNull PsiFile file,
      @NotNull Collection<TextRange> ranges,
      @Nullable final ArrangementCallback callback) {
    final Document document = PsiDocumentManager.getInstance(file.getProject()).getDocument(file);
    if (document == null) {
      return;
    }

    final Rearranger<?> rearranger = Rearranger.EXTENSION.forLanguage(file.getLanguage());
    if (rearranger == null) {
      return;
    }

    final CodeStyleSettings settings =
        CodeStyleSettingsManager.getInstance(file.getProject()).getCurrentSettings();
    ArrangementSettings arrangementSettings =
        settings.getCommonSettings(file.getLanguage()).getArrangementSettings();
    if (arrangementSettings == null && rearranger instanceof ArrangementStandardSettingsAware) {
      arrangementSettings = ((ArrangementStandardSettingsAware) rearranger).getDefaultSettings();
    }

    if (arrangementSettings == null) {
      return;
    }

    final DocumentEx documentEx;
    if (document instanceof DocumentEx && !((DocumentEx) document).isInBulkUpdate()) {
      documentEx = (DocumentEx) document;
    } else {
      documentEx = null;
    }

    final Context<? extends ArrangementEntry> context =
        Context.from(rearranger, document, file, ranges, arrangementSettings, settings);

    ApplicationManager.getApplication()
        .runWriteAction(
            new Runnable() {
              @Override
              public void run() {
                if (documentEx != null) {
                  // documentEx.setInBulkUpdate(true);
                }
                try {
                  doArrange(context);
                  if (callback != null) {
                    callback.afterArrangement(context.moveInfos);
                  }
                } finally {
                  if (documentEx != null) {
                    // documentEx.setInBulkUpdate(false);
                  }
                }
              }
            });
  }
コード例 #2
0
  public static boolean isValidName(
      final Project project, final PsiElement psiElement, final String newName) {
    if (newName == null || newName.length() == 0) {
      return false;
    }
    final Condition<String> inputValidator =
        RenameInputValidatorRegistry.getInputValidator(psiElement);
    if (inputValidator != null) {
      return inputValidator.value(newName);
    }
    if (psiElement instanceof PsiFile || psiElement instanceof PsiDirectory) {
      return newName.indexOf('\\') < 0 && newName.indexOf('/') < 0;
    }
    if (psiElement instanceof PomTargetPsiElement) {
      return !StringUtil.isEmptyOrSpaces(newName);
    }

    final PsiFile file = psiElement.getContainingFile();
    final Language elementLanguage = psiElement.getLanguage();

    final Language fileLanguage = file == null ? null : file.getLanguage();
    Language language =
        fileLanguage == null
            ? elementLanguage
            : fileLanguage.isKindOf(elementLanguage) ? fileLanguage : elementLanguage;

    return LanguageNamesValidation.INSTANCE
        .forLanguage(language)
        .isIdentifier(newName.trim(), project);
  }
  private void highlightInjectedSyntax(
      @NotNull PsiFile injectedPsi, @NotNull HighlightInfoHolder holder) {
    List<Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange>>
        tokens = InjectedLanguageUtil.getHighlightTokens(injectedPsi);
    if (tokens == null) return;

    final Language injectedLanguage = injectedPsi.getLanguage();
    Project project = injectedPsi.getProject();
    SyntaxHighlighter syntaxHighlighter =
        SyntaxHighlighterFactory.getSyntaxHighlighter(
            injectedLanguage, project, injectedPsi.getVirtualFile());
    final TextAttributes defaultAttrs = myGlobalScheme.getAttributes(HighlighterColors.TEXT);

    for (Trinity<IElementType, SmartPsiElementPointer<PsiLanguageInjectionHost>, TextRange> token :
        tokens) {
      ProgressManager.checkCanceled();
      IElementType tokenType = token.getFirst();
      PsiLanguageInjectionHost injectionHost = token.getSecond().getElement();
      if (injectionHost == null) continue;
      TextRange textRange = token.getThird();
      TextAttributesKey[] keys = syntaxHighlighter.getTokenHighlights(tokenType);
      if (textRange.getLength() == 0) continue;

      TextRange annRange = textRange.shiftRight(injectionHost.getTextRange().getStartOffset());
      // force attribute colors to override host' ones
      TextAttributes attributes = null;
      for (TextAttributesKey key : keys) {
        TextAttributes attrs2 = myGlobalScheme.getAttributes(key);
        if (attrs2 != null) {
          attributes = attributes == null ? attrs2 : TextAttributes.merge(attributes, attrs2);
        }
      }
      TextAttributes forcedAttributes;
      if (attributes == null || attributes.isEmpty() || attributes.equals(defaultAttrs)) {
        forcedAttributes = TextAttributes.ERASE_MARKER;
      } else {
        HighlightInfo info =
            HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
                .range(annRange)
                .textAttributes(TextAttributes.ERASE_MARKER)
                .createUnconditionally();
        holder.add(info);

        forcedAttributes =
            new TextAttributes(
                attributes.getForegroundColor(),
                attributes.getBackgroundColor(),
                attributes.getEffectColor(),
                attributes.getEffectType(),
                attributes.getFontType());
      }

      HighlightInfo info =
          HighlightInfo.newHighlightInfo(HighlightInfoType.INJECTED_LANGUAGE_FRAGMENT)
              .range(annRange)
              .textAttributes(forcedAttributes)
              .createUnconditionally();
      holder.add(info);
    }
  }
コード例 #4
0
  @Nullable
  public static Commenter getCommenter(
      final PsiFile file,
      final Editor editor,
      final Language lineStartLanguage,
      final Language lineEndLanguage) {

    final FileViewProvider viewProvider = file.getViewProvider();

    for (MultipleLangCommentProvider provider :
        MultipleLangCommentProvider.EP_NAME.getExtensions()) {
      if (provider.canProcess(file, viewProvider)) {
        return provider.getLineCommenter(file, editor, lineStartLanguage, lineEndLanguage);
      }
    }

    final Language fileLanguage = file.getLanguage();
    Language lang =
        lineStartLanguage == null
                || LanguageCommenters.INSTANCE.forLanguage(lineStartLanguage) == null
                || fileLanguage.getBaseLanguage()
                    == lineStartLanguage // file language is a more specific dialect of the line
            // language
            ? fileLanguage
            : lineStartLanguage;

    if (viewProvider instanceof TemplateLanguageFileViewProvider
        && lang == ((TemplateLanguageFileViewProvider) viewProvider).getTemplateDataLanguage()) {
      lang = viewProvider.getBaseLanguage();
    }

    return LanguageCommenters.INSTANCE.forLanguage(lang);
  }
コード例 #5
0
  private static boolean isEnabled(DataContext dataContext) {
    Project project = CommonDataKeys.PROJECT.getData(dataContext);
    if (project == null
        || EditorGutter.KEY.getData(dataContext) != null
        || Boolean.TRUE.equals(dataContext.getData(CommonDataKeys.EDITOR_VIRTUAL_SPACE))) {
      return false;
    }

    Editor editor = CommonDataKeys.EDITOR.getData(dataContext);
    if (editor == null) {
      UsageTarget[] target = UsageView.USAGE_TARGETS_KEY.getData(dataContext);
      return target != null && target.length > 0;
    } else {
      PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
      if (file == null) {
        return false;
      }

      Language language = PsiUtilBase.getLanguageInEditor(editor, project);
      if (language == null) {
        language = file.getLanguage();
      }
      return !(LanguageFindUsages.INSTANCE.forLanguage(language)
          instanceof EmptyFindUsagesProvider);
    }
  }
コード例 #6
0
  public void commentRange(
      int startOffset,
      int endOffset,
      String commentPrefix,
      String commentSuffix,
      Commenter commenter) {
    final CharSequence chars = myDocument.getCharsSequence();
    LogicalPosition caretPosition = myCaret.getLogicalPosition();

    if (startOffset == 0 || chars.charAt(startOffset - 1) == '\n') {
      if (endOffset == myDocument.getTextLength()
          || endOffset > 0 && chars.charAt(endOffset - 1) == '\n') {
        CodeStyleManager codeStyleManager = CodeStyleManager.getInstance(myProject);
        CommonCodeStyleSettings settings =
            CodeStyleSettingsManager.getSettings(myProject).getCommonSettings(myFile.getLanguage());
        String space;
        if (!settings.BLOCK_COMMENT_AT_FIRST_COLUMN) {
          final FileType fileType = myFile.getFileType();
          int line1 = myEditor.offsetToLogicalPosition(startOffset).line;
          int line2 = myEditor.offsetToLogicalPosition(endOffset - 1).line;
          Indent minIndent =
              CommentUtil.getMinLineIndent(myProject, myDocument, line1, line2, fileType);
          if (minIndent == null) {
            minIndent = codeStyleManager.zeroIndent();
          }
          space = codeStyleManager.fillIndent(minIndent, fileType);
        } else {
          space = "";
        }
        final StringBuilder nestingPrefix = new StringBuilder(space).append(commentPrefix);
        if (!commentPrefix.endsWith("\n")) {
          nestingPrefix.append("\n");
        }
        final StringBuilder nestingSuffix = new StringBuilder(space);
        nestingSuffix.append(
            commentSuffix.startsWith("\n") ? commentSuffix.substring(1) : commentSuffix);
        nestingSuffix.append("\n");
        TextRange range =
            insertNestedComments(
                startOffset,
                endOffset,
                nestingPrefix.toString(),
                nestingSuffix.toString(),
                commenter);
        myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
        LogicalPosition pos = new LogicalPosition(caretPosition.line + 1, caretPosition.column);
        myCaret.moveToLogicalPosition(pos);
        return;
      }
    }

    TextRange range =
        insertNestedComments(startOffset, endOffset, commentPrefix, commentSuffix, commenter);
    myCaret.setSelection(range.getStartOffset(), range.getEndOffset());
    LogicalPosition pos =
        new LogicalPosition(caretPosition.line, caretPosition.column + commentPrefix.length());
    myCaret.moveToLogicalPosition(pos);
  }
コード例 #7
0
 private static boolean isCopyUpToDate(Document document, @NotNull PsiFile file) {
   if (!file.isValid()) {
     return false;
   }
   // the psi file cache might have been cleared by some external activity,
   // in which case PSI-document sync may stop working
   PsiFile current = PsiDocumentManager.getInstance(file.getProject()).getPsiFile(document);
   return current != null && current.getViewProvider().getPsi(file.getLanguage()) == file;
 }
コード例 #8
0
 @Nullable
 public static String findUri(PsiFile file, int offset) {
   PsiReference currentRef = file.getViewProvider().findReferenceAt(offset, file.getLanguage());
   if (currentRef == null) currentRef = file.getViewProvider().findReferenceAt(offset);
   if (currentRef instanceof URLReference || currentRef instanceof DependentNSReference) {
     return currentRef.getCanonicalText();
   }
   return null;
 }
コード例 #9
0
 @Override
 public void beforeCharDeleted(final char c, final PsiFile file, final Editor editor) {
   Language _language = file.getLanguage();
   final IdeaAutoEditHandler autoEditHandler =
       IdeaAutoEditHandlerExtension.INSTANCE.forLanguage(_language);
   boolean _notEquals = (!Objects.equal(autoEditHandler, null));
   if (_notEquals) {
     autoEditHandler.beforeCharDeleted(c, file, ((EditorEx) editor));
   }
 }
コード例 #10
0
 @NotNull
 @Override
 public PsiElementVisitor buildVisitor(@NotNull ProblemsHolder holder, boolean isOnTheFly) {
   PsiFile psiFile = holder.getFile();
   if (psiFile.getLanguage() != JavaLanguage.INSTANCE
       || !PsiUtil.isLanguageLevel5OrHigher(psiFile)) {
     return new PsiElementVisitor() {};
   }
   return super.buildVisitor(holder, isOnTheFly);
 }
コード例 #11
0
 public FormattingDocumentModelImpl(@NotNull final Document document, PsiFile file) {
   myDocument = document;
   myFile = file;
   if (file != null) {
     Language language = file.getLanguage();
     myWhiteSpaceStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy(language);
   } else {
     myWhiteSpaceStrategy = WhiteSpaceFormattingStrategyFactory.getStrategy();
   }
   mySettings = CodeStyleSettingsManager.getSettings(file != null ? file.getProject() : null);
 }
コード例 #12
0
 public static void initState(
     ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
   state.extendsSets = extendsSets;
   PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
   state.completionState = file == null ? null : file.getUserData(COMPLETION_STATE_KEY);
   Language language = file == null ? root.getLanguage() : file.getLanguage();
   state.caseSensitive = language.isCaseSensitive();
   PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
   state.braces = matcher == null ? null : matcher.getPairs();
   if (state.braces != null && state.braces.length == 0) state.braces = null;
 }
コード例 #13
0
 @Nullable
 public UsageType getUsageType(PsiElement element) {
   final PsiFile psiFile = element.getContainingFile();
   if (XMLLanguage.INSTANCE.equals(psiFile.getLanguage())
       && DomManager.getDomManager(element.getProject())
               .getFileElement((XmlFile) psiFile, DomElement.class)
           != null) {
     return DOM_USAGE_TYPE;
   }
   return null;
 }
コード例 #14
0
  @Nullable
  public ProblemDescriptor[] checkFile(
      @NotNull PsiFile file, @NotNull InspectionManager manager, boolean isOnTheFly) {
    final Language language = file.getLanguage();
    if (!acceptsLanguage(language)) return null;

    final Visitor visitor = createVisitor(manager, isOnTheFly);

    file.accept(visitor);

    return visitor.getProblems();
  }
コード例 #15
0
 @Override
 public CharSequence getText(final TextRange textRange) {
   if (textRange.getStartOffset() < 0 || textRange.getEndOffset() > myDocument.getTextLength()) {
     LOG.error(
         String.format(
             "Please submit a ticket to the tracker and attach current source file to it!%nInvalid processing detected: given text "
                 + "range (%s) targets non-existing regions (the boundaries are [0; %d)). File's language: %s",
             textRange, myDocument.getTextLength(), myFile.getLanguage()));
   }
   return myDocument
       .getCharsSequence()
       .subSequence(textRange.getStartOffset(), textRange.getEndOffset());
 }
 @Override
 public Result preprocessEnter(
     @NotNull PsiFile file,
     @NotNull Editor editor,
     @NotNull Ref<Integer> caretOffsetRef,
     @NotNull Ref<Integer> caretAdvance,
     @NotNull DataContext dataContext,
     EditorActionHandler originalHandler) {
   if (!file.getLanguage().is(JsonLanguage.INSTANCE)) {
     return Result.Continue;
   }
   return super.preprocessEnter(
       file, editor, caretOffsetRef, caretAdvance, dataContext, originalHandler);
 }
コード例 #17
0
  public String processPrimaryFragment(
      final T firstToExtract,
      final T lastToExtract,
      final PsiDirectory targetDirectory,
      final String targetfileName,
      final PsiFile srcFile)
      throws IncorrectOperationException {
    final String includePath =
        doExtract(
            targetDirectory, targetfileName, firstToExtract, lastToExtract, srcFile.getLanguage());

    doReplaceRange(includePath, firstToExtract, lastToExtract);
    return includePath;
  }
コード例 #18
0
  private void updateState() {
    myCbIncludeSubdirs.setEnabled(myRbDirectory.isSelected());
    myCbOptimizeImports.setEnabled(
        !myRbSelectedText.isSelected()
            && !(myFile != null
                && LanguageImportStatements.INSTANCE.forFile(myFile).isEmpty()
                && myRbFile.isSelected()));
    myCbArrangeEntries.setEnabled(
        myFile != null && Rearranger.EXTENSION.forLanguage(myFile.getLanguage()) != null);

    myCbOnlyVcsChangedRegions.setEnabled(canTargetVcsRegions());
    myDoNotAskMeCheckBox.setEnabled(!myRbDirectory.isSelected());
    myRbDirectory.setEnabled(!myDoNotAskMeCheckBox.isSelected());
  }
コード例 #19
0
 private static void initState(IElementType root, PsiBuilder builder, ErrorState state) {
   PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
   state.completionState = file == null ? null : file.getUserData(COMPLETION_STATE_KEY);
   Language language = file == null ? root.getLanguage() : file.getLanguage();
   state.caseSensitive = language.isCaseSensitive();
   ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
   if (parserDefinition != null) {
     state.commentTokens = parserDefinition.getCommentTokens();
     state.whitespaceTokens = parserDefinition.getWhitespaceTokens();
   }
   PairedBraceMatcher matcher = LanguageBraceMatching.INSTANCE.forLanguage(language);
   state.braces = matcher == null ? null : matcher.getPairs();
   if (state.braces != null && state.braces.length == 0) state.braces = null;
 }
コード例 #20
0
 @Override
 public List<ReferenceType> getAllClasses(final SourcePosition source) throws NoDataException {
   PsiFile _file = source.getFile();
   Language _language = _file.getLanguage();
   boolean _notEquals = (!Objects.equal(_language, this.language));
   if (_notEquals) {
     throw NoDataException.INSTANCE;
   }
   final Map<URI, AbstractTraceRegion> traces =
       this._debugProcessExtensions.getTracesForSource(this.process, source);
   final ArrayList<ReferenceType> allClasses = CollectionLiterals.<ReferenceType>newArrayList();
   final int line = source.getLine();
   Set<Map.Entry<URI, AbstractTraceRegion>> _entrySet = traces.entrySet();
   for (final Map.Entry<URI, AbstractTraceRegion> uri2trace : _entrySet) {
     {
       AbstractTraceRegion _value = uri2trace.getValue();
       TreeIterator<AbstractTraceRegion> _treeIterator = _value.treeIterator();
       final Function1<AbstractTraceRegion, Boolean> _function =
           new Function1<AbstractTraceRegion, Boolean>() {
             @Override
             public Boolean apply(final AbstractTraceRegion it) {
               List<ILocationData> _associatedLocations = it.getAssociatedLocations();
               ILocationData _head =
                   IterableExtensions.<ILocationData>head(_associatedLocations);
               int _lineNumber = 0;
               if (_head != null) {
                 _lineNumber = _head.getLineNumber();
               }
               return Boolean.valueOf((_lineNumber == line));
             }
           };
       final AbstractTraceRegion region =
           IteratorExtensions.<AbstractTraceRegion>findFirst(_treeIterator, _function);
       boolean _notEquals_1 = (!Objects.equal(region, null));
       if (_notEquals_1) {
         URI _key = uri2trace.getKey();
         final PsiFile psiFile = this._debugProcessExtensions.getPsiFile(this.process, _key);
         PositionManagerImpl _javaPositionManger =
             this._debugProcessExtensions.getJavaPositionManger(this.process);
         int _myLineNumber = region.getMyLineNumber();
         int _plus = (_myLineNumber + 1);
         SourcePosition _createFromLine = SourcePosition.createFromLine(psiFile, _plus);
         final List<ReferenceType> classes = _javaPositionManger.getAllClasses(_createFromLine);
         allClasses.addAll(classes);
       }
     }
   }
   return allClasses;
 }
コード例 #21
0
  public static Set<TemplateContextType> getApplicableContextTypes(PsiFile file, int offset) {
    Set<TemplateContextType> result = getDirectlyApplicableContextTypes(file, offset);

    Language baseLanguage = file.getViewProvider().getBaseLanguage();
    if (baseLanguage != file.getLanguage()) {
      PsiFile basePsi = file.getViewProvider().getPsi(baseLanguage);
      if (basePsi != null) {
        result.addAll(getDirectlyApplicableContextTypes(basePsi, offset));
      }
    }

    // if we have, for example, a Ruby fragment in RHTML selected with its exact bounds, the file
    // language and the base
    // language will be ERb, so we won't match HTML templates for it. but they're actually valid
    Language languageAtOffset = PsiUtilCore.getLanguageAtOffset(file, offset);
    if (languageAtOffset != file.getLanguage() && languageAtOffset != baseLanguage) {
      PsiFile basePsi = file.getViewProvider().getPsi(languageAtOffset);
      if (basePsi != null) {
        result.addAll(getDirectlyApplicableContextTypes(basePsi, offset));
      }
    }

    return result;
  }
コード例 #22
0
 @Override
 public boolean charDeleted(final char c, final PsiFile file, final Editor editor) {
   boolean _xblockexpression = false;
   {
     Language _language = file.getLanguage();
     final IdeaAutoEditHandler autoEditHandler =
         IdeaAutoEditHandlerExtension.INSTANCE.forLanguage(_language);
     boolean _xifexpression = false;
     boolean _notEquals = (!Objects.equal(autoEditHandler, null));
     if (_notEquals) {
       _xifexpression = autoEditHandler.charDeleted(c, file, ((EditorEx) editor));
     } else {
       _xifexpression = false;
     }
     _xblockexpression = _xifexpression;
   }
   return _xblockexpression;
 }
コード例 #23
0
ファイル: GlancePanel.java プロジェクト: Natinux/CodeGlance
  /** Fires off a new task to the worker thread. This should only be called from the ui thread. */
  private void updateImage() {
    if (config.disabled) return;
    if (project.isDisposed()) return;

    PsiFile file = PsiDocumentManager.getInstance(project).getPsiFile(editor.getDocument());
    if (file == null) {
      return;
    }

    synchronized (this) {
      // If we have already sent a rendering job off to get processed then first we need to wait for
      // it to finish.
      // see updateComplete for dirty handling. The is that there will be fast updates plus one
      // final update to
      // ensure accuracy, dropping any requests in the middle.
      if (updatePending) {
        dirty = true;
        return;
      }
      updatePending = true;
    }

    SyntaxHighlighter hl =
        SyntaxHighlighterFactory.getSyntaxHighlighter(
            file.getLanguage(), project, file.getVirtualFile());

    nextBuffer = activeBuffer == 0 ? 1 : 0;

    runner.add(
        new RenderTask(
            minimaps[nextBuffer],
            editor.getDocument().getText(),
            editor.getColorsScheme(),
            hl,
            editor.getFoldingModel().getAllFoldRegions(),
            new Runnable() {
              @Override
              public void run() {
                updateComplete();
              }
            }));
  }
コード例 #24
0
 @NotNull
 private static Map<PsiElement, FoldingDescriptor> buildRanges(
     @NotNull Editor editor, @NotNull PsiFile psiFile) {
   final FoldingBuilder foldingBuilder =
       LanguageFolding.INSTANCE.forLanguage(psiFile.getLanguage());
   final ASTNode node = psiFile.getNode();
   if (node == null) return Collections.emptyMap();
   final FoldingDescriptor[] descriptors =
       LanguageFolding.buildFoldingDescriptors(
           foldingBuilder, psiFile, editor.getDocument(), true);
   Map<PsiElement, FoldingDescriptor> ranges = new HashMap<PsiElement, FoldingDescriptor>();
   for (FoldingDescriptor descriptor : descriptors) {
     final ASTNode ast = descriptor.getElement();
     final PsiElement psi = ast.getPsi();
     if (psi != null) {
       ranges.put(psi, descriptor);
     }
   }
   return ranges;
 }
コード例 #25
0
ファイル: PsiViewerPanel.java プロジェクト: cmf/psiviewer
  public void selectElementAtCaret(@Nullable Editor editor, @Nullable String changeSource) {
    if (editor == null) /* Vince Mallet (21 Oct 2003) */ {
      debug("selectElementAtCaret: Can't select element, editor is null");
      return;
    }

    PsiFile psiFile = PsiDocumentManager.getInstance(_project).getPsiFile(editor.getDocument());

    PsiElement elementAtCaret = null;
    if (psiFile != null) {
      Language selectedLanguage = _projectComponent.getSelectedLanguage();
      FileViewProvider viewProvider = psiFile.getViewProvider();

      if (selectedLanguage != null) {
        PsiFile selectedRoot = viewProvider.getPsi(selectedLanguage);
        if (selectedRoot == null) {
          selectedLanguage = null;
        }
      }

      if (selectedLanguage == null) {
        selectedLanguage = psiFile.getLanguage();
      }

      elementAtCaret =
          viewProvider.findElementAt(editor.getCaretModel().getOffset(), selectedLanguage);

      if (elementAtCaret != null && elementAtCaret.getParent() != null) {
        if (elementAtCaret.getParent().getChildren().length == 0)
          elementAtCaret = elementAtCaret.getParent();
      }
    }

    if (elementAtCaret != null && elementAtCaret != getSelectedElement()) {
      debug("new element at caret " + elementAtCaret + ", current root=" + getRootElement());
      if (!PsiTreeUtil.isAncestor(getRootElement(), elementAtCaret, false))
        selectRootElement(psiFile, TITLE_PREFIX_CURRENT_FILE);
      setSelectedElement(
          elementAtCaret, changeSource == null ? PsiViewerPanel.CARET_MOVED : changeSource);
    }
  }
コード例 #26
0
 @Override
 public boolean containsWhiteSpaceSymbolsOnly(int startOffset, int endOffset) {
   WhiteSpaceFormattingStrategy strategy = myWhiteSpaceStrategy;
   if (strategy.check(myDocument.getCharsSequence(), startOffset, endOffset) >= endOffset) {
     return true;
   }
   PsiElement injectedElement =
       myFile != null ? InjectedLanguageUtil.findElementAtNoCommit(myFile, startOffset) : null;
   if (injectedElement != null) {
     Language injectedLanguage = injectedElement.getLanguage();
     if (!injectedLanguage.equals(myFile.getLanguage())) {
       WhiteSpaceFormattingStrategy localStrategy =
           WhiteSpaceFormattingStrategyFactory.getStrategy(injectedLanguage);
       if (localStrategy != null) {
         return localStrategy.check(myDocument.getCharsSequence(), startOffset, endOffset)
             >= endOffset;
       }
     }
   }
   return false;
 }
コード例 #27
0
 @Nullable
 protected PsiDocCommentOwner getContainer(final PsiElement context) {
   if (context == null || !context.getManager().isInProject(context)) {
     return null;
   }
   final PsiFile containingFile = context.getContainingFile();
   if (containingFile == null) {
     // for PsiDirectory
     return null;
   }
   if (!containingFile.getLanguage().isKindOf(StdLanguages.JAVA) || context instanceof PsiFile) {
     return null;
   }
   PsiElement container = context;
   while (container instanceof PsiAnonymousClass
       || !(container instanceof PsiDocCommentOwner)
       || container instanceof PsiTypeParameter) {
     container = PsiTreeUtil.getParentOfType(container, PsiDocCommentOwner.class);
     if (container == null) return null;
   }
   return (PsiDocCommentOwner) container;
 }
コード例 #28
0
        @Override
        protected Boolean compute(PsiElement parent, Object p) {
          OuterLanguageElement element =
              PsiTreeUtil.getChildOfType(parent, OuterLanguageElement.class);

          if (element == null) {
            // JspOuterLanguageElement is located under XmlText
            for (PsiElement child = parent.getFirstChild();
                child != null;
                child = child.getNextSibling()) {
              if (child instanceof XmlText) {
                element = PsiTreeUtil.getChildOfType(child, OuterLanguageElement.class);
                if (element != null) {
                  break;
                }
              }
            }
          }
          if (element == null) return false;
          PsiFile containingFile = parent.getContainingFile();
          return containingFile.getViewProvider().getBaseLanguage() != containingFile.getLanguage();
        }
コード例 #29
0
  public static boolean checkConsistency(PsiFile psiFile, Document document) {
    // todo hack
    if (psiFile.getVirtualFile() == null) return true;

    CharSequence editorText = document.getCharsSequence();
    int documentLength = document.getTextLength();
    if (psiFile.textMatches(editorText)) {
      LOG.assertTrue(psiFile.getTextLength() == documentLength);
      return true;
    }

    char[] fileText = psiFile.textToCharArray();
    @SuppressWarnings({"NonConstantStringShouldBeStringBuffer"})
    @NonNls
    String error =
        "File '"
            + psiFile.getName()
            + "' text mismatch after reparse. "
            + "File length="
            + fileText.length
            + "; Doc length="
            + documentLength
            + "\n";
    int i = 0;
    for (; i < documentLength; i++) {
      if (i >= fileText.length) {
        error += "editorText.length > psiText.length i=" + i + "\n";
        break;
      }
      if (i >= editorText.length()) {
        error += "editorText.length > psiText.length i=" + i + "\n";
        break;
      }
      if (editorText.charAt(i) != fileText[i]) {
        error += "first unequal char i=" + i + "\n";
        break;
      }
    }
    // error += "*********************************************" + "\n";
    // if (i <= 500){
    //  error += "Equal part:" + editorText.subSequence(0, i) + "\n";
    // }
    // else{
    //  error += "Equal part start:\n" + editorText.subSequence(0, 200) + "\n";
    //  error += "................................................" + "\n";
    //  error += "................................................" + "\n";
    //  error += "................................................" + "\n";
    //  error += "Equal part end:\n" + editorText.subSequence(i - 200, i) + "\n";
    // }
    error += "*********************************************" + "\n";
    error +=
        "Editor Text tail:("
            + (documentLength - i)
            + ")\n"; // + editorText.subSequence(i, Math.min(i + 300, documentLength)) + "\n";
    error += "*********************************************" + "\n";
    error += "Psi Text tail:(" + (fileText.length - i) + ")\n";
    error += "*********************************************" + "\n";

    if (document instanceof DocumentWindow) {
      error += "doc: '" + document.getText() + "'\n";
      error += "psi: '" + psiFile.getText() + "'\n";
      error += "ast: '" + psiFile.getNode().getText() + "'\n";
      error += psiFile.getLanguage() + "\n";
      PsiElement context =
          InjectedLanguageManager.getInstance(psiFile.getProject()).getInjectionHost(psiFile);
      if (context != null) {
        error += "context: " + context + "; text: '" + context.getText() + "'\n";
        error += "context file: " + context.getContainingFile() + "\n";
      }
      error +=
          "document window ranges: "
              + Arrays.asList(((DocumentWindow) document).getHostRanges())
              + "\n";
    }
    LOG.error(error);
    // document.replaceString(0, documentLength, psiFile.getText());
    return false;
  }
コード例 #30
0
  @Override
  protected JComponent createCenterPanel() {
    JPanel panel = new JPanel(new GridBagLayout());
    panel.setBorder(BorderFactory.createEmptyBorder(4, 8, 8, 0));
    GridBagConstraints gbConstraints = new GridBagConstraints();
    gbConstraints.gridy = 0;
    gbConstraints.gridx = 0;
    gbConstraints.gridwidth = 3;
    gbConstraints.gridheight = 1;
    gbConstraints.weightx = 1;

    gbConstraints.fill = GridBagConstraints.BOTH;
    gbConstraints.insets = new Insets(0, 0, 0, 0);

    myRbFile =
        new JRadioButton(
            CodeInsightBundle.message(
                "process.scope.file",
                (myFile != null ? "'" + myFile.getVirtualFile().getPresentableUrl() + "'" : "")));
    panel.add(myRbFile, gbConstraints);

    myRbSelectedText = new JRadioButton(CodeInsightBundle.message("reformat.option.selected.text"));
    if (myTextSelected != null) {
      gbConstraints.gridy++;
      gbConstraints.insets = new Insets(0, 0, 0, 0);
      panel.add(myRbSelectedText, gbConstraints);
    }

    myRbDirectory = new JRadioButton();
    myCbIncludeSubdirs =
        new JCheckBox(CodeInsightBundle.message("reformat.option.include.subdirectories"));
    if (myDirectory != null) {
      myRbDirectory.setText(
          CodeInsightBundle.message(
              "reformat.option.all.files.in.directory",
              myDirectory.getVirtualFile().getPresentableUrl()));
      gbConstraints.gridy++;
      gbConstraints.insets = new Insets(0, 0, 0, 0);
      panel.add(myRbDirectory, gbConstraints);

      if (myDirectory.getSubdirectories().length > 0) {
        gbConstraints.gridy++;
        gbConstraints.insets = new Insets(0, 20, 0, 0);
        panel.add(myCbIncludeSubdirs, gbConstraints);
      }
    }

    myCbOptimizeImports =
        new JCheckBox(CodeInsightBundle.message("reformat.option.optimize.imports"));
    if (myTextSelected != null && LanguageImportStatements.INSTANCE.hasAnyExtensions()) {
      gbConstraints.gridy++;
      gbConstraints.insets = new Insets(0, 0, 0, 0);
      panel.add(myCbOptimizeImports, gbConstraints);
    }

    myCbArrangeEntries =
        new JCheckBox(CodeInsightBundle.message("reformat.option.rearrange.entries"));
    if (myFile != null && Rearranger.EXTENSION.forLanguage(myFile.getLanguage()) != null) {
      gbConstraints.gridy++;
      gbConstraints.insets = new Insets(0, 0, 0, 0);
      panel.add(myCbArrangeEntries, gbConstraints);
    }

    myCbOnlyVcsChangedRegions =
        new JCheckBox(CodeInsightBundle.message("reformat.option.vcs.changed.region"));
    gbConstraints.gridy++;
    panel.add(myCbOnlyVcsChangedRegions, gbConstraints);

    ButtonGroup buttonGroup = new ButtonGroup();
    buttonGroup.add(myRbFile);
    buttonGroup.add(myRbSelectedText);
    buttonGroup.add(myRbDirectory);

    myRbFile.setEnabled(myFile != null);
    myRbSelectedText.setEnabled(myTextSelected == Boolean.TRUE);

    return panel;
  }