Java Code Examples for com.intellij.lang.Language

The following examples show how to use com.intellij.lang.Language. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: consulo   Source File: InjectedLanguageBlockBuilder.java    License: Apache License 2.0 6 votes vote down vote up
public void addInjectedLanguageBlockWrapper(final List<Block> result, final ASTNode injectedNode,
                                            final Indent indent, int offset, @Nullable TextRange range) {

  //
  // Do not create a block for an empty range
  //
  if (range != null) {
    if (range.getLength() == 0) return;
    if(StringUtil.isEmptyOrSpaces(range.substring(injectedNode.getText()))) {
      return;
    }
  }
  
  final PsiElement childPsi = injectedNode.getPsi();
  final Language childLanguage = childPsi.getLanguage();
  final FormattingModelBuilder builder = LanguageFormatting.INSTANCE.forContext(childLanguage, childPsi);
  LOG.assertTrue(builder != null);
  final FormattingModel childModel = builder.createModel(childPsi, getSettings());
  Block original = childModel.getRootBlock();

  if ((original.isLeaf() && injectedNode.getText().trim().length() > 0) || original.getSubBlocks().size() != 0) {
    result.add(createInjectedBlock(injectedNode, original, indent, offset, range, childLanguage));
  }
}
 
Example 2
Source Project: consulo   Source File: DiffUtil.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
private static EditorHighlighter createEditorHighlighter(@Nullable Project project, @Nonnull DocumentContent content) {
  FileType type = content.getContentType();
  VirtualFile file = content.getHighlightFile();
  Language language = content.getUserData(DiffUserDataKeys.LANGUAGE);

  EditorHighlighterFactory highlighterFactory = EditorHighlighterFactory.getInstance();
  if (language != null) {
    SyntaxHighlighter syntaxHighlighter = SyntaxHighlighterFactory.getSyntaxHighlighter(language, project, file);
    return highlighterFactory.createEditorHighlighter(syntaxHighlighter, EditorColorsManager.getInstance().getGlobalScheme());
  }
  if (file != null) {
    if ((type == null || type == PlainTextFileType.INSTANCE) || file.getFileType() == type || file instanceof LightVirtualFile) {
      return highlighterFactory.createEditorHighlighter(project, file);
    }
  }
  if (type != null) {
    return highlighterFactory.createEditorHighlighter(project, type);
  }
  return null;
}
 
Example 3
Source Project: consulo   Source File: StubUpdatingIndex.java    License: Apache License 2.0 6 votes vote down vote up
public static boolean canHaveStub(@Nonnull ProjectLocator projectLocator, @Nullable Project project, @Nonnull VirtualFile file) {
  FileType fileType = SubstitutedFileType.substituteFileType(file, file.getFileType(), project == null ? projectLocator.guessProjectForFile(file) : project);
  if (fileType instanceof LanguageFileType) {
    final Language l = ((LanguageFileType)fileType).getLanguage();
    final ParserDefinition parserDefinition = LanguageParserDefinitions.INSTANCE.forLanguage(l);
    if (parserDefinition == null) {
      return false;
    }

    final IFileElementType elementType = parserDefinition.getFileNodeType();
    if (elementType instanceof IStubFileElementType) {
      if (((IStubFileElementType)elementType).shouldBuildStubFor(file)) {
        return true;
      }
      FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();
      if (file instanceof NewVirtualFile &&
          fileBasedIndex instanceof FileBasedIndexImpl &&
          ((FileBasedIndexImpl)fileBasedIndex).getIndex(INDEX_ID).isIndexedStateForFile(((NewVirtualFile)file).getId(), file)) {
        return true;
      }
    }
  }
  final BinaryFileStubBuilder builder = BinaryFileStubBuilders.INSTANCE.forFileType(fileType);
  return builder != null && builder.acceptsFile(file);
}
 
Example 4
Source Project: consulo   Source File: TemplateLanguageErrorFilter.java    License: Apache License 2.0 6 votes vote down vote up
protected TemplateLanguageErrorFilter(
  final @Nonnull TokenSet templateExpressionStartTokens,
  final @Nonnull Class templateFileViewProviderClass,
  final @Nonnull String... knownSubLanguageNames)
{
  myTemplateExpressionStartTokens = TokenSet.create(templateExpressionStartTokens.getTypes());
  myTemplateFileViewProviderClass = templateFileViewProviderClass;

  List<String> knownSubLanguageList = new ArrayList<String>(Arrays.asList(knownSubLanguageNames));
  knownSubLanguageList.add("JavaScript");
  knownSubLanguageList.add("CSS");
  knownLanguageSet = new HashSet<Language>();
  for (String name : knownSubLanguageList) {
    final Language language = Language.findLanguageByID(name);
    if (language != null) {
      knownLanguageSet.add(language);
    }
  }
}
 
Example 5
Source Project: consulo   Source File: BlockSupportImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Nullable
protected static ASTNode tryReparseNode(@Nonnull IReparseableElementTypeBase reparseable, @Nonnull ASTNode node, @Nonnull CharSequence newTextStr,
                                        @Nonnull PsiManager manager, @Nonnull Language baseLanguage, @Nonnull CharTable charTable) {
  if (!reparseable.isParsable(node.getTreeParent(), newTextStr, baseLanguage, manager.getProject())) {
    return null;
  }
  ASTNode chameleon;
  if (reparseable instanceof ICustomParsingType) {
    chameleon = ((ICustomParsingType)reparseable).parse(newTextStr, SharedImplUtil.findCharTableByTree(node));
  }
  else if (reparseable instanceof ILazyParseableElementType) {
    chameleon = ((ILazyParseableElementType)reparseable).createNode(newTextStr);
  }
  else {
    throw new AssertionError(reparseable.getClass() + " must either implement ICustomParsingType or extend ILazyParseableElementType");
  }
  if (chameleon == null) {
    return null;
  }
  DummyHolder holder = DummyHolderFactory.createHolder(manager, null, node.getPsi(), charTable);
  holder.getTreeElement().rawAddChildren((TreeElement)chameleon);
  if (!reparseable.isValidReparse(node, chameleon)) {
    return null;
  }
  return chameleon;
}
 
Example 6
Source Project: consulo   Source File: Sand2PackageProvider.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
@Override
public PsiPackage createPackage(@Nonnull PsiManager psiManager,
                                @Nonnull PsiPackageManager packageManager,
                                @Nonnull Class<? extends ModuleExtension> extensionClass,
                                @Nonnull String packageName) {
  return new PsiPackageBase(psiManager, packageManager, extensionClass, packageName) {
    @Override
    protected ArrayFactory<? extends PsiPackage> getPackageArrayFactory() {
      return PsiPackage.ARRAY_FACTORY;
    }

    @RequiredReadAction
    @Nonnull
    @Override
    public Language getLanguage() {
      return SandLanguage.INSTANCE;
    }
  };
}
 
Example 7
Source Project: bamboo-soy   Source File: SoyLayeredHighlighter.java    License: Apache License 2.0 6 votes vote down vote up
public SoyLayeredHighlighter(
    @Nullable Project project,
    @Nullable VirtualFile virtualFile,
    @NotNull EditorColorsScheme colors) {
  // Creating main highlighter.
  super(new SoySyntaxHighlighter(), colors);

  // Highlighter for the outer language.
  FileType type = null;
  if (project == null || virtualFile == null) {
    type = StdFileTypes.PLAIN_TEXT;
  } else {
    Language language = TemplateDataLanguageMappings.getInstance(project).getMapping(virtualFile);
    if (language != null) type = language.getAssociatedFileType();
    if (type == null) type = SoyLanguage.getDefaultTemplateLang();
  }

  SyntaxHighlighter outerHighlighter =
      SyntaxHighlighterFactory.getSyntaxHighlighter(type, project, virtualFile);

  registerLayer(OTHER, new LayerDescriptor(outerHighlighter, ""));
}
 
Example 8
Source Project: consulo   Source File: FormattingDocumentModelImpl.java    License: Apache License 2.0 6 votes vote down vote up
@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;
}
 
Example 9
Source Project: tutorials   Source File: SearchAction.java    License: MIT License 6 votes vote down vote up
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
    Optional<PsiFile> psiFile = Optional.ofNullable(e.getData(LangDataKeys.PSI_FILE));
    String languageTag = psiFile
            .map(PsiFile::getLanguage)
            .map(Language::getDisplayName)
            .map(String::toLowerCase)
            .map(lang -> "[" + lang + "]")
            .orElse("");

    Editor editor = e.getRequiredData(CommonDataKeys.EDITOR);
    CaretModel caretModel = editor.getCaretModel();
    String selectedText = caretModel.getCurrentCaret().getSelectedText();

    BrowserUtil.browse("https://stackoverflow.com/search?q=" + languageTag + selectedText);
}
 
Example 10
Source Project: consulo   Source File: LanguageConsoleBuilder.java    License: Apache License 2.0 6 votes vote down vote up
@Nonnull
public LanguageConsoleView build(@Nonnull Project project, @Nonnull Language language) {
  final MyHelper helper = new MyHelper(project, language.getDisplayName() + " Console", language, psiFileFactory);
  GutteredLanguageConsole consoleView = new GutteredLanguageConsole(helper, gutterContentProvider);
  if (oneLineInput) {
    consoleView.getConsoleEditor().setOneLineMode(true);
  }
  if (executeActionHandler != null) {
    assert historyType != null;
    doInitAction(consoleView, executeActionHandler, historyType);
  }

  if (processInputStateKey != null) {
    assert executeActionHandler != null;
    if (PropertiesComponent.getInstance().getBoolean(processInputStateKey)) {
      executeActionHandler.myUseProcessStdIn = true;
      DaemonCodeAnalyzer daemonCodeAnalyzer = DaemonCodeAnalyzer.getInstance(consoleView.getProject());
      daemonCodeAnalyzer.setHighlightingEnabled(consoleView.getFile(), false);
    }
    consoleView.addCustomConsoleAction(new UseConsoleInputAction(processInputStateKey));
  }
  return consoleView;
}
 
Example 11
private boolean isComment(int offset) {
  final HighlighterIterator it = myEditor.getHighlighter().createIterator(offset);
  IElementType tokenType = it.getTokenType();
  Language language = tokenType.getLanguage();
  TokenSet comments = myComments.get(language);
  if (comments == null) {
    ParserDefinition definition = LanguageParserDefinitions.INSTANCE.forLanguage(language);
    if (definition != null) {
      comments = definition.getCommentTokens();
    }
    if (comments == null) {
      return false;
    }
    else {
      myComments.put(language, comments);
    }
  }
  return comments.contains(tokenType);
}
 
Example 12
Source Project: consulo   Source File: RefManagerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public RefManagerImpl(@Nonnull Project project, @Nullable AnalysisScope scope, @Nonnull GlobalInspectionContext context) {
  myProject = project;
  myScope = scope;
  myContext = context;
  myPsiManager = PsiManager.getInstance(project);
  myRefProject = new RefProjectImpl(this);
  for (InspectionExtensionsFactory factory : InspectionExtensionsFactory.EP_NAME.getExtensionList()) {
    final RefManagerExtension<?> extension = factory.createRefManagerExtension(this);
    if (extension != null) {
      myExtensions.put(extension.getID(), extension);
      for (Language language : extension.getLanguages()) {
        myLanguageExtensions.put(language, extension);
      }
    }
  }
  if (scope != null) {
    for (Module module : ModuleManager.getInstance(getProject()).getModules()) {
      getRefModule(module);
    }
  }
}
 
Example 13
Source Project: idea-php-typo3-plugin   Source File: FluidFileViewProvider.java    License: MIT License 6 votes vote down vote up
@Nullable
@Override
protected PsiFile createFile(@NotNull Language lang) {
    if (lang == myTemplateDataLanguage) {
        PsiFileImpl file = (PsiFileImpl) LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this);
        file.setContentElementType(TEMPLATE_DATA);

        return file;
    } else if (lang == FluidLanguage.INSTANCE) {

        return LanguageParserDefinitions.INSTANCE.forLanguage(lang).createFile(this);
    } else {

        return null;
    }
}
 
Example 14
Source Project: react-templates-plugin   Source File: RTJSBracesUtil.java    License: MIT License 6 votes vote down vote up
public static boolean hasConflicts(String start, String end, PsiElement element) {
    final Language elementLanguage = element.getLanguage();
    // JSP contains two roots that contain XmlText, don't inject anything in JSP root to prevent double injections
    if ("JSP".equals(elementLanguage.getDisplayName())) {
        return true;
    }

    PsiFile file = element.getContainingFile();
    if (DEFAULT_START.equals(start) || DEFAULT_END.equals(end)) {
        // JSX attributes don't contain AngularJS injections, {{}} is JSX injection with object inside
        if (elementLanguage.isKindOf(JavascriptLanguage.INSTANCE)) return true;

        for (Language language : file.getViewProvider().getLanguages()) {
            if (DEFAULT_CONFLICTS.contains(language.getDisplayName())) {
                return true;
            }
        }
    }
    return false;
}
 
Example 15
Source Project: consulo   Source File: DummyHolder.java    License: Apache License 2.0 6 votes vote down vote up
public DummyHolder(@Nonnull PsiManager manager, @Nullable TreeElement contentElement, @Nullable PsiElement context, @Nullable CharTable table, @Nullable Boolean validity, Language language) {
  super(TokenType.DUMMY_HOLDER, TokenType.DUMMY_HOLDER, new DummyHolderViewProvider(manager));
  myLanguage = language;
  ((DummyHolderViewProvider)getViewProvider()).setDummyHolder(this);
  myContext = context;
  myTable = table != null ? table : IdentityCharTable.INSTANCE;
  if (contentElement instanceof FileElement) {
    ((FileElement)contentElement).setPsi(this);
    ((FileElement)contentElement).setCharTable(myTable);
    setTreeElementPointer((FileElement)contentElement);
  }
  else if (contentElement != null) {
    getTreeElement().rawAddChildren(contentElement);
    clearCaches();
  }
  myExplicitlyValid = validity;
}
 
Example 16
Source Project: consulo   Source File: ScratchFileCreationHelper.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static String reformat(@Nonnull Project project, @Nonnull Language language, @Nonnull String text) {
  return WriteCommandAction.runWriteCommandAction(project, (Computable<String>)() -> {
    PsiFile psi = parseHeader(project, language, text);
    if (psi != null) CodeStyleManager.getInstance(project).reformat(psi);
    return psi == null ? text : psi.getText();
  });
}
 
Example 17
Source Project: consulo   Source File: TextEditorPsiDataProvider.java    License: Apache License 2.0 5 votes vote down vote up
private static Language getLanguageAtCurrentPositionInEditor(Caret caret, final PsiFile psiFile) {
  int caretOffset = caret.getOffset();
  int mostProbablyCorrectLanguageOffset = caretOffset == caret.getSelectionStart() ||
                                          caretOffset == caret.getSelectionEnd()
                                          ? caret.getSelectionStart()
                                          : caretOffset;
  if (caret.hasSelection()) {
    return getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset, caret.getSelectionEnd());
  }

  return PsiUtilCore.getLanguageAtOffset(psiFile, mostProbablyCorrectLanguageOffset);
}
 
Example 18
Source Project: consulo   Source File: FoldingUpdate.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Checks the ability to initialize folding in the Dumb Mode for file.
 *
 * @param file the file to test
 * @return true  if folding initialization available in the Dumb Mode
 */
private static boolean supportsDumbModeFolding(@Nonnull PsiFile file) {
  final FileViewProvider viewProvider = file.getViewProvider();
  for (final Language language : viewProvider.getLanguages()) {
    final FoldingBuilder foldingBuilder = LanguageFolding.INSTANCE.forLanguage(language);
    if (foldingBuilder != null && !DumbService.isDumbAware(foldingBuilder)) return false;
  }
  return true;
}
 
Example 19
Source Project: consulo   Source File: CommonCodeStyleSettingsManager.java    License: Apache License 2.0 5 votes vote down vote up
private void initNonReadSettings() {
  final LanguageCodeStyleSettingsProvider[] providers = Extensions.getExtensions(LanguageCodeStyleSettingsProvider.EP_NAME);
  for (final LanguageCodeStyleSettingsProvider provider : providers) {
    Language target = provider.getLanguage();
    if (!myCommonSettingsMap.containsKey(target)) {
      CommonCodeStyleSettings initialSettings = safelyGetDefaults(provider);
      if (initialSettings != null) {
        init(initialSettings, target);
      }
    }
  }
}
 
Example 20
Source Project: consulo   Source File: LRUPopupBuilder.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
public static ListPopup forFileLanguages(@Nonnull Project project, @Nonnull String title, @Nullable Language selection, @Nonnull Consumer<? super Language> onChosen) {
  return languagePopupBuilder(project, title).
          forValues(LanguageUtil.getFileLanguages()).
          withSelection(selection).
          onChosen(onChosen).
          buildPopup();
}
 
Example 21
Source Project: consulo   Source File: ClassSearchEverywhereContributor.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
static PersistentSearchEverywhereContributorFilter<Language> createLanguageFilter(@Nonnull Project project) {
  List<Language> items = Language.getRegisteredLanguages().stream().filter(lang -> lang != Language.ANY && !(lang instanceof DependentLanguage)).sorted(LanguageUtil.LANGUAGE_COMPARATOR)
          .collect(Collectors.toList());
  GotoClassSymbolConfiguration persistentConfig = GotoClassSymbolConfiguration.getInstance(project);
  return new PersistentSearchEverywhereContributorFilter<>(items, persistentConfig, Language::getDisplayName, language -> {
    final LanguageFileType fileType = language.getAssociatedFileType();
    return fileType != null ? fileType.getIcon() : null;
  });
}
 
Example 22
Source Project: consulo   Source File: InjectedLanguageBlockBuilder.java    License: Apache License 2.0 5 votes vote down vote up
public Block createInjectedBlock(ASTNode node,
                                 Block originalBlock,
                                 Indent indent,
                                 int offset,
                                 TextRange range,
                                 @Nullable Language language)
{
  return new InjectedLanguageBlockWrapper(originalBlock, offset, range, indent, language);
}
 
Example 23
Source Project: needsmoredojo   Source File: AttachPointResolver.java    License: Apache License 2.0 5 votes vote down vote up
@Nullable
public static PsiElement[] getGotoDeclarationTargets(@Nullable PsiElement psiElement, int i, @Nullable Editor editor)
{
    if(psiElement == null || !psiElement.getLanguage().equals(Language.findLanguageByID("JavaScript")))
    {
        return new PsiElement[0];
    }

    DojoSettings settings = ServiceManager.getService(psiElement.getProject(), DojoSettings.class);
    if(!settings.isNeedsMoreDojoEnabled())
    {
        return new PsiElement[0];
    }

    PsiFile templateFile = new TemplatedWidgetUtil(psiElement.getContainingFile()).findTemplatePath();

    if(templateFile == null)
    {
        return new PsiElement[0];
    }

    PsiElement attachPoint = TemplatedWidgetUtil.getAttachPointElementInHtmlFile(psiElement, templateFile);
    if(attachPoint == null)
    {
        return new PsiElement[0];
    }

    return new PsiElement[] { attachPoint };
}
 
Example 24
Source Project: consulo   Source File: SmartPsiFileRangePointerImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Nonnull
private static SmartPointerElementInfo createElementInfo(@Nonnull PsiFile containingFile, @Nonnull ProperTextRange range, boolean forInjected) {
  Project project = containingFile.getProject();
  if (containingFile.getViewProvider() instanceof FreeThreadedFileViewProvider) {
    PsiLanguageInjectionHost host = InjectedLanguageManager.getInstance(project).getInjectionHost(containingFile);
    if (host != null) {
      SmartPsiElementPointer<PsiLanguageInjectionHost> hostPointer = SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host);
      return new InjectedSelfElementInfo(project, containingFile, range, containingFile, hostPointer);
    }
  }
  if (!forInjected && range.equals(containingFile.getTextRange())) return new FileElementInfo(containingFile);
  return new SelfElementInfo(range, Identikit.fromTypes(PsiElement.class, null, Language.ANY), containingFile, forInjected);
}
 
Example 25
Source Project: consulo   Source File: EditorSmartKeysConfigurable.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean hasAnyDocAwareCommenters() {
  final Collection<Language> languages = Language.getRegisteredLanguages();
  for (Language language : languages) {
    final Commenter commenter = LanguageCommenters.INSTANCE.forLanguage(language);
    if (commenter instanceof CodeDocumentationAwareCommenter) {
      final CodeDocumentationAwareCommenter docCommenter = (CodeDocumentationAwareCommenter)commenter;
      if (docCommenter.getDocumentationCommentLinePrefix() != null) {
        return true;
      }
    }
  }
  return false;
}
 
Example 26
Source Project: consulo   Source File: FormatterUtil.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean spacesOnly(@Nullable TreeElement node) {
  if (node == null) return false;

  if (isWhitespaceOrEmpty(node)) return true;
  PsiElement psi = node.getPsi();
  if (psi == null) {
    return false;
  }
  Language language = psi.getLanguage();
  return WhiteSpaceFormattingStrategyFactory.getStrategy(language).containsWhitespacesOnly(node);
}
 
Example 27
Source Project: consulo   Source File: CodeCompletionHandlerBase.java    License: Apache License 2.0 5 votes vote down vote up
public static void addCompletionChar(InsertionContext context, LookupElement item) {
  if (!context.getOffsetMap().containsOffset(InsertionContext.TAIL_OFFSET)) {
    String message = "tailOffset<0 after inserting " + item + " of " + item.getClass();
    if (context instanceof WatchingInsertionContext) {
      message += "; invalidated at: " + ((WatchingInsertionContext)context).invalidateTrace + "\n--------";
    }
    LOG.info(message);
  }
  else if (!CompletionAssertions.isEditorValid(context.getEditor())) {
    LOG.info("Injected editor invalidated " + context.getEditor());
  }
  else {
    context.getEditor().getCaretModel().moveToOffset(context.getTailOffset());
  }
  if (context.getCompletionChar() == Lookup.COMPLETE_STATEMENT_SELECT_CHAR) {
    Language language = PsiUtilBase.getLanguageInEditor(context.getEditor(), context.getFile().getProject());
    if (language != null) {
      for (SmartEnterProcessor processor : SmartEnterProcessors.INSTANCE.allForLanguage(language)) {
        if (processor.processAfterCompletion(context.getEditor(), context.getFile())) break;
      }
    }
  }
  else {
    DataContext dataContext = DataManager.getInstance().getDataContext(context.getEditor().getContentComponent());
    EditorActionManager.getInstance().getTypedAction().getHandler().execute(context.getEditor(), context.getCompletionChar(), dataContext);
  }
}
 
Example 28
Source Project: consulo   Source File: LanguageSubstitutors.java    License: Apache License 2.0 5 votes vote down vote up
private static void processLanguageSubstitution(@Nonnull final VirtualFile file,
                                                @Nonnull Language originalLang,
                                                @Nonnull final Language substitutedLang) {
  if (file instanceof VirtualFileWindow) {
    // Injected files are created with substituted language, no need to reparse:
    //   com.intellij.psi.impl.source.tree.injected.MultiHostRegistrarImpl#doneInjecting
    return;
  }
  Language prevSubstitutedLang = SUBSTITUTED_LANG_KEY.get(file);
  final Language prevLang = ObjectUtil.notNull(prevSubstitutedLang, originalLang);
  if (!prevLang.is(substitutedLang)) {
    if (file.replace(SUBSTITUTED_LANG_KEY, prevSubstitutedLang, substitutedLang)) {
      if (prevSubstitutedLang == null) {
        return; // no need to reparse for the first language substitution
      }
      if (ApplicationManager.getApplication().isUnitTestMode()) {
        return;
      }
      file.putUserData(REPARSING_SCHEDULED, true);
      ApplicationManager.getApplication().invokeLater(new Runnable() {
        @Override
        public void run() {
          if (file.replace(REPARSING_SCHEDULED, true, null)) {
            LOG.info("Reparsing " + file.getPath() + " because of language substitution " +
                     prevLang.getID() + "->" + substitutedLang.getID());
            FileContentUtilCore.reparseFiles(file);
          }
        }
      }, ModalityState.defaultModalityState());
    }
  }
}
 
Example 29
Source Project: consulo   Source File: LineLayout.java    License: Apache License 2.0 5 votes vote down vote up
private static boolean distinctTokens(@Nullable IElementType token1, @Nullable IElementType token2) {
  if (token1 == token2) return false;
  if (token1 == null || token2 == null) return true;
  if (StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(token1) || StringEscapesTokenTypes.STRING_LITERAL_ESCAPES.contains(token2)) return false;
  if (token1 != TokenType.WHITE_SPACE && token2 != TokenType.WHITE_SPACE && !token1.getLanguage().is(token2.getLanguage())) return true;
  Language language = token1.getLanguage();
  if (language == Language.ANY) language = token2.getLanguage();
  BidiRegionsSeparator separator = LanguageBidiRegionsSeparator.INSTANCE.forLanguage(language);
  return separator.createBorderBetweenTokens(token1, token2);
}
 
Example 30
Source Project: intellij-haxe   Source File: PullUpProcessor.java    License: Apache License 2.0 5 votes vote down vote up
private PullUpHelper<MemberInfo> getProcessor(Language language) {
  PullUpHelper<MemberInfo> helper = myProcessors.get(language);
  if (helper == null) {
    //helper = PullUpHelper.INSTANCE.forLanguage(language).createPullUpHelper(this);
    helper = new HaxePullUpHelper(this);
    myProcessors.put(language, helper);
  }
  return helper;
}