@Nullable(
     "null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
 public static Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessFromContent(
     @NotNull VirtualFile virtualFile, @NotNull byte[] content, int length) {
   Charset defaultCharset =
       ObjectUtils.notNull(
           EncodingManager.getInstance().getEncoding(virtualFile, true),
           CharsetToolkit.getDefaultSystemCharset());
   CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, defaultCharset) : null;
   String detectedFromBytes = null;
   try {
     if (GUESS_UTF) {
       toolkit.setEnforce8Bit(true);
       Charset charset = toolkit.guessFromBOM();
       if (charset != null) {
         detectedFromBytes = AUTO_DETECTED_FROM_BOM;
         byte[] bom =
             ObjectUtils.notNull(CharsetToolkit.getMandatoryBom(charset), CharsetToolkit.UTF8_BOM);
         return Trinity.create(charset, null, bom);
       }
       CharsetToolkit.GuessedEncoding guessed = toolkit.guessFromContent(length);
       if (guessed == CharsetToolkit.GuessedEncoding.VALID_UTF8) {
         detectedFromBytes = "auto-detected from bytes";
         return Trinity.create(
             CharsetToolkit.UTF8_CHARSET, guessed, null); // UTF detected, ignore all directives
       }
       if (guessed == CharsetToolkit.GuessedEncoding.SEVEN_BIT) {
         return Trinity.create(null, guessed, null);
       }
     }
     return null;
   } finally {
     setCharsetWasDetectedFromBytes(virtualFile, detectedFromBytes);
   }
 }
 private static void fillJsTestFileStructure(
     @NotNull JstdTestFileStructure jsTestFileStructure, @NotNull JSStatement statement) {
   if (statement instanceof JSExpressionStatement) {
     JSExpressionStatement jsExpressionStatement = (JSExpressionStatement) statement;
     JSExpression expressionOfStatement = jsExpressionStatement.getExpression();
     if (expressionOfStatement instanceof JSCallExpression) {
       // TestCase("testCaseName", { test1: function() {} });
       JSCallExpression callExpression = (JSCallExpression) expressionOfStatement;
       createTestCaseStructure(jsTestFileStructure, callExpression);
     } else if (expressionOfStatement instanceof JSAssignmentExpression) {
       // testCase = TestCase("testCaseName");
       JSAssignmentExpression jsAssignmentExpression =
           (JSAssignmentExpression) expressionOfStatement;
       JSCallExpression rOperandCallExpression =
           ObjectUtils.tryCast(jsAssignmentExpression.getROperand(), JSCallExpression.class);
       if (rOperandCallExpression != null) {
         JstdTestCaseStructure testCaseStructure =
             createTestCaseStructure(jsTestFileStructure, rOperandCallExpression);
         if (testCaseStructure != null) {
           JSDefinitionExpression jsDefinitionExpression =
               ObjectUtils.tryCast(
                   jsAssignmentExpression.getLOperand(), JSDefinitionExpression.class);
           if (jsDefinitionExpression != null) {
             JSReferenceExpression jsReferenceExpression =
                 ObjectUtils.tryCast(
                     jsDefinitionExpression.getExpression(), JSReferenceExpression.class);
             if (jsReferenceExpression != null) {
               String refName = jsReferenceExpression.getReferencedName();
               if (refName != null) {
                 addPrototypeTests(testCaseStructure, refName, jsExpressionStatement);
               }
             }
           }
         }
       }
     }
   }
   if (statement instanceof JSVarStatement) {
     // var testCase = TestCase("testCaseName");
     JSVarStatement jsVarStatement = (JSVarStatement) statement;
     JSVariable[] jsVariables =
         ObjectUtils.notNull(jsVarStatement.getVariables(), JSVariable.EMPTY_ARRAY);
     for (JSVariable jsVariable : jsVariables) {
       JSCallExpression jsCallExpression =
           ObjectUtils.tryCast(jsVariable.getInitializer(), JSCallExpression.class);
       if (jsCallExpression != null) {
         JstdTestCaseStructure testCaseStructure =
             createTestCaseStructure(jsTestFileStructure, jsCallExpression);
         if (testCaseStructure != null) {
           String refName = jsVariable.getQualifiedName();
           if (refName != null) {
             addPrototypeTests(testCaseStructure, refName, jsVarStatement);
           }
         }
       }
     }
   }
 }
 @Override
 public PsiElement handleElementRename(final String newElementName)
     throws IncorrectOperationException {
   CheckUtil.checkWritable(this);
   final PsiElement firstChildNode = ObjectUtils.assertNotNull(getFirstChild());
   final PsiElement firstInIdentifier =
       getClass().isInstance(firstChildNode)
           ? ObjectUtils.assertNotNull(firstChildNode.getNextSibling()).getNextSibling()
           : firstChildNode;
   getNode().removeRange(firstInIdentifier.getNode(), null);
   final PsiElement referenceName =
       ObjectUtils.assertNotNull(parseReference(newElementName).getReferenceNameElement());
   getNode().addChild(referenceName.getNode());
   return this;
 }
  @Override
  public void customizePainter(
      @NotNull JComponent component,
      @NotNull Collection<VcsRef> references,
      @Nullable VcsLogRefManager manager,
      @NotNull Color background,
      @NotNull Color foreground) {
    FontMetrics metrics = component.getFontMetrics(getReferenceFont());
    myHeight =
        metrics.getHeight()
            + RectanglePainter.TOP_TEXT_PADDING
            + RectanglePainter.BOTTOM_TEXT_PADDING;
    myWidth = 2 * PaintParameters.LABEL_PADDING;

    myLabels = ContainerUtil.newArrayList();
    if (manager == null) return;

    List<VcsRef> sorted = ContainerUtil.sorted(references, manager.getLabelsOrderComparator());

    for (Map.Entry<VcsRefType, Collection<VcsRef>> entry :
        ContainerUtil.groupBy(sorted, VcsRef::getType).entrySet()) {
      VcsRef ref = ObjectUtils.assertNotNull(ContainerUtil.getFirstItem(entry.getValue()));
      String text = ref.getName() + (entry.getValue().size() > 1 ? " +" : "");
      myLabels.add(Pair.create(text, entry.getKey().getBackgroundColor()));

      myWidth +=
          myLabelPainter.calculateSize(text, metrics).getWidth() + PaintParameters.LABEL_PADDING;
    }
  }
  @Nullable
  private ClassLoader createGreclipseLoader(@Nullable String jar) {
    if (StringUtil.isEmpty(jar)) return null;

    if (jar.equals(myGreclipseJar)) {
      return myGreclipseLoader;
    }

    try {
      URL[] urls = {
        new File(jar).toURI().toURL(),
        new File(ObjectUtils.assertNotNull(PathManager.getJarPathForClass(GreclipseMain.class)))
            .toURI()
            .toURL()
      };
      ClassLoader loader = new URLClassLoader(urls, null);
      Class.forName("org.eclipse.jdt.internal.compiler.batch.Main", false, loader);
      myGreclipseJar = jar;
      myGreclipseLoader = loader;
      return loader;
    } catch (Exception e) {
      LOG.error(e);
      return null;
    }
  }
 @NotNull
 private static FilePath rebasePath(
     @NotNull FilePath oldBase, @NotNull FilePath newBase, @NotNull FilePath path) {
   String relativePath =
       ObjectUtils.assertNotNull(FileUtil.getRelativePath(oldBase.getPath(), path.getPath(), '/'));
   return VcsUtil.getFilePath(newBase.getPath() + "/" + relativePath, path.isDirectory());
 }
Example #7
0
 @NotNull
 public static GitRemoteBranch findOrCreateRemoteBranch(
     @NotNull GitRepository repository, @NotNull GitRemote remote, @NotNull String branchName) {
   GitRemoteBranch remoteBranch = findRemoteBranch(repository, remote, branchName);
   return ObjectUtils.notNull(
       remoteBranch, new GitStandardRemoteBranch(remote, branchName, GitBranch.DUMMY_HASH));
 }
  public static void fillCompletionVariants(
      CompletionParameters parameters, CompletionResultSet result) {
    if (parameters.getCompletionType() != CompletionType.BASIC
        && parameters.getCompletionType() != CompletionType.SMART) {
      return;
    }

    PsiElement position = parameters.getPosition();
    if (psiElement(PsiIdentifier.class)
        .withParents(PsiJavaCodeReferenceElement.class, PsiTypeElement.class, PsiClass.class)
        .andNot(JavaCompletionData.AFTER_DOT)
        .andNot(psiElement().afterLeaf(psiElement().inside(PsiModifierList.class)))
        .accepts(position)) {
      suggestGeneratedMethods(result, position);
    } else if (psiElement(PsiIdentifier.class)
        .withParents(
            PsiJavaCodeReferenceElement.class,
            PsiAnnotation.class,
            PsiModifierList.class,
            PsiClass.class)
        .accepts(position)) {
      PsiAnnotation annotation =
          ObjectUtils.assertNotNull(PsiTreeUtil.getParentOfType(position, PsiAnnotation.class));
      int annoStart = annotation.getTextRange().getStartOffset();
      suggestGeneratedMethods(
          result.withPrefixMatcher(
              annotation.getText().substring(0, parameters.getOffset() - annoStart)),
          position);
    }
  }
 @Nullable
 private static JstdTestCaseStructure createTestCaseStructure(
     @NotNull JstdTestFileStructure jsTestFileStructure,
     @NotNull JSCallExpression testCaseCallExpression) {
   JSReferenceExpression referenceExpression =
       ObjectUtils.tryCast(
           testCaseCallExpression.getMethodExpression(), JSReferenceExpression.class);
   if (referenceExpression != null) {
     String referenceName = referenceExpression.getReferencedName();
     if (TEST_CASE_NAME.equals(referenceName) || ASYNC_TEST_CASE_NAME.equals(referenceName)) {
       JSExpression[] arguments = JsPsiUtils.getArguments(testCaseCallExpression);
       if (arguments.length >= 1) {
         String testCaseName = JsPsiUtils.extractStringValue(arguments[0]);
         if (testCaseName != null) {
           JSObjectLiteralExpression testsObjectLiteral = null;
           if (arguments.length >= 2) {
             testsObjectLiteral = JsPsiUtils.extractObjectLiteralExpression(arguments[1]);
           }
           JstdTestCaseStructure testCaseStructure =
               new JstdTestCaseStructure(
                   jsTestFileStructure, testCaseName, testCaseCallExpression, testsObjectLiteral);
           jsTestFileStructure.addTestCaseStructure(testCaseStructure);
           if (testsObjectLiteral != null) {
             fillTestCaseStructureByObjectLiteral(testCaseStructure, testsObjectLiteral);
           }
           return testCaseStructure;
         }
       }
     }
   }
   return null;
 }
Example #10
0
  @NotNull
  @Override
  public List<LightRef> getHierarchyRestrictedToLibraryScope(
      @NotNull LightRef baseRef,
      @NotNull PsiElement basePsi,
      @NotNull ByteArrayEnumerator names,
      @NotNull GlobalSearchScope libraryScope) {
    final PsiClass baseClass =
        ObjectUtils.notNull(
            basePsi instanceof PsiClass
                ? (PsiClass) basePsi
                : ReadAction.compute(() -> (PsiMember) basePsi).getContainingClass());

    final List<LightRef> overridden = new ArrayList<>();
    Processor<PsiClass> processor =
        c -> {
          if (c.hasModifierProperty(PsiModifier.PRIVATE)) return true;
          String qName = ReadAction.compute(() -> c.getQualifiedName());
          if (qName == null) return true;
          overridden.add(baseRef.override(id(qName, names)));
          return true;
        };

    ClassInheritorsSearch.search(
            baseClass,
            LibraryScopeCache.getInstance(baseClass.getProject()).getLibrariesOnlyScope(),
            true)
        .forEach(processor);
    return overridden;
  }
 @Override
 @NotNull
 public GrModifierList getAnnotationList() {
   GrImportStatementStub stub = getStub();
   if (stub != null) {
     return ObjectUtils.assertNotNull(getStubOrPsiChild(GroovyElementTypes.MODIFIERS));
   }
   return findNotNullChildByClass(GrModifierList.class);
 }
  /** Sets current LAF. The method doesn't update component hierarchy. */
  @Override
  public void setCurrentLookAndFeel(UIManager.LookAndFeelInfo lookAndFeelInfo) {
    if (findLaf(lookAndFeelInfo.getClassName()) == null) {
      LOG.error("unknown LookAndFeel : " + lookAndFeelInfo);
      return;
    }
    // Set L&F
    if (IdeaLookAndFeelInfo.CLASS_NAME.equals(
        lookAndFeelInfo.getClassName())) { // that is IDEA default LAF
      IdeaLaf laf = new IdeaLaf();
      MetalLookAndFeel.setCurrentTheme(new IdeaBlueMetalTheme());
      try {
        UIManager.setLookAndFeel(laf);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    } else if (DarculaLookAndFeelInfo.CLASS_NAME.equals(lookAndFeelInfo.getClassName())) {
      DarculaLaf laf = new DarculaLaf();
      try {
        UIManager.setLookAndFeel(laf);
        JBColor.setDark(true);
        IconLoader.setUseDarkIcons(true);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    } else { // non default LAF
      try {
        LookAndFeel laf =
            ((LookAndFeel) Class.forName(lookAndFeelInfo.getClassName()).newInstance());
        if (laf instanceof MetalLookAndFeel) {
          MetalLookAndFeel.setCurrentTheme(new DefaultMetalTheme());
        }
        UIManager.setLookAndFeel(laf);
      } catch (Exception e) {
        Messages.showMessageDialog(
            IdeBundle.message(
                "error.cannot.set.look.and.feel", lookAndFeelInfo.getName(), e.getMessage()),
            CommonBundle.getErrorTitle(),
            Messages.getErrorIcon());
        return;
      }
    }
    myCurrentLaf =
        ObjectUtils.chooseNotNull(findLaf(lookAndFeelInfo.getClassName()), lookAndFeelInfo);

    checkLookAndFeel(lookAndFeelInfo, false);
  }
 public static void requeueIfPossible(InferenceCapable element) {
   final Boolean userData =
       ObjectUtils.notNull(
           element.getContainingFile().getUserData(PsiFileEx.BATCH_REFERENCE_PROCESSING), false);
   if (!userData && !PsiTreeUtil.hasErrorElements(element)) {
     final Project project = element.getProject();
     if (project != null) LuaPsiManager.getInstance(project).queueInferences(element);
   }
 }
  @NotNull
  public ListMergeStatus check(
      @NotNull CommittedChangeList list, @NotNull MergeInfoCached state, boolean isCached) {
    SvnMergeInfoCache.MergeCheckResult mergeCheckResult = state.getMap().get(list.getNumber());
    ListMergeStatus result =
        state.copiedAfter(list) ? ListMergeStatus.COMMON : ListMergeStatus.from(mergeCheckResult);

    return ObjectUtils.notNull(
        result, isCached ? ListMergeStatus.REFRESHING : ListMergeStatus.ALIEN);
  }
 @Override
 public void applyTo(@NotNull JstdRunSettings.Builder runSettingsBuilder) {
   BrowsersConfiguration.BrowserFamily selectedBrowser =
       ObjectUtils.tryCast(
           myPreferredDebugBrowserComboBox.getSelectedItem(),
           BrowsersConfiguration.BrowserFamily.class);
   if (selectedBrowser != null) {
     runSettingsBuilder.setPreferredDebugBrowser(selectedBrowser);
   }
 }
    public void setSelected(AnActionEvent e, boolean state) {
      T change = ObjectUtils.tryCast(e.getData(VcsDataKeys.CURRENT_CHANGE), myClass);
      if (change == null) return;

      if (state) {
        myViewer.includeChange(change);
      } else {
        myViewer.excludeChange(change);
      }
    }
 private static void suggestGeneratedMethods(CompletionResultSet result, PsiElement position) {
   PsiClass parent =
       CompletionUtil.getOriginalElement(
           ObjectUtils.assertNotNull(PsiTreeUtil.getParentOfType(position, PsiClass.class)));
   if (parent != null) {
     Set<MethodSignature> addedSignatures = ContainerUtil.newHashSet();
     addGetterSetterElements(result, parent, addedSignatures);
     addSuperSignatureElements(parent, true, result, addedSignatures);
     addSuperSignatureElements(parent, false, result, addedSignatures);
   }
 }
 @Nullable
 private static BasePathInfo newBasePathInfo(@NotNull CompletionParameters parameters) {
   YAMLFile yamlFile = ObjectUtils.tryCast(parameters.getOriginalFile(), YAMLFile.class);
   if (yamlFile != null) {
     List<YAMLDocument> yamlDocuments = yamlFile.getDocuments();
     if (!yamlDocuments.isEmpty()) {
       return new BasePathInfo(yamlDocuments.get(0));
     }
   }
   return null;
 }
 @NotNull
 private String findPresetHttpUrl() {
   return ObjectUtils.chooseNotNull(
       ContainerUtil.find(
           myUrlsFromCommand,
           url -> {
             String scheme = UriUtil.splitScheme(url).getFirst();
             return scheme.startsWith("http");
           }),
       ContainerUtil.getFirstItem(myUrlsFromCommand));
 }
 /**
  * Copies content of {@code fromDir} to {@code toDir}. It's equivalent to "cp -r fromDir/* toDir"
  * unix command.
  *
  * @param fromDir source directory
  * @param toDir destination directory
  * @throws IOException in case of any IO troubles
  */
 public static void copyDirContent(@NotNull File fromDir, @NotNull File toDir) throws IOException {
   File[] children = ObjectUtils.notNull(fromDir.listFiles(), ArrayUtil.EMPTY_FILE_ARRAY);
   for (File child : children) {
     File target = new File(toDir, child.getName());
     if (child.isFile()) {
       copy(child, target);
     } else {
       copyDir(child, target, true);
     }
   }
 }
 public GitLogProvider(
     @NotNull Project project,
     @NotNull GitRepositoryManager repositoryManager,
     @NotNull VcsLogObjectsFactory factory,
     @NotNull GitUserRegistry userRegistry) {
   myProject = project;
   myRepositoryManager = repositoryManager;
   myUserRegistry = userRegistry;
   myRefSorter = new GitRefManager(myRepositoryManager);
   myVcsObjectsFactory = factory;
   myVcs = ObjectUtils.assertNotNull(GitVcs.getInstance(project));
 }
 private static void addPrototypeTest(
     @NotNull JstdTestCaseStructure testCaseStructure,
     @Nullable JSExpression rightAssignmentOperand,
     @NotNull JSDefinitionExpression wholeLeftDefExpr) {
   JSReferenceExpression wholeLeftRefExpr =
       ObjectUtils.tryCast(wholeLeftDefExpr.getExpression(), JSReferenceExpression.class);
   LeafPsiElement testMethodLeafPsiElement = null;
   if (wholeLeftRefExpr != null) {
     testMethodLeafPsiElement =
         ObjectUtils.tryCast(wholeLeftRefExpr.getReferenceNameElement(), LeafPsiElement.class);
   }
   if (testMethodLeafPsiElement != null
       && testMethodLeafPsiElement.getElementType() == JSTokenTypes.IDENTIFIER) {
     JSFunctionExpression jsFunctionExpression =
         JsPsiUtils.extractFunctionExpression(rightAssignmentOperand);
     JstdTestStructure jstdTestStructure =
         JstdTestStructure.newPrototypeBasedTestStructure(
             wholeLeftDefExpr, testMethodLeafPsiElement, jsFunctionExpression);
     if (jstdTestStructure != null) {
       testCaseStructure.addTestStructure(jstdTestStructure);
     }
   }
 }
  private static void assertResolvesTo(
      @Nullable PsiReference reference, @NotNull String file, @NotNull String function, int arity) {
    assertNotNull(reference);

    ErlangFunction resolvedFunction =
        ObjectUtils.tryCast(reference.resolve(), ErlangFunction.class);
    assertNotNull(resolvedFunction);

    String actualFile = resolvedFunction.getContainingFile().getName();
    assertEquals(file, actualFile);

    assertEquals(function, resolvedFunction.getName());
    assertEquals(arity, resolvedFunction.getArity());
  }
  public static void openTipInBrowser(@Nullable TipAndTrickBean tip, JEditorPane browser) {
    if (tip == null) return;
    try {
      PluginDescriptor pluginDescriptor = tip.getPluginDescriptor();
      ClassLoader tipLoader =
          pluginDescriptor == null
              ? TipUIUtil.class.getClassLoader()
              : ObjectUtils.notNull(
                  pluginDescriptor.getPluginClassLoader(), TipUIUtil.class.getClassLoader());

      URL url = ResourceUtil.getResource(tipLoader, "/tips/", tip.fileName);

      if (url == null) {
        setCantReadText(browser, tip);
        return;
      }

      StringBuffer text = new StringBuffer(ResourceUtil.loadText(url));
      updateShortcuts(text);
      updateImages(text, tipLoader);
      String replaced =
          text.toString()
              .replace("&productName;", ApplicationNamesInfo.getInstance().getFullProductName());
      String major = ApplicationInfo.getInstance().getMajorVersion();
      replaced = replaced.replace("&majorVersion;", major);
      String minor = ApplicationInfo.getInstance().getMinorVersion();
      replaced = replaced.replace("&minorVersion;", minor);
      replaced =
          replaced.replace("&majorMinorVersion;", major + ("0".equals(minor) ? "" : ("." + minor)));
      replaced = replaced.replace("&settingsPath;", CommonBundle.settingsActionPath());
      replaced =
          replaced.replaceFirst(
              "<link rel=\"stylesheet\".*tips\\.css\">", ""); // don't reload the styles
      if (browser.getUI() == null) {
        browser.updateUI();
        boolean succeed = browser.getUI() != null;
        String message =
            "reinit JEditorPane.ui: "
                + (succeed ? "OK" : "FAIL")
                + ", laf="
                + LafManager.getInstance().getCurrentLookAndFeel();
        if (succeed) LOG.warn(message);
        else LOG.error(message);
      }
      adjustFontSize(((HTMLEditorKit) browser.getEditorKit()).getStyleSheet());
      browser.read(new StringReader(replaced), url);
    } catch (IOException e) {
      setCantReadText(browser, tip);
    }
  }
 private static void addBasePathCompletionsIfNeeded(
     @NotNull CompletionParameters parameters,
     @NotNull CompletionResultSet result,
     @NotNull BipartiteString caretBipartiteElementText) {
   YAMLKeyValue keyValue =
       ObjectUtils.tryCast(parameters.getPosition().getParent(), YAMLKeyValue.class);
   if (keyValue != null) {
     if (keyValue.getParent() instanceof YAMLDocument && BasePathInfo.isBasePathKey(keyValue)) {
       BasePathInfo basePathInfo = newBasePathInfo(parameters);
       if (basePathInfo != null) {
         VirtualFile configDir = basePathInfo.getConfigDir();
         if (configDir != null) {
           addPathCompletions(result, caretBipartiteElementText, configDir, true);
         }
       }
     }
   }
 }
Example #26
0
  @NotNull
  private static Pair.NonNull<Charset, byte[]> getCharsetAndBOM(
      @NotNull byte[] content, @NotNull Charset charset) {
    if (charset.name().contains(CharsetToolkit.UTF8) && CharsetToolkit.hasUTF8Bom(content)) {
      return Pair.createNonNull(charset, CharsetToolkit.UTF8_BOM);
    }
    try {
      Charset fromBOM = CharsetToolkit.guessFromBOM(content);
      if (fromBOM != null) {
        return Pair.createNonNull(
            fromBOM,
            ObjectUtils.notNull(
                CharsetToolkit.getMandatoryBom(fromBOM), ArrayUtil.EMPTY_BYTE_ARRAY));
      }
    } catch (UnsupportedCharsetException ignore) {
    }

    return Pair.createNonNull(charset, ArrayUtil.EMPTY_BYTE_ARRAY);
  }
    @NotNull
    private static Pair<EditorTextField, EditorEx> createEditor(
        Project project, @Nullable FileType fileType, boolean inheritFontFromLaF) {
      EditorTextField field =
          new EditorTextField(new MyDocument(), project, fileType, false, false);
      field.setSupplementary(true);
      field.setFontInheritedFromLAF(inheritFontFromLaF);
      field.addNotify(); // creates editor

      EditorEx editor = (EditorEx) ObjectUtils.assertNotNull(field.getEditor());
      editor.setRendererMode(true);

      editor.setColorsScheme(editor.createBoundColorSchemeDelegate(null));
      editor.getSettings().setCaretRowShown(false);

      editor.getScrollPane().setBorder(null);

      return Pair.create(field, editor);
    }
  private void paintOnComponentUnderViewport(Component component, Graphics g) {
    JBViewport viewport = ObjectUtils.tryCast(myOwner, JBViewport.class);
    if (viewport == null || viewport.getView() != component || viewport.isPaintingNow()) return;

    // We're painting a component which has a viewport as it's ancestor.
    // As the viewport paints status text, we'll erase it, so we need to schedule a repaint for the
    // viewport with status text's bounds.
    // But it causes flicker, so we paint status text over the component first and then schedule the
    // viewport repaint.

    Rectangle textBoundsInViewport = getTextComponentBound();

    int xInOwner = textBoundsInViewport.x - component.getX();
    int yInOwner = textBoundsInViewport.y - component.getY();
    Rectangle textBoundsInOwner =
        new Rectangle(xInOwner, yInOwner, textBoundsInViewport.width, textBoundsInViewport.height);
    doPaintStatusText(g, textBoundsInOwner);

    viewport.repaint(textBoundsInViewport);
  }
 private static void addTopLevelKeysCompletionIfNeeded(
     @NotNull CompletionParameters parameters,
     @NotNull CompletionResultSet result,
     @NotNull BipartiteString caretBipartiteElementText) {
   PsiElement element = parameters.getPosition();
   YAMLDocument yamlDocument = ObjectUtils.tryCast(element.getParent(), YAMLDocument.class);
   if (yamlDocument == null) {
     yamlDocument =
         JstdConfigFileUtils.getVerifiedHierarchyHead(
             element.getParent(), new Class[] {YAMLKeyValue.class}, YAMLDocument.class);
   }
   if (yamlDocument != null) {
     String prefix = caretBipartiteElementText.getPrefix();
     result = result.withPrefixMatcher(prefix);
     for (String key : JstdConfigFileUtils.VALID_TOP_LEVEL_KEYS) {
       if (key.startsWith(prefix)) {
         result.addElement(LookupItem.fromString(key + ":"));
       }
     }
   }
 }
  @NotNull
  protected ChangesSelection getChangesSelection() {
    final Change leadSelection = ObjectUtils.tryCast(myViewer.getLeadSelection(), Change.class);
    List<Change> changes = getSelectedChanges();

    if (changes.size() < 2) {
      List<Change> allChanges = getAllChanges();
      if (allChanges.size() > 1 || changes.isEmpty()) {
        changes = allChanges;
      }
    }

    if (leadSelection != null) {
      int indexInSelection = changes.indexOf(leadSelection);
      if (indexInSelection == -1) {
        return new ChangesSelection(Collections.singletonList(leadSelection), 0);
      } else {
        return new ChangesSelection(changes, indexInSelection);
      }
    } else {
      return new ChangesSelection(changes, 0);
    }
  }