コード例 #1
0
  public void registerExtension(
      final PluginDescriptor pluginDescriptor, final Element extensionElement) {
    final PluginId pluginId = pluginDescriptor.getPluginId();

    String epName = extractEPName(extensionElement);

    ExtensionComponentAdapter adapter;
    final PicoContainer container = getPluginContainer(pluginId.getIdString());
    final ExtensionPoint extensionPoint = getExtensionPoint(epName);
    if (extensionPoint.getKind() == ExtensionPoint.Kind.INTERFACE) {
      String implClass = extensionElement.getAttributeValue("implementation");
      if (implClass == null) {
        throw new RuntimeException(
            "'implementation' attribute not specified for '"
                + epName
                + "' extension in '"
                + pluginId.getIdString()
                + "' plugin");
      }
      adapter =
          new ExtensionComponentAdapter(
              implClass,
              extensionElement,
              container,
              pluginDescriptor,
              shouldDeserializeInstance(extensionElement));
    } else {
      adapter =
          new ExtensionComponentAdapter(
              extensionPoint.getClassName(), extensionElement, container, pluginDescriptor, true);
    }
    myExtensionElement2extension.put(extensionElement, adapter);
    internalGetPluginContainer().registerComponent(adapter);
    getExtensionPoint(epName).registerExtensionAdapter(adapter);
  }
 public void doDispose() {
   ExtensionPoint<RuntimeConfigurationProducer> creatorsExtensionPoint =
       Extensions.getArea(null)
           .getExtensionPoint(RuntimeConfigurationProducer.RUNTIME_CONFIGURATION_PRODUCER);
   for (RuntimeConfigurationProducer configurationCreator :
       ListSequence.fromList(
               LegacyRunConfigurationsProvider_CustomApplicationPlugin.this
                   .myConfigurationCreators)
           .reversedList()) {
     creatorsExtensionPoint.unregisterExtension(configurationCreator);
   }
   ListSequence.fromList(
           LegacyRunConfigurationsProvider_CustomApplicationPlugin.this.myConfigurationCreators)
       .clear();
   ExtensionPoint<ConfigurationType> kindsExtensionPoint =
       Extensions.getArea(null).getExtensionPoint(ConfigurationType.CONFIGURATION_TYPE_EP);
   for (ConfigurationType configurationKind :
       ListSequence.fromList(
               LegacyRunConfigurationsProvider_CustomApplicationPlugin.this.myConfigurationKinds)
           .reversedList()) {
     kindsExtensionPoint.unregisterExtension(configurationKind);
   }
   ListSequence.fromList(
           LegacyRunConfigurationsProvider_CustomApplicationPlugin.this.myConfigurationKinds)
       .clear();
 }
  public void doDispose() {
    ExtensionPoint<ConfigurationType> configurationExtensionPoint =
        Extensions.getArea(null).getExtensionPoint(ConfigurationType.CONFIGURATION_TYPE_EP);
    for (ConfigurationType configurationKind :
        ListSequence.fromList(
                RunConfigurationsInitializer_CustomApplicationPlugin.this.myRegisteredKinds)
            .reversedList()) {
      configurationExtensionPoint.unregisterExtension(configurationKind);
    }
    ListSequence.fromList(
            RunConfigurationsInitializer_CustomApplicationPlugin.this.myRegisteredKinds)
        .clear();

    ExtensionPoint<RuntimeConfigurationProducer> producerExtensionPoint =
        Extensions.getArea(null)
            .getExtensionPoint(RuntimeConfigurationProducer.RUNTIME_CONFIGURATION_PRODUCER);
    for (RuntimeConfigurationProducer producer :
        ListSequence.fromList(
            RunConfigurationsInitializer_CustomApplicationPlugin.this.myRegisteredProducers)) {
      producerExtensionPoint.unregisterExtension(producer);
    }
    ListSequence.fromList(
            RunConfigurationsInitializer_CustomApplicationPlugin.this.myRegisteredProducers)
        .clear();
  }
コード例 #4
0
 public void unregisterExtensionPoint(final String extensionPointName) {
   ExtensionPoint extensionPoint = myExtensionPoints.get(extensionPointName);
   if (extensionPoint != null) {
     extensionPoint.reset();
     myExtensionPoints.remove(extensionPointName);
     notifyEPRemoved(extensionPoint);
   }
 }
コード例 #5
0
 public void initializeAnnotators() {
   ExtensionPoint<RefGraphAnnotator> point =
       Extensions.getRootArea().getExtensionPoint(ToolExtensionPoints.INSPECTIONS_GRAPH_ANNOTATOR);
   final RefGraphAnnotator[] graphAnnotators = point.getExtensions();
   for (RefGraphAnnotator annotator : graphAnnotators) {
     registerGraphAnnotator(annotator);
   }
 }
コード例 #6
0
 private void fireBeforeApplicationLoaded() {
   ExtensionPoint<ApplicationLoadListener> point =
       Extensions.getRootArea().getExtensionPoint("com.intellij.ApplicationLoadListener");
   final ApplicationLoadListener[] objects = point.getExtensions();
   for (ApplicationLoadListener object : objects) {
     object.beforeApplicationLoaded(this);
   }
 }
コード例 #7
0
  public void doInit() {
    // register kinds
    ExtensionPoint<ConfigurationType> configurationExtensionPoint =
        Extensions.getArea(null).getExtensionPoint(ConfigurationType.CONFIGURATION_TYPE_EP);

    // add foreign factories
    _FunctionTypes._return_P1_E0<? extends Class<ConfigurationType>, ? super String>
        getClassFunction =
            new _FunctionTypes._return_P1_E0<Class<ConfigurationType>, String>() {
              public Class<ConfigurationType> invoke(String className) {
                try {
                  return (Class<ConfigurationType>)
                      getClass().getClassLoader().loadClass(className);
                } catch (ClassNotFoundException cl) {
                  LOG.error(
                      "Can not find configuration type "
                          + className
                          + ". Check languages dependency.",
                      cl);
                  return (Class<ConfigurationType>) null;
                }
              }
            };
    {
      ConfigurationType configurationType =
          ContainerUtil.findInstance(
              configurationExtensionPoint.getExtensions(),
              getClassFunction.invoke("jetbrains.mps.buildlanguage.plugin.Ant_Kind"));
      if (configurationType != null) {
        ((Ant_Kind) configurationType)
            .addForeignFactory(
                new PackagingBuildScript_Configuration_Factory((Ant_Kind) configurationType));
      }
    }

    // register creators
    ExtensionPoint<RuntimeConfigurationProducer> producerExtensionPoint =
        Extensions.getArea(null)
            .getExtensionPoint(RuntimeConfigurationProducer.RUNTIME_CONFIGURATION_PRODUCER);
    {
      ConfigurationType configurationType =
          ContainerUtil.findInstance(
              configurationExtensionPoint.getExtensions(),
              getClassFunction.invoke("jetbrains.mps.buildlanguage.plugin.Ant_Kind"));
      if (configurationType != null) {
        List<RuntimeConfigurationProducer> configurationProducers =
            PackagingBuildScript_Producer.getProducers(configurationType);
        ListSequence.fromList(
                RunConfigurationsInitializer_CustomApplicationPlugin.this.myRegisteredProducers)
            .addSequence(ListSequence.fromList(configurationProducers));
        for (RuntimeConfigurationProducer producer :
            ListSequence.fromList(configurationProducers)) {
          producerExtensionPoint.registerExtension(producer);
        }
      }
    }
  }
コード例 #8
0
 @Override
 protected void tearDown() throws Exception {
   ExtensionPoint<EntryPoint> point =
       Extensions.getRootArea().getExtensionPoint(ExtensionPoints.DEAD_CODE_TOOL);
   point.unregisterExtension(myUnusedCodeExtension);
   myUnusedCodeExtension = null;
   ext_src = null;
   super.tearDown();
 }
コード例 #9
0
  public InjectedLanguageManagerImpl(Project project, DumbService dumbService) {
    myProject = project;
    myDumbService = dumbService;

    final ExtensionPoint<MultiHostInjector> multiPoint =
        Extensions.getArea(project).getExtensionPoint(MultiHostInjector.MULTIHOST_INJECTOR_EP_NAME);
    multiPoint.addExtensionPointListener(
        new ExtensionPointListener<MultiHostInjector>() {
          @Override
          public void extensionAdded(
              @NotNull MultiHostInjector injector, @Nullable PluginDescriptor pluginDescriptor) {
            registerMultiHostInjector(injector);
          }

          @Override
          public void extensionRemoved(
              @NotNull MultiHostInjector injector, @Nullable PluginDescriptor pluginDescriptor) {
            unregisterMultiHostInjector(injector);
          }
        },
        this);
    final ExtensionPointListener<LanguageInjector> myListener =
        new ExtensionPointListener<LanguageInjector>() {
          @Override
          public void extensionAdded(
              @NotNull LanguageInjector extension, @Nullable PluginDescriptor pluginDescriptor) {
            psiManagerInjectorsChanged();
          }

          @Override
          public void extensionRemoved(
              @NotNull LanguageInjector extension, @Nullable PluginDescriptor pluginDescriptor) {
            psiManagerInjectorsChanged();
          }
        };
    final ExtensionPoint<LanguageInjector> psiManagerPoint =
        Extensions.getRootArea().getExtensionPoint(LanguageInjector.EXTENSION_POINT_NAME);
    psiManagerPoint.addExtensionPointListener(myListener, this);
    myProgress = new DaemonProgressIndicator();
    project
        .getMessageBus()
        .connect(this)
        .subscribe(
            DaemonCodeAnalyzer.DAEMON_EVENT_TOPIC,
            new DaemonCodeAnalyzer.DaemonListener() {
              @Override
              public void daemonFinished() {}

              @Override
              public void daemonCancelEventOccurred() {
                myProgress.cancel();
              }
            });
  }
コード例 #10
0
 protected <T> void addModuleExtension(final ExtensionPointName<T> name, final T extension) {
   final ExtensionPoint<T> extensionPoint = Extensions.getArea(this).getExtensionPoint(name);
   extensionPoint.registerExtension(extension);
   Disposer.register(
       myLifetime,
       new Disposable() {
         @Override
         public void dispose() {
           extensionPoint.unregisterExtension(extension);
         }
       });
 }
コード例 #11
0
 public <T> void addProjectExtension(
     @NotNull ExtensionPointName<T> name, @NotNull final T extension) {
   final ExtensionPoint<T> extensionPoint = Extensions.getArea(myProject).getExtensionPoint(name);
   extensionPoint.registerExtension(extension);
   Disposer.register(
       myParentDisposable,
       new Disposable() {
         @Override
         public void dispose() {
           extensionPoint.unregisterExtension(extension);
         }
       });
 }
コード例 #12
0
 public void resumeInteractions() {
   myAvailabilityNotificationsActive = true;
   ExtensionPoint[] extensionPoints = getExtensionPoints();
   for (ExtensionPoint extensionPoint : extensionPoints) {
     extensionPoint.getExtensions(); // creates extensions from ComponentAdapters
   }
   for (Runnable action : mySuspendedListenerActions) {
     try {
       action.run();
     } catch (Exception e) {
       myLogger.error(e);
     }
   }
   mySuspendedListenerActions.clear();
 }
 public void doInit() {
   // register kinds
   ExtensionPoint<ConfigurationType> kindsExtensionPoint =
       Extensions.getArea(null).getExtensionPoint(ConfigurationType.CONFIGURATION_TYPE_EP);
   {
     ExecutableFileRunConfiguration_ConfigurationType configurationKind =
         new ExecutableFileRunConfiguration_ConfigurationType();
     ListSequence.fromList(
             LegacyRunConfigurationsProvider_CustomApplicationPlugin.this.myConfigurationKinds)
         .addElement(configurationKind);
     kindsExtensionPoint.registerExtension(configurationKind);
   }
   // register foreign factories
   // register creators
 }
コード例 #14
0
 public static <T> void registerExtension(
     final ExtensionsArea area,
     final ExtensionPointName<T> name,
     final T t,
     final Disposable parentDisposable) {
   final ExtensionPoint<T> extensionPoint = area.getExtensionPoint(name.getName());
   extensionPoint.registerExtension(t);
   Disposer.register(
       parentDisposable,
       new Disposable() {
         @Override
         public void dispose() {
           extensionPoint.unregisterExtension(t);
         }
       });
 }
コード例 #15
0
  private static void registerExtensionPointsAndExtensions(
      ExtensionsArea area, List<IdeaPluginDescriptorImpl> loadedPlugins) {
    for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) {
      descriptor.registerExtensionPoints(area);
    }

    Set<String> epNames = ContainerUtil.newHashSet();
    for (ExtensionPoint point : area.getExtensionPoints()) {
      epNames.add(point.getName());
    }

    for (IdeaPluginDescriptorImpl descriptor : loadedPlugins) {
      for (String epName : epNames) {
        descriptor.registerExtensions(area, epName);
      }
    }
  }
コード例 #16
0
  private static void loadComponentRoamingTypes() {
    ExtensionPoint<RoamingTypeExtensionPointBean> point =
        Extensions.getRootArea().getExtensionPoint("com.intellij.ComponentRoamingType");
    final RoamingTypeExtensionPointBean[] componentRoamingTypes = point.getExtensions();

    for (RoamingTypeExtensionPointBean object : componentRoamingTypes) {

      assert object.componentName != null;
      assert object.roamingType != null;

      final RoamingType type = RoamingType.valueOf(object.roamingType);

      assert type != null;

      ComponentRoamingManager.getInstance().setRoamingType(object.componentName, type);
    }
  }
コード例 #17
0
 @SuppressWarnings({"unchecked"})
 private void notifyEPRemoved(final ExtensionPoint extensionPoint) {
   Collection<ExtensionPointAvailabilityListener> listeners =
       myAvailabilityListeners.get(extensionPoint.getName());
   for (final ExtensionPointAvailabilityListener listener : listeners) {
     notifyUnavailableListener(extensionPoint, listener);
   }
 }
 public void testUnsortedSuppressed() throws Exception {
   final ExtensionPoint<AlphaUnsortedPropertiesFileInspectionSuppressor> ep =
       Extensions.getRootArea()
           .getExtensionPoint(AlphaUnsortedPropertiesFileInspectionSuppressor.EP_NAME);
   final AlphaUnsortedPropertiesFileInspectionSuppressor suppressor =
       new AlphaUnsortedPropertiesFileInspectionSuppressor() {
         @Override
         public boolean suppressInspectionFor(PropertiesFile propertiesFile) {
           return propertiesFile.getName().toLowerCase().contains("suppress");
         }
       };
   try {
     ep.registerExtension(suppressor);
     doTest();
   } finally {
     ep.unregisterExtension(suppressor);
   }
 }
コード例 #19
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    myProjectFixture =
        IdeaTestFixtureFactory.getFixtureFactory()
            .createFixtureBuilder(getTestName(true))
            .getFixture();
    myProjectFixture.setUp();

    myProject = myProjectFixture.getProject();
    myProjectRoot = myProject.getBaseDir();
    cd(myProjectRoot);
    Module module = doCreateRealModuleIn("foo", myProject, EmptyModuleType.getInstance());
    myRootModel = ((ModuleRootManagerImpl) ModuleRootManager.getInstance(module)).getRootModel();
    mkdir(myRepositoryFolderName);
    myProjectRoot.refresh(false, true);
    myRepository = myProjectRoot.findChild(myRepositoryFolderName);
    myVcs = new MockAbstractVcs(myProject);
    myVcsManager = (ProjectLevelVcsManagerImpl) ProjectLevelVcsManager.getInstance(myProject);
    ExtensionPoint<VcsRootChecker> point = getExtensionPoint();
    myExtension =
        new VcsRootChecker() {
          @Override
          public VcsKey getSupportedVcs() {
            return myVcs.getKeyInstanceMethod();
          }

          @Override
          public boolean isRoot(@NotNull String path) {
            return new File(path, DOT_MOCK).exists();
          }

          @Override
          public boolean isVcsDir(@Nullable String path) {
            return path != null && path.toLowerCase().endsWith(DOT_MOCK);
          }
        };
    point.registerExtension(myExtension);
    myVcsManager.registerVcs(myVcs);
    myVcsName = myVcs.getName();
    myRepository.refresh(false, true);
  }
コード例 #20
0
  @Override
  protected void setUp() throws Exception {
    super.setUp();
    ExtensionPoint<EntryPoint> point =
        Extensions.getRootArea().getExtensionPoint(ExtensionPoints.DEAD_CODE_TOOL);
    myUnusedCodeExtension =
        new EntryPoint() {
          @NotNull
          @Override
          public String getDisplayName() {
            return "duh";
          }

          @Override
          public boolean isEntryPoint(RefElement refElement, PsiElement psiElement) {
            return isEntryPoint(psiElement);
          }

          @Override
          public boolean isEntryPoint(PsiElement psiElement) {
            return ext_src != null
                && VfsUtilCore.isAncestor(ext_src, PsiUtilCore.getVirtualFile(psiElement), false);
          }

          @Override
          public boolean isSelected() {
            return false;
          }

          @Override
          public void setSelected(boolean selected) {}

          @Override
          public void readExternal(Element element) {}

          @Override
          public void writeExternal(Element element) {}
        };

    point.registerExtension(myUnusedCodeExtension);
  }
コード例 #21
0
  private static void patchRootAreaExtensions() {
    ExtensionsArea rootArea = Extensions.getArea(null);

    for (ToolWindowEP ep : Extensions.getExtensions(ToolWindowEP.EP_NAME)) {
      if (ToolWindowId.FAVORITES_VIEW.equals(ep.id)
          || ToolWindowId.TODO_VIEW.equals(ep.id)
          || EventLog.LOG_TOOL_WINDOW_ID.equals(ep.id)
          || ToolWindowId.STRUCTURE_VIEW.equals(ep.id)) {
        rootArea.getExtensionPoint(ToolWindowEP.EP_NAME).unregisterExtension(ep);
      }
    }

    for (DirectoryProjectConfigurator ep :
        Extensions.getExtensions(DirectoryProjectConfigurator.EP_NAME)) {
      if (ep instanceof PlatformProjectViewOpener) {
        rootArea.getExtensionPoint(DirectoryProjectConfigurator.EP_NAME).unregisterExtension(ep);
      }
    }

    // unregister unrelated tips
    for (TipAndTrickBean tip : Extensions.getExtensions(TipAndTrickBean.EP_NAME)) {
      if (UNRELATED_TIPS.contains(tip.fileName)) {
        rootArea.getExtensionPoint(TipAndTrickBean.EP_NAME).unregisterExtension(tip);
      }
    }

    for (IntentionActionBean ep : Extensions.getExtensions(IntentionManager.EP_INTENTION_ACTIONS)) {
      if ("org.intellij.lang.regexp.intention.CheckRegExpIntentionAction".equals(ep.className)) {
        rootArea.getExtensionPoint(IntentionManager.EP_INTENTION_ACTIONS).unregisterExtension(ep);
      }
    }

    final ExtensionPoint<ProjectAttachProcessor> point =
        Extensions.getRootArea().getExtensionPoint(ProjectAttachProcessor.EP_NAME);
    for (ProjectAttachProcessor attachProcessor :
        Extensions.getExtensions(ProjectAttachProcessor.EP_NAME)) {
      point.unregisterExtension(attachProcessor);
    }
  }
コード例 #22
0
  public EntryPointsManagerImpl(Project project) {
    myProject = project;
    myTemporaryEntryPoints = new HashSet<RefElement>();
    myPersistentEntryPoints =
        new LinkedHashMap<
            String,
            SmartRefElementPointer>(); // To keep the order between readExternal to writeExternal
    Disposer.register(project, this);
    final ExtensionPoint<EntryPoint> point =
        Extensions.getRootArea().getExtensionPoint(ExtensionPoints.DEAD_CODE_TOOL);
    point.addExtensionPointListener(
        new ExtensionPointListener<EntryPoint>() {
          @Override
          public void extensionAdded(
              @NotNull EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) {
            extensionRemoved(extension, pluginDescriptor);
          }

          @Override
          public void extensionRemoved(
              @NotNull EntryPoint extension, @Nullable PluginDescriptor pluginDescriptor) {
            if (ADDITIONAL_ANNOS != null) {
              ADDITIONAL_ANNOS = null;
              UIUtil.invokeLaterIfNeeded(
                  new Runnable() {
                    @Override
                    public void run() {
                      if (ApplicationManager.getApplication().isDisposed()) return;
                      InspectionProfileManager.getInstance().fireProfileChanged(null);
                    }
                  });
            }
          }
        },
        this);
  }
コード例 #23
0
  @Override
  protected boolean queryExternalUsagesRequests(
      @NotNull final RefManager manager,
      @NotNull final GlobalJavaInspectionContext globalContext,
      @NotNull final ProblemDescriptionsProcessor processor) {
    final EntryPointsManager entryPointsManager = globalContext.getEntryPointsManager(manager);
    for (RefElement entryPoint : entryPointsManager.getEntryPoints()) {
      ignoreElement(processor, entryPoint);
    }

    ExtensionPoint<VisibilityExtension> point =
        Extensions.getRootArea().getExtensionPoint(ExtensionPoints.VISIBLITY_TOOL);
    for (VisibilityExtension addin : point.getExtensions()) {
      addin.fillIgnoreList(manager, processor);
    }
    manager.iterate(
        new RefJavaVisitor() {
          @Override
          public void visitElement(@NotNull final RefEntity refEntity) {
            if (!(refEntity instanceof RefElement)) return;
            if (processor.getDescriptions(refEntity) == null) return;
            refEntity.accept(
                new RefJavaVisitor() {
                  @Override
                  public void visitField(@NotNull final RefField refField) {
                    if (refField.getAccessModifier() != PsiModifier.PRIVATE) {
                      globalContext.enqueueFieldUsagesProcessor(
                          refField,
                          new GlobalJavaInspectionContext.UsagesProcessor() {
                            @Override
                            public boolean process(PsiReference psiReference) {
                              ignoreElement(processor, refField);
                              return false;
                            }
                          });
                    }
                  }

                  @Override
                  public void visitMethod(@NotNull final RefMethod refMethod) {
                    if (!refMethod.isExternalOverride()
                        && refMethod.getAccessModifier() != PsiModifier.PRIVATE
                        && !(refMethod instanceof RefImplicitConstructor)) {
                      globalContext.enqueueDerivedMethodsProcessor(
                          refMethod,
                          new GlobalJavaInspectionContext.DerivedMethodsProcessor() {
                            @Override
                            public boolean process(PsiMethod derivedMethod) {
                              ignoreElement(processor, refMethod);
                              return false;
                            }
                          });

                      globalContext.enqueueMethodUsagesProcessor(
                          refMethod,
                          new GlobalJavaInspectionContext.UsagesProcessor() {
                            @Override
                            public boolean process(PsiReference psiReference) {
                              ignoreElement(processor, refMethod);
                              return false;
                            }
                          });

                      if (entryPointsManager.isAddNonJavaEntries()) {
                        final RefClass ownerClass = refMethod.getOwnerClass();
                        if (refMethod.isConstructor()
                            && ownerClass.getDefaultConstructor() != null) {
                          String qualifiedName = ownerClass.getElement().getQualifiedName();
                          if (qualifiedName != null) {
                            final Project project = manager.getProject();
                            PsiSearchHelper.SERVICE
                                .getInstance(project)
                                .processUsagesInNonJavaFiles(
                                    qualifiedName,
                                    new PsiNonJavaFileReferenceProcessor() {
                                      @Override
                                      public boolean process(
                                          PsiFile file, int startOffset, int endOffset) {
                                        entryPointsManager.addEntryPoint(refMethod, false);
                                        ignoreElement(processor, refMethod);
                                        return false;
                                      }
                                    },
                                    GlobalSearchScope.projectScope(project));
                          }
                        }
                      }
                    }
                  }

                  @Override
                  public void visitClass(@NotNull final RefClass refClass) {
                    if (!refClass.isAnonymous()) {
                      globalContext.enqueueDerivedClassesProcessor(
                          refClass,
                          new GlobalJavaInspectionContext.DerivedClassesProcessor() {
                            @Override
                            public boolean process(PsiClass inheritor) {
                              ignoreElement(processor, refClass);
                              return false;
                            }
                          });

                      globalContext.enqueueClassUsagesProcessor(
                          refClass,
                          new GlobalJavaInspectionContext.UsagesProcessor() {
                            @Override
                            public boolean process(PsiReference psiReference) {
                              ignoreElement(processor, refClass);
                              return false;
                            }
                          });
                    }
                  }
                });
          }
        });
    return false;
  }
コード例 #24
0
ファイル: MyTestInjector.java プロジェクト: novokrest/JBIDEA
  private static void injectVariousStuffEverywhere(Disposable parent, final PsiManager psiManager) {
    final Language ql = Language.findLanguageByID("JPAQL");
    final Language js = Language.findLanguageByID("JavaScript");
    final Language html = Language.findLanguageByID("HTML");
    if (ql == null || js == null) return;
    final Language ecma4 = Language.findLanguageByID("ECMA Script Level 4");

    final MultiHostInjector myMultiHostInjector =
        new MultiHostInjector() {
          @Override
          public void getLanguagesToInject(
              @NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
            XmlAttributeValue value = (XmlAttributeValue) context;
            PsiElement parent = value.getParent();
            if (parent instanceof XmlAttribute) {
              @NonNls String attrName = ((XmlAttribute) parent).getLocalName();
              if ("jsInBraces".equals(attrName)) {
                registrar.startInjecting(js);
                String text = value.getText();
                int index = 0;
                while (text.indexOf('{', index) != -1) {
                  int lbrace = text.indexOf('{', index);
                  int rbrace = text.indexOf('}', index);
                  registrar.addPlace(
                      "", "", (PsiLanguageInjectionHost) value, new TextRange(lbrace + 1, rbrace));
                  index = rbrace + 1;
                }
                registrar.doneInjecting();
              }
            }
          }

          @Override
          @NotNull
          public List<? extends Class<? extends PsiElement>> elementsToInjectIn() {
            return Arrays.asList(XmlAttributeValue.class);
          }
        };
    InjectedLanguageManager.getInstance(psiManager.getProject())
        .registerMultiHostInjector(myMultiHostInjector);
    Disposer.register(
        parent,
        new Disposable() {
          @Override
          public void dispose() {
            boolean b =
                InjectedLanguageManager.getInstance(psiManager.getProject())
                    .unregisterMultiHostInjector(myMultiHostInjector);
            assert b;
          }
        });

    final LanguageInjector myInjector =
        new LanguageInjector() {
          @Override
          public void getLanguagesToInject(
              @NotNull PsiLanguageInjectionHost host,
              @NotNull InjectedLanguagePlaces placesToInject) {
            if (host instanceof XmlAttributeValue) {
              XmlAttributeValue value = (XmlAttributeValue) host;
              PsiElement parent = value.getParent();
              if (parent instanceof XmlAttribute) {
                @NonNls String attrName = ((XmlAttribute) parent).getLocalName();
                if ("ql".equals(attrName)) {
                  inject(host, placesToInject, ql);
                  return;
                }
                if ("js".equals(attrName)) {
                  inject(host, placesToInject, js);
                  return;
                }

                if ("jsprefix".equals(attrName)) {
                  inject(host, placesToInject, js, "function foo(doc, window){", "}");
                  return;
                }
              }
            }
            if (host instanceof XmlText) {
              // inject to xml tags named 'ql'
              final XmlText xmlText = (XmlText) host;
              XmlTag tag = xmlText.getParentTag();
              if (tag == null) return;
              if ("ql".equals(tag.getLocalName())) {
                inject(host, placesToInject, ql);
                return;
              }
              if ("js".equals(tag.getLocalName())) {
                inject(host, placesToInject, js);
                return;
              }
              if ("htmlInject".equals(tag.getLocalName())) {
                inject(host, placesToInject, html);
                return;
              }
              if (ecma4 != null && "ecma4".equals(tag.getLocalName())) {
                inject(host, placesToInject, ecma4);
                return;
              }
              if ("jsprefix".equals(tag.getLocalName())) {
                inject(host, placesToInject, js, "function foo(doc, window){", "}");
                return;
              }

              if ("jsInHash".equals(tag.getLocalName())) {
                String text = xmlText.getText();
                if (text.contains("#")) {
                  int start = text.indexOf('#');
                  int end = text.lastIndexOf('#');
                  if (start != end && start != -1) {
                    placesToInject.addPlace(js, new TextRange(start + 1, end), null, null);
                    return;
                  }
                }
              }
            }

            if (host instanceof PsiComment
                && ((PsiComment) host).getTokenType() == JavaTokenType.C_STYLE_COMMENT) {
              /* {{{
               *   js code
               *   js code
               * }}}
               */
              String text = host.getText();
              String prefix = "/*\n * {{{\n";
              String suffix = " }}}\n */";
              if (text.startsWith(prefix) && text.endsWith(suffix)) {
                String s = StringUtil.trimEnd(StringUtil.trimStart(text, prefix), suffix);
                int off = 0;
                while (!s.isEmpty()) {
                  String t = s.trim();
                  if (t.startsWith("*")) t = t.substring(1).trim();
                  int i = s.length() - t.length();
                  off += i;
                  int endOfLine = t.indexOf('\n');
                  if (endOfLine == -1) endOfLine = t.length();
                  placesToInject.addPlace(
                      js, TextRange.from(prefix.length() + off, endOfLine), "", "\n");
                  off += endOfLine;
                  s = s.substring(i + endOfLine);
                }
                return;
              }
            }

            if (host instanceof PsiCommentImpl) {
              String text = host.getText();
              if (text.startsWith("/*--{") && text.endsWith("}--*/")) {
                TextRange textRange = new TextRange(4, text.length() - 4);
                if (!(host.getParent() instanceof PsiMethod)) return;
                PsiMethod method = (PsiMethod) host.getParent();
                if (!method.hasModifierProperty(PsiModifier.NATIVE)
                    || !method.hasModifierProperty(PsiModifier.PUBLIC)) return;
                String paramList = "";
                for (PsiParameter parameter : method.getParameterList().getParameters()) {
                  if (!paramList.isEmpty()) paramList += ",";
                  paramList += parameter.getName();
                }
                @NonNls String header = "function " + method.getName() + "(" + paramList + ") {";
                Language gwt = Language.findLanguageByID("GWT JavaScript");
                placesToInject.addPlace(gwt, textRange, header, "}");
                return;
              }
              PsiElement parent = host.getParent();
              if (parent instanceof PsiMethod && ((PsiMethod) parent).getName().equals("xml")) {
                placesToInject.addPlace(
                    StdLanguages.XML, new TextRange(2, host.getTextLength() - 2), null, null);
                return;
              }
            }

            // inject to all string literal initializers of variables named 'ql'
            if (host instanceof PsiLiteralExpression
                && ((PsiLiteralExpression) host).getValue() instanceof String) {
              PsiVariable variable = PsiTreeUtil.getParentOfType(host, PsiVariable.class);
              if (variable == null) return;
              if (host.getParent() instanceof PsiPolyadicExpression) return;
              if ("ql".equals(variable.getName())) {
                placesToInject.addPlace(ql, textRangeToInject(host), null, null);
              }
              if ("xml".equals(variable.getName())) {
                placesToInject.addPlace(StdLanguages.XML, textRangeToInject(host), null, null);
              }
              if ("js".equals(variable.getName())) { // with prefix/suffix
                placesToInject.addPlace(
                    js, textRangeToInject(host), "function foo(doc,window) {", "}");
              }

              if ("lang".equals(variable.getName())) {
                // various lang depending on field "languageID" content
                PsiClass aClass = PsiTreeUtil.getParentOfType(variable, PsiClass.class);
                aClass = aClass.findInnerClassByName("Language", false);
                String text =
                    aClass
                        .getInitializers()[0]
                        .getBody()
                        .getFirstBodyElement()
                        .getNextSibling()
                        .getText()
                        .substring(2);
                Language language = Language.findLanguageByID(text);

                if (language != null) {
                  placesToInject.addPlace(language, textRangeToInject(host), "", "");
                }
              }
            }
          }
        };

    final ExtensionPoint<LanguageInjector> extensionPoint =
        Extensions.getRootArea().getExtensionPoint(LanguageInjector.EXTENSION_POINT_NAME);
    extensionPoint.registerExtension(myInjector);
    Disposer.register(
        parent,
        new Disposable() {
          @Override
          public void dispose() {
            extensionPoint.unregisterExtension(myInjector);
          }
        });
  }