Merge "Import updater module"
diff --git a/bin/win/IdeaWin32.dll b/bin/win/IdeaWin32.dll
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/IdeaWin64.dll b/bin/win/IdeaWin64.dll
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/breakgen.dll b/bin/win/breakgen.dll
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/breakgen64.dll b/bin/win/breakgen64.dll
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/focuskiller.dll b/bin/win/focuskiller.dll
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/focuskiller64.dll b/bin/win/focuskiller64.dll
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/fsnotifier.exe b/bin/win/fsnotifier.exe
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/restarter.exe b/bin/win/restarter.exe
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/runnerw.exe b/bin/win/runnerw.exe
old mode 100755
new mode 100644
Binary files differ
diff --git a/bin/win/vistalauncher.exe b/bin/win/vistalauncher.exe
old mode 100755
new mode 100644
Binary files differ
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java
index e625dc16..27f61c4 100644
--- a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewImpl.java
@@ -21,7 +21,6 @@
 import com.intellij.ide.errorTreeView.ErrorViewStructure;
 import com.intellij.ide.errorTreeView.GroupingElement;
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.compiler.CompileScope;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Disposer;
@@ -36,9 +35,9 @@
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.ide.PooledThreadExecutor;
 
 import java.util.UUID;
-import java.util.concurrent.Executor;
 
 /**
  * @author Eugene Zhuravlev
@@ -48,12 +47,7 @@
   private static final String PROBLEMS_TOOLWINDOW_ID = "Problems";
   
   private final ProblemsViewPanel myPanel;
-  private final SequentialTaskExecutor myViewUpdater = new SequentialTaskExecutor(new Executor() {
-    @Override
-    public void execute(Runnable command) {
-      ApplicationManager.getApplication().executeOnPooledThread(command);
-    }
-  });
+  private final SequentialTaskExecutor myViewUpdater = new SequentialTaskExecutor(new PooledThreadExecutor());
 
   public ProblemsViewImpl(final Project project, final ToolWindowManager wm) {
     super(project);
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewPanel.java b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewPanel.java
index d65451e..6187745 100644
--- a/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewPanel.java
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/ProblemsViewPanel.java
@@ -25,12 +25,13 @@
     myTree.getEmptyText().setText("No compilation problems found");
   }
 
-
+  @Override
   protected void fillRightToolbarGroup(DefaultActionGroup group) {
     super.fillRightToolbarGroup(group);
     group.add(new CompilerPropertiesAction());
   }
 
+  @Override
   protected void addExtraPopupMenuActions(DefaultActionGroup group) {
     group.add(new ExcludeFromCompileAction(myProject, this));
     // todo: do we need compiler's popup actions here?
@@ -51,5 +52,4 @@
   protected boolean canHideWarnings() {
     return false;
   }
-
-}
+}
\ No newline at end of file
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java b/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java
index add20bd..35091f7 100644
--- a/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java
+++ b/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java
@@ -34,11 +34,11 @@
 import org.jboss.netty.channel.Channels;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.ide.PooledThreadExecutor;
 import org.jetbrains.jps.api.CmdlineProtoUtil;
 import org.jetbrains.jps.api.CmdlineRemoteProto;
 
 import java.util.*;
-import java.util.concurrent.Executor;
 
 /**
  * @author Eugene Zhuravlev
@@ -50,12 +50,7 @@
   private final Project myProject;
   private int myConstantSearchesCount = 0;
   private final CachingSearcher mySearcher;
-  private final SequentialTaskExecutor myTaskExecutor = new SequentialTaskExecutor(new Executor() {
-    @Override
-    public void execute(Runnable command) {
-      ApplicationManager.getApplication().executeOnPooledThread(command);
-    }
-  });
+  private final SequentialTaskExecutor myTaskExecutor = new SequentialTaskExecutor(new PooledThreadExecutor());
 
   protected DefaultMessageHandler(Project project) {
     myProject = project;
diff --git a/java/debugger/impl/src/com/intellij/debugger/DefaultDebugEnvironment.java b/java/debugger/impl/src/com/intellij/debugger/DefaultDebugEnvironment.java
index e0f463e..5a842e4 100644
--- a/java/debugger/impl/src/com/intellij/debugger/DefaultDebugEnvironment.java
+++ b/java/debugger/impl/src/com/intellij/debugger/DefaultDebugEnvironment.java
@@ -20,15 +20,12 @@
 import com.intellij.execution.Executor;
 import com.intellij.execution.configurations.*;
 import com.intellij.execution.filters.ExceptionFilters;
-import com.intellij.execution.filters.Filter;
 import com.intellij.execution.filters.TextConsoleBuilder;
 import com.intellij.execution.runners.ProgramRunner;
 import com.intellij.execution.runners.RunContentBuilder;
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.search.GlobalSearchScope;
 
-import java.util.List;
-
 /**
  * Created by IntelliJ IDEA.
  * User: michael.golubev
@@ -65,10 +62,7 @@
     if (myState instanceof CommandLineState) {
       final TextConsoleBuilder consoleBuilder = ((CommandLineState)myState).getConsoleBuilder();
       if (consoleBuilder != null) {
-        List<Filter> filters = ExceptionFilters.getFilters(mySearchScope);
-        for (Filter filter : filters) {
-          consoleBuilder.addFilter(filter);
-        }
+        consoleBuilder.filters(ExceptionFilters.getFilters(mySearchScope));
       }
     }
     return myState.execute(myExecutor, myRunner);
diff --git a/java/debugger/impl/src/com/intellij/debugger/apiAdapters/TransportServiceWrapper.java b/java/debugger/impl/src/com/intellij/debugger/apiAdapters/TransportServiceWrapper.java
index 84a4679..d667035 100644
--- a/java/debugger/impl/src/com/intellij/debugger/apiAdapters/TransportServiceWrapper.java
+++ b/java/debugger/impl/src/com/intellij/debugger/apiAdapters/TransportServiceWrapper.java
@@ -18,14 +18,11 @@
 import com.intellij.execution.ExecutionException;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.util.ArrayUtil;
-import com.sun.jdi.connect.Transport;
+import com.sun.jdi.connect.spi.TransportService;
 
 import java.io.IOException;
 import java.lang.reflect.Constructor;
 import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.util.HashMap;
-import java.util.Map;
 
 /**
  * @author max
@@ -33,113 +30,28 @@
 public class TransportServiceWrapper {
   private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.apiAdapters.TransportService");
 
-  private final Object myDelegateObject;
-  private final Class myDelegateClass;
+  private final TransportService myTransport;
+  private final Class<? extends TransportService> myDelegateClass;
 
   private static final String SOCKET_TRANSPORT_CLASS = "com.sun.tools.jdi.SocketTransportService";
   private static final String SHMEM_TRANSPORT_CLASS = "com.sun.tools.jdi.SharedMemoryTransportService";
   
-  private final Map<String, Object> myListenAddresses = new HashMap<String, Object>();
-
-  private TransportServiceWrapper(Class delegateClass) throws NoSuchMethodException,
+  private TransportServiceWrapper(Class<? extends TransportService> delegateClass) throws NoSuchMethodException,
                                                       IllegalAccessException,
                                                       InvocationTargetException,
                                                       InstantiationException {
     myDelegateClass = delegateClass;
     final Constructor constructor = delegateClass.getDeclaredConstructor(ArrayUtil.EMPTY_CLASS_ARRAY);
     constructor.setAccessible(true);
-    myDelegateObject = constructor.newInstance(ArrayUtil.EMPTY_OBJECT_ARRAY);
+    myTransport = (TransportService)constructor.newInstance(ArrayUtil.EMPTY_OBJECT_ARRAY);
   }
 
-  /**
-   * Applicable if IDEA is run on JDK 1.4.2.x only!
-   * @param transportObj
-   */
-  private TransportServiceWrapper(Transport transportObj) {
-    myDelegateClass = transportObj.getClass();
-    myDelegateObject = transportObj;
+  public TransportService.ListenKey startListening() throws IOException {
+    return myTransport.startListening();
   }
 
-  public ConnectionServiceWrapper attach(final String s) throws IOException {
-    try {
-      // Applicable if IDEA is run on JDK 1.4.2.x only!
-      // in JDK 1.5 the signature of the "attach" method has been changed to "attach(String, long, long)"
-      //noinspection HardCodedStringLiteral
-      final Method method = myDelegateClass.getMethod("attach", new Class[]{String.class});
-      method.setAccessible(true);
-      return new ConnectionServiceWrapper(method.invoke(myDelegateObject, new Object[]{s}));
-    }
-    catch (NoSuchMethodException e) {
-      LOG.error(e);
-    }
-    catch (IllegalAccessException e) {
-      LOG.error(e);
-    }
-    catch (InvocationTargetException e) {
-      final Throwable cause = e.getCause();
-      if (cause instanceof IOException) {
-        throw (IOException)cause;
-      }
-      LOG.error(e);
-    }
-    return null;
-  }
-
-  public String startListening() throws IOException {
-    try {
-      //noinspection HardCodedStringLiteral
-      final Method method = myDelegateClass.getMethod("startListening", ArrayUtil.EMPTY_CLASS_ARRAY);
-      method.setAccessible(true);
-      final Object rv = method.invoke(myDelegateObject, ArrayUtil.EMPTY_OBJECT_ARRAY);
-      // important! do not cast to string cause return types differ in jdk 1.4 and jdk 1.5
-      final String strValue = rv.toString();
-      myListenAddresses.put(strValue, rv);
-      return strValue;
-    }
-    catch (NoSuchMethodException e) {
-      LOG.error(e);
-    }
-    catch (IllegalAccessException e) {
-      LOG.error(e);
-    }
-    catch (InvocationTargetException e) {
-      final Throwable cause = e.getCause();
-      if (cause instanceof IOException) {
-        throw (IOException)cause;
-      }
-      LOG.error(e);
-    }
-    return null;
-  }
-
-  public void stopListening(final String address) throws IOException {
-    try {
-      Object value = myListenAddresses.get(address);
-      if (value == null) {
-        value = address;
-      }
-      Class paramClass = value.getClass();
-      for (Class superClass = paramClass.getSuperclass(); !Object.class.equals(superClass); superClass = superClass.getSuperclass()) {
-        paramClass = superClass;
-      }
-      //noinspection HardCodedStringLiteral
-      final Method method = myDelegateClass.getMethod("stopListening", new Class[] {paramClass});
-      method.setAccessible(true);
-      method.invoke(myDelegateObject, new Object[]{value});
-    }
-    catch (NoSuchMethodException e) {
-      LOG.error(e);
-    }
-    catch (IllegalAccessException e) {
-      LOG.error(e);
-    }
-    catch (InvocationTargetException e) {
-      final Throwable cause = e.getCause();
-      if (cause instanceof IOException) {
-        throw (IOException)cause;
-      }
-      LOG.error(e);
-    }
+  public void stopListening(final TransportService.ListenKey address) throws IOException {
+    myTransport.stopListening(address);
   }
 
   @SuppressWarnings({"HardCodedStringLiteral"})
@@ -147,11 +59,10 @@
     if (SOCKET_TRANSPORT_CLASS.equals(myDelegateClass.getName())) {
       return "dt_socket";
     }
-    else if (SHMEM_TRANSPORT_CLASS.equals(myDelegateClass.getName())) {
+    if (SHMEM_TRANSPORT_CLASS.equals(myDelegateClass.getName())) {
       return "dt_shmem";
     }
-
-    LOG.error("Unknown serivce");
+    LOG.error("Unknown service");
     return "<unknown>";
   }
 
@@ -160,14 +71,14 @@
     try {
       try {
         if (forceSocketTransport) {
-          transport = new TransportServiceWrapper(Class.forName(SOCKET_TRANSPORT_CLASS));
+          transport = new TransportServiceWrapper((Class<? extends TransportService>)Class.forName(SOCKET_TRANSPORT_CLASS));
         }
         else {
-          transport = new TransportServiceWrapper(Class.forName(SHMEM_TRANSPORT_CLASS));
+          transport = new TransportServiceWrapper((Class<? extends TransportService>)Class.forName(SHMEM_TRANSPORT_CLASS));
         }
       }
       catch (UnsatisfiedLinkError ignored) {
-        transport = new TransportServiceWrapper(Class.forName(SOCKET_TRANSPORT_CLASS));
+        transport = new TransportServiceWrapper((Class<? extends TransportService>)Class.forName(SOCKET_TRANSPORT_CLASS));
       }
     }
     catch (Exception e) {
@@ -176,13 +87,4 @@
     return transport;
   }
 
-  /**
-   * Applicable if IDEA is run on JDK 1.4.2.x only!
-   * @param transportObject
-   * @return transport service wrapper
-   */
-  public static TransportServiceWrapper getTransportService(Transport transportObject){
-    return new TransportServiceWrapper(transportObject);
-  }
-
 }
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
index 4a05b02..d8c7544 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
@@ -19,7 +19,6 @@
 import com.intellij.debugger.*;
 import com.intellij.debugger.actions.DebuggerActions;
 import com.intellij.debugger.apiAdapters.ConnectionServiceWrapper;
-import com.intellij.debugger.apiAdapters.TransportServiceWrapper;
 import com.intellij.debugger.engine.evaluation.*;
 import com.intellij.debugger.engine.events.DebuggerCommandImpl;
 import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
@@ -544,23 +543,7 @@
 
         myDebugProcessDispatcher.getMulticaster().connectorIsReady();
         try {
-          if (SOCKET_ATTACHING_CONNECTOR_NAME.equals(connector.name()) && Patches.SUN_JDI_CONNECTOR_HANGUP_BUG) {
-            String portString = myConnection.getAddress();
-            String hostString = myConnection.getHostName();
-
-            if (hostString == null || hostString.isEmpty()) {
-              //noinspection HardCodedStringLiteral
-              hostString = "localhost";
-            }
-            hostString += ":";
-
-            final TransportServiceWrapper transportServiceWrapper = TransportServiceWrapper.getTransportService(connector.transport());
-            myConnectionService = transportServiceWrapper.attach(hostString + portString);
-            return myConnectionService.createVirtualMachine();
-          }
-          else {
-            return connector.attach(myArguments);
-          }
+          return connector.attach(myArguments);
         }
         catch (IllegalArgumentException e) {
           throw new CantRunException(e.getLocalizedMessage());
diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsImpl.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsImpl.java
index 6be6899..0f368bf 100644
--- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerUtilsImpl.java
@@ -38,6 +38,7 @@
 import com.intellij.psi.PsiExpression;
 import com.intellij.util.net.NetUtils;
 import com.sun.jdi.Value;
+import com.sun.jdi.connect.spi.TransportService;
 import org.jdom.Element;
 
 import java.io.IOException;
@@ -139,8 +140,9 @@
     }
 
     try {
-      String address = transportService.startListening();
-      transportService.stopListening(address);
+      TransportService.ListenKey listenKey = transportService.startListening();
+      final String address = listenKey.address();
+      transportService.stopListening(listenKey);
       return address;
     }
     catch (IOException e) {
diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/GenericDebuggerParametersRunnerConfigurable.java b/java/debugger/impl/src/com/intellij/debugger/impl/GenericDebuggerParametersRunnerConfigurable.java
index b36d0a430..9d5d481 100644
--- a/java/debugger/impl/src/com/intellij/debugger/impl/GenericDebuggerParametersRunnerConfigurable.java
+++ b/java/debugger/impl/src/com/intellij/debugger/impl/GenericDebuggerParametersRunnerConfigurable.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.options.ShowSettingsUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.util.text.StringUtilRt;
 import com.intellij.ui.PortField;
 import com.intellij.xdebugger.impl.settings.DebuggerConfigurable;
 import org.jetbrains.annotations.NotNull;
@@ -99,10 +100,6 @@
   }
 
   @Override
-  public void disposeEditor() {
-  }
-
-  @Override
   public void resetEditorFrom(GenericDebuggerRunnerSettings runnerSettings) {
     setIsLocal(runnerSettings.LOCAL);
     setTransport(runnerSettings.getTransport());
@@ -153,9 +150,8 @@
   }
 
   private void checkPort() throws ConfigurationException {
-    final int port = myPortField.getNumber();
-    if (isSocket() && port > 0 && (port < 0 || port > 0xffff)) {
-      throw new ConfigurationException(DebuggerBundle.message("error.text.invalid.port.0", port));
+    if (isSocket() && !myPortField.isSpecified()) {
+      throw new ConfigurationException(DebuggerBundle.message("error.text.invalid.port"));
     }
   }
 
@@ -172,7 +168,7 @@
 
   private void setPort(String port) {
     if (isSocket()) {
-      myPortField.setNumber(StringUtil.parseInt(port, 0));
+      myPortField.setNumber(StringUtilRt.parseInt(port, 0));
     }
     else {
       myAddressField.setText(port);
diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java
index c189e4b..9ba6365 100644
--- a/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java
+++ b/java/debugger/impl/src/com/intellij/debugger/ui/DebuggerSessionTab.java
@@ -38,7 +38,6 @@
 import com.intellij.execution.configurations.RunProfile;
 import com.intellij.execution.executors.DefaultDebugExecutor;
 import com.intellij.execution.filters.ExceptionFilters;
-import com.intellij.execution.filters.Filter;
 import com.intellij.execution.filters.TextConsoleBuilder;
 import com.intellij.execution.filters.TextConsoleBuilderFactory;
 import com.intellij.execution.ui.ConsoleView;
@@ -100,6 +99,7 @@
     final DebuggerSettings debuggerSettings = DebuggerSettings.getInstance();
     if (!ApplicationManager.getApplication().isUnitTestMode()) {
       getContextManager().addListener(new DebuggerContextListener() {
+        @Override
         public void changeEvent(DebuggerContextImpl newContext, int event) {
           switch (event) {
             case DebuggerSession.EVENT_DETACHED:
@@ -176,12 +176,14 @@
     }
 
     myUi.addListener(new ContentManagerAdapter() {
+      @Override
       public void selectionChanged(ContentManagerEvent event) {
         updateStatus(event.getContent());
       }
     }, this);
 
     debuggerSession.getContextManager().addListener(new DebuggerContextListener() {
+      @Override
       public void changeEvent(DebuggerContextImpl newContext, int event) {
         if (!myUi.isDisposed()) {
           attractFramesOnPause(event);
@@ -346,6 +348,7 @@
   }
 
 
+  @Override
   public void dispose() {
     disposeSession();
     myFramesPanel.dispose();
@@ -452,10 +455,7 @@
   public void addThreadDump(List<ThreadState> threads) {
     final Project project = getProject();
     final TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
-    List<Filter> filters = ExceptionFilters.getFilters(myDebuggerSession.getSearchScope());
-    for (Filter filter : filters) {
-      consoleBuilder.addFilter(filter);
-    }
+    consoleBuilder.filters(ExceptionFilters.getFilters(myDebuggerSession.getSearchScope()));
     final ConsoleView consoleView = consoleBuilder.getConsole();
     final DefaultActionGroup toolbarActions = new DefaultActionGroup();
     consoleView.allowHeavyFilters();
@@ -471,11 +471,13 @@
     myThreadDumpsCount += 1;
     myCurrentThreadDumpId += 1;
     Disposer.register(this, new Disposable() {
+      @Override
       public void dispose() {
         myUi.removeContent(content, true);
       }
     });
     Disposer.register(content, new Disposable() {
+      @Override
       public void dispose() {
         myThreadDumpsCount -= 1;
         if (myThreadDumpsCount == 0) {
@@ -494,15 +496,18 @@
   }
 
   private class MyDebuggerStateManager extends DebuggerStateManager {
+    @Override
     public void fireStateChanged(DebuggerContextImpl newContext, int event) {
       super.fireStateChanged(newContext, event);
     }
 
+    @Override
     public DebuggerContextImpl getContext() {
       final DebuggerSession session = myDebuggerSession;
       return session != null ? session.getContextManager().getContext() : DebuggerContextImpl.EMPTY_CONTEXT;
     }
 
+    @Override
     public void setState(DebuggerContextImpl context, int state, int event, String description) {
       final DebuggerSession session = myDebuggerSession;
       if (session != null) {
@@ -519,6 +524,7 @@
       myAutoModeEnabled = DebuggerSettings.getInstance().AUTO_VARIABLES_MODE;
     }
 
+    @Override
     public void update(final AnActionEvent e) {
       super.update(e);
       final Presentation presentation = e.getPresentation();
@@ -526,10 +532,12 @@
       presentation.setText(autoModeEnabled ? "All-Variables Mode" : "Auto-Variables Mode");
     }
 
+    @Override
     public boolean isSelected(AnActionEvent e) {
       return myAutoModeEnabled;
     }
 
+    @Override
     public void setSelected(AnActionEvent e, boolean enabled) {
       myAutoModeEnabled = enabled;
       DebuggerSettings.getInstance().AUTO_VARIABLES_MODE = enabled;
@@ -551,6 +559,7 @@
       myTextUnavailable = DebuggerBundle.message("action.watches.method.return.value.unavailable.reason");
     }
 
+    @Override
     public void update(final AnActionEvent e) {
       super.update(e);
       final Presentation presentation = e.getPresentation();
@@ -567,10 +576,12 @@
       }
     }
 
+    @Override
     public boolean isSelected(AnActionEvent e) {
       return myWatchesReturnValues;
     }
 
+    @Override
     public void setSelected(AnActionEvent e, boolean watch) {
       myWatchesReturnValues = watch;
       DebuggerSettings.getInstance().WATCH_RETURN_VALUES = watch;
diff --git a/java/execution/impl/src/com/intellij/execution/applet/AppletConfigurable.java b/java/execution/impl/src/com/intellij/execution/applet/AppletConfigurable.java
index c781a7f..d7027dd 100644
--- a/java/execution/impl/src/com/intellij/execution/applet/AppletConfigurable.java
+++ b/java/execution/impl/src/com/intellij/execution/applet/AppletConfigurable.java
@@ -40,7 +40,8 @@
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.io.File;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.List;
 
 public class AppletConfigurable extends SettingsEditor<AppletConfiguration> implements CheckableRunConfigurationEditor<AppletConfiguration>,
@@ -256,9 +257,6 @@
     return myWholePanel;
   }
 
-  public void disposeEditor() {
-  }
-
   public void checkEditorData(final AppletConfiguration configuration) {
     configuration.MAIN_CLASS_NAME = toNull(getClassNameComponent().getText());
     configuration.HTML_FILE_NAME = toSystemFormat(getHtmlPathComponent().getText());
diff --git a/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurable.java b/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurable.java
index 4fb04e2..b72a888 100644
--- a/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurable.java
+++ b/java/execution/impl/src/com/intellij/execution/application/ApplicationConfigurable.java
@@ -114,9 +114,6 @@
     return myWholePanel;
   }
 
-  public void disposeEditor() {
-  }
-
   private void createUIComponents() {
     myMainClass = new LabeledComponent<EditorTextFieldWithBrowseButton>();
     myMainClass.setComponent(new EditorTextFieldWithBrowseButton(myProject, true, new JavaCodeFragment.VisibilityChecker() {
diff --git a/java/execution/impl/src/com/intellij/execution/remote/RemoteConfigurable.java b/java/execution/impl/src/com/intellij/execution/remote/RemoteConfigurable.java
index cfcf4e1..5cfd535 100644
--- a/java/execution/impl/src/com/intellij/execution/remote/RemoteConfigurable.java
+++ b/java/execution/impl/src/com/intellij/execution/remote/RemoteConfigurable.java
@@ -180,9 +180,6 @@
     return myPanel;
   }
 
-  public void disposeEditor() {
-  }
-
   private void updateHelpText() {
     boolean useSockets = !myRbShmem.isSelected();
 
diff --git a/java/execution/openapi/src/com/intellij/execution/JavaExecutionUtil.java b/java/execution/openapi/src/com/intellij/execution/JavaExecutionUtil.java
index 2ac23b7..95a2c2d 100644
--- a/java/execution/openapi/src/com/intellij/execution/JavaExecutionUtil.java
+++ b/java/execution/openapi/src/com/intellij/execution/JavaExecutionUtil.java
@@ -25,7 +25,6 @@
 import com.intellij.execution.util.ExecutionErrorDialog;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.module.Module;
-import com.intellij.openapi.module.ModuleUtil;
 import com.intellij.openapi.module.ModuleUtilCore;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Condition;
@@ -109,26 +108,28 @@
       myIcon = icon;
     }
 
+    @Override
     public Icon getIcon() {
       return myIcon;
     }
 
+    @Override
     public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
       final JavaCommandLineState state = new JavaCommandLineState(env) {
+        @Override
         protected JavaParameters createJavaParameters() {
           return myParameters;
         }
       };
       final TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(myProject);
       if (myFilters != null) {
-        for (final Filter myFilter : myFilters) {
-          builder.addFilter(myFilter);
-        }
+        builder.filters(myFilters);
       }
       state.setConsoleBuilder(builder);
       return state;
     }
 
+    @Override
     public String getName() {
       return myContentName;
     }
@@ -154,7 +155,7 @@
   }
 
   public static Module findModule(@NotNull final PsiClass psiClass) {
-    return ModuleUtil.findModuleForPsiElement(psiClass);
+    return ModuleUtilCore.findModuleForPsiElement(psiClass);
   }
 
   @Nullable
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java
index 1f8ebc6..4465367 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/nullable/NullableStuffInspectionBase.java
@@ -417,6 +417,7 @@
     }
   }
 
+  @NotNull
   private static LocalQuickFix[] wrapFix(LocalQuickFix fix) {
     if (fix == null) return LocalQuickFix.EMPTY_ARRAY;
     return new LocalQuickFix[]{fix};
diff --git a/java/java-impl/src/com/intellij/codeInspection/unusedImport/UnusedImportLocalInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/unusedImport/UnusedImportLocalInspection.java
similarity index 89%
rename from java/java-impl/src/com/intellij/codeInspection/unusedImport/UnusedImportLocalInspection.java
rename to java/java-analysis-impl/src/com/intellij/codeInspection/unusedImport/UnusedImportLocalInspection.java
index a8feaf9..362eb75 100644
--- a/java/java-impl/src/com/intellij/codeInspection/unusedImport/UnusedImportLocalInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/unusedImport/UnusedImportLocalInspection.java
@@ -17,7 +17,7 @@
 package com.intellij.codeInspection.unusedImport;
 
 import com.intellij.codeInsight.daemon.GroupNames;
-import com.intellij.codeInspection.BaseJavaLocalInspectionTool;
+import com.intellij.codeInspection.BaseJavaBatchLocalInspectionTool;
 import com.intellij.codeInspection.InspectionsBundle;
 import com.intellij.codeInspection.ex.PairedUnfairLocalInspectionTool;
 import com.siyeh.ig.imports.UnusedImportInspection;
@@ -28,7 +28,7 @@
  * User: anna
  * Date: 17-Feb-2006
  */
-public class UnusedImportLocalInspection extends BaseJavaLocalInspectionTool implements PairedUnfairLocalInspectionTool {
+public class UnusedImportLocalInspection extends BaseJavaBatchLocalInspectionTool implements PairedUnfairLocalInspectionTool {
   @NonNls public static final String SHORT_NAME = "UNUSED_IMPORT";
   public static final String DISPLAY_NAME = InspectionsBundle.message("unused.import");
 
diff --git a/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java b/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java
index 7f645a5..6899c7a 100644
--- a/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java
+++ b/java/java-impl/src/com/intellij/analysis/JavaAnalysisScope.java
@@ -31,6 +31,7 @@
 import com.intellij.psi.search.PackageScope;
 import com.intellij.psi.search.SearchScope;
 import com.intellij.util.containers.ContainerUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.HashSet;
@@ -56,7 +57,7 @@
     final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(defaultProject).getFileIndex();
     final HashSet<Module> modules = new HashSet<Module>();
     if (myType == FILE) {
-      if (myElement instanceof PsiJavaFile && !JspPsiUtil.isInJspFile(myElement)) {
+      if (myElement instanceof PsiJavaFile && !FileTypeUtils.isInServerPageFile(myElement)) {
         PsiJavaFile psiJavaFile = (PsiJavaFile)myElement;
         final PsiClass[] classes = psiJavaFile.getClasses();
         boolean onlyPackLocalClasses = true;
@@ -83,7 +84,7 @@
     return super.getNarrowedComplementaryScope(defaultProject);
   }
 
-  
+
 
   @Override
   public String getShortenName() {
diff --git a/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java b/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java
index 0cb53dd..fe002f6 100644
--- a/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/CodeInsightUtil.java
@@ -43,6 +43,7 @@
 import com.intellij.util.FilteredQuery;
 import com.intellij.util.Processor;
 import com.intellij.util.Query;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -108,7 +109,7 @@
         break;
       }
       if (parent instanceof PsiCodeBlock) break;
-      if (JspPsiUtil.isInJspFile(parent) && parent instanceof PsiFile) break;
+      if (FileTypeUtils.isInServerPageFile(parent) && parent instanceof PsiFile) break;
       if (parent instanceof PsiCodeFragment) break;
       if (parent == null || parent instanceof PsiFile) return PsiElement.EMPTY_ARRAY;
       parent = parent.getParent();
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
index d0aa4f96..2cbde60 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
@@ -27,6 +27,7 @@
 import com.intellij.openapi.projectRoots.JavaSdkVersion;
 import com.intellij.openapi.projectRoots.JavaVersionService;
 import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
@@ -59,49 +60,24 @@
   public static HighlightInfo checkInferredTypeArguments(PsiMethod genericMethod,
                                                          PsiMethodCallExpression call,
                                                          PsiSubstitutor substitutor) {
-    PsiTypeParameter[] typeParameters = genericMethod.getTypeParameters();
-    for (PsiTypeParameter typeParameter : typeParameters) {
-      PsiType substituted = substitutor.substitute(typeParameter);
-      if (substituted == null) return null;
-      substituted = PsiUtil.captureToplevelWildcards(substituted, call);
-      PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes();
-      for (PsiClassType type : extendsTypes) {
-        PsiType extendsType = substitutor.substitute(type);
-        if (substituted instanceof PsiWildcardType) {
-          if (((PsiWildcardType)substituted).isSuper()) {
-            continue;
-          }
-          final PsiType extendsBound = ((PsiWildcardType)substituted).getExtendsBound();
-          if (TypeConversionUtil.erasure(extendsType).equals(TypeConversionUtil.erasure(extendsBound))) {
-            if (extendsBound instanceof PsiClassType) {
-              PsiType[] parameters = ((PsiClassType)extendsBound).getParameters();
-              if (parameters.length == 1) {
-                PsiType argType = parameters[0];
-                if (argType instanceof PsiCapturedWildcardType) {
-                  argType = ((PsiCapturedWildcardType)argType).getWildcard();
-                }
-                if (argType instanceof PsiWildcardType && !((PsiWildcardType)argType).isBounded()) continue;
-              }
-            }
-          }
-        }
-        if (!TypeConversionUtil.isAssignable(extendsType, substituted, false)) {
-          PsiClass boundClass = extendsType instanceof PsiClassType ? ((PsiClassType)extendsType).resolve() : null;
+    final Pair<PsiTypeParameter, PsiType> inferredTypeArgument =
+      GenericsUtil.findTypeParameterWithBoundError(genericMethod.getTypeParameters(), substitutor, call, false);
+    if (inferredTypeArgument != null) {
+      final PsiType extendsType = inferredTypeArgument.second;
+      final PsiTypeParameter typeParameter = inferredTypeArgument.first;
+      PsiClass boundClass = extendsType instanceof PsiClassType ? ((PsiClassType)extendsType).resolve() : null;
 
-          @NonNls String messageKey = boundClass == null || typeParameter.isInterface() == boundClass.isInterface()
-                                      ? "generics.inferred.type.for.type.parameter.is.not.within.its.bound.extend"
-                                      : "generics.inferred.type.for.type.parameter.is.not.within.its.bound.implement";
+      @NonNls String messageKey = boundClass == null || typeParameter.isInterface() == boundClass.isInterface()
+                                  ? "generics.inferred.type.for.type.parameter.is.not.within.its.bound.extend"
+                                  : "generics.inferred.type.for.type.parameter.is.not.within.its.bound.implement";
 
-          String description = JavaErrorMessages.message(
-            messageKey,
-            HighlightUtil.formatClass(typeParameter),
-            JavaHighlightUtil.formatType(extendsType),
-            JavaHighlightUtil.formatType(substituted)
-          );
-
-          return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(call).descriptionAndTooltip(description).create();
-        }
-      }
+      String description = JavaErrorMessages.message(
+        messageKey,
+        HighlightUtil.formatClass(typeParameter),
+        JavaHighlightUtil.formatType(extendsType),
+        JavaHighlightUtil.formatType(substitutor.substitute(typeParameter))
+      );
+      return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(call).descriptionAndTooltip(description).create();
     }
 
     return null;
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
index f74f6f9..c32a30c 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
@@ -32,6 +32,7 @@
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.util.Processor;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -265,7 +266,7 @@
         scope = PsiTreeUtil.getParentOfType(scope, PsiCodeBlock.class);
       }
 
-      topBlock = JspPsiUtil.isInJspFile(scope) && scope instanceof PsiFile ? scope : PsiUtil.getTopLevelEnclosingCodeBlock(expression, scope);
+      topBlock = FileTypeUtils.isInServerPageFile(scope) && scope instanceof PsiFile ? scope : PsiUtil.getTopLevelEnclosingCodeBlock(expression, scope);
       if (variable instanceof PsiField) {
         // non final field already initialized with default value
         if (!variable.hasModifierProperty(PsiModifier.FINAL)) return null;
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
index 7916c58..5c59702 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
@@ -43,13 +43,10 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
-import com.intellij.psi.impl.source.jsp.jspJava.JspClass;
-import com.intellij.psi.impl.source.jsp.jspJava.JspHolderMethod;
 import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
 import com.intellij.psi.impl.source.tree.java.PsiLiteralExpressionImpl;
 import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl;
 import com.intellij.psi.javadoc.PsiDocComment;
-import com.intellij.psi.jsp.JspFile;
 import com.intellij.psi.scope.processor.VariablesNotProcessor;
 import com.intellij.psi.scope.util.PsiScopesUtil;
 import com.intellij.psi.search.GlobalSearchScope;
@@ -64,6 +61,7 @@
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.xml.util.XmlStringUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import gnu.trove.THashMap;
 import org.intellij.lang.annotations.Language;
 import org.jetbrains.annotations.NonNls;
@@ -484,7 +482,7 @@
     if (method == null && lambda != null) {
       //todo check return statements type inside lambda
     }
-    else if (method == null && !(parent instanceof JspFile)) {
+    else if (method == null && !(parent instanceof ServerPageFile)) {
       description = JavaErrorMessages.message("return.outside.method");
       errorResult = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(statement).descriptionAndTooltip(description).create();
     }
@@ -697,11 +695,11 @@
 
   @Nullable
   private static HighlightInfoType getUnhandledExceptionHighlightType(final PsiElement element) {
-    if (!JspPsiUtil.isInJspFile(element)) {
+    if (!FileTypeUtils.isInServerPageFile(element)) {
       return HighlightInfoType.UNHANDLED_EXCEPTION;
     }
     PsiMethod targetMethod = PsiTreeUtil.getParentOfType(element, PsiMethod.class);
-    if (!(targetMethod instanceof JspHolderMethod)) return HighlightInfoType.UNHANDLED_EXCEPTION;
+    if (!(targetMethod instanceof SyntheticElement)) return HighlightInfoType.UNHANDLED_EXCEPTION;
     // ignore JSP top level errors - it handled by UnhandledExceptionInJSP inspection
     return null;
   }
@@ -806,7 +804,7 @@
         if (PsiModifier.PUBLIC.equals(modifier)) {
           isAllowed = modifierOwnerParent instanceof PsiJavaFile ||
                       modifierOwnerParent instanceof PsiClass &&
-                      (modifierOwnerParent instanceof JspClass || ((PsiClass)modifierOwnerParent).getQualifiedName() != null);
+                      (modifierOwnerParent instanceof PsiSyntheticClass || ((PsiClass)modifierOwnerParent).getQualifiedName() != null);
         }
         else if (PsiModifier.STATIC.equals(modifier) || PsiModifier.PRIVATE.equals(modifier) || PsiModifier.PROTECTED.equals(modifier) ||
                  PsiModifier.PACKAGE_LOCAL.equals(modifier)) {
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
index 290633f..5c9e198 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
@@ -36,7 +36,6 @@
 import com.intellij.psi.*;
 import com.intellij.psi.controlFlow.ControlFlowUtil;
 import com.intellij.psi.impl.source.javadoc.PsiDocMethodOrFieldRef;
-import com.intellij.psi.impl.source.jsp.jspJava.JspClass;
 import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
 import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl;
@@ -362,7 +361,7 @@
   @Override
   public void visitClass(PsiClass aClass) {
     super.visitClass(aClass);
-    if (aClass instanceof JspClass) return;
+    if (aClass instanceof PsiSyntheticClass) return;
     if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkInterfaceMultipleInheritance(aClass));
     if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkDuplicateTopLevelClass(aClass));
     if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkEnumMustNotBeLocal(aClass));
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodFix.java
index 2021b1b..aa7cdee 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddMethodFix.java
@@ -96,12 +96,11 @@
                              @NotNull PsiElement endElement) {
     final PsiClass myClass = (PsiClass)startElement;
 
-    return myMethodPrototype != null
-           && myMethodPrototype.isValid()
-           && myClass.isValid()
-           && myClass.getManager().isInProject(myClass)
-           && myText != null
-           && MethodSignatureUtil.findMethodBySignature(myClass, myMethodPrototype, false) == null
+    return myMethodPrototype.isValid() &&
+           myClass.isValid() &&
+           myClass.getManager().isInProject(myClass) &&
+           myText != null &&
+           MethodSignatureUtil.findMethodBySignature(myClass, myMethodPrototype, false) == null
         ;
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java
index 5de7252..1a2683e 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/ImportClassFixBase.java
@@ -46,6 +46,7 @@
 import com.intellij.util.Processor;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.HashSet;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -287,7 +288,7 @@
 
     if (classes.length == 1
         && (canImportHere = canImportHere(allowCaretNearRef, editor, psiFile, classes[0].getName()))
-        && (JspPsiUtil.isInJspFile(psiFile) ?
+        && (FileTypeUtils.isInServerPageFile(psiFile) ?
             CodeInsightSettings.getInstance().JSP_ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY :
             CodeInsightSettings.getInstance().ADD_UNAMBIGIOUS_IMPORTS_ON_THE_FLY)
         && (ApplicationManager.getApplication().isUnitTestMode() || codeAnalyzer.canChangeFileSilently(psiFile))
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.form b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.form
index ce18bcc..51a40ab 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.form
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/LocateLibraryDialog.form
@@ -1,7 +1,7 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.codeInsight.daemon.impl.quickfix.LocateLibraryDialog">
   <grid id="cbd77" binding="contentPane" layout-manager="GridLayoutManager" row-count="2" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
-    <margin top="0" left="10" bottom="10" right="10"/>
+    <margin top="0" left="0" bottom="0" right="0"/>
     <constraints>
       <xy x="48" y="54" width="623" height="297"/>
     </constraints>
@@ -14,7 +14,7 @@
           <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="4" hsize-policy="7" anchor="1" fill="1" indent="0" use-parent-layout="false"/>
         </constraints>
         <properties/>
-        <border type="etched"/>
+        <border type="none"/>
         <children>
           <component id="feb4c" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myLibraryFile">
             <constraints>
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java
index 735520a..5534f5f 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateClassOrPackageFix.java
@@ -74,19 +74,20 @@
         i.remove();
       }
     }
-    return directories.isEmpty() ? null : new CreateClassOrPackageFix(directories,
-                                                                      context,
-                                                                      fixPath ? qualifiedName : redPart,
-                                                                      redPart,
-                                                                      kind,
-                                                                      superClass,
-                                                                      templateName);
+    return new CreateClassOrPackageFix(directories,
+                                       context,
+                                       fixPath ? qualifiedName : redPart,
+                                       redPart,
+                                       kind,
+                                       superClass,
+                                       templateName);
   }
 
   @Nullable
   public static CreateClassOrPackageFix createFix(@NotNull final String qualifiedName,
                                                   @NotNull final PsiElement context,
-                                                  @Nullable ClassKind kind, final String superClass) {
+                                                  @Nullable ClassKind kind,
+                                                  String superClass) {
     return createFix(qualifiedName, context.getResolveScope(), context, null, kind, superClass, null);
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateFieldOrPropertyFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateFieldOrPropertyFix.java
index b63d891..956e57c 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateFieldOrPropertyFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/quickFix/CreateFieldOrPropertyFix.java
@@ -52,7 +52,11 @@
   private final PropertyMemberType myMemberType;
   private final PsiAnnotation[] myAnnotations;
 
-  public CreateFieldOrPropertyFix(final PsiClass aClass, final String name, final PsiType type, final PropertyMemberType memberType, final PsiAnnotation[] annotations) {
+  public CreateFieldOrPropertyFix(final PsiClass aClass,
+                                  final String name,
+                                  final PsiType type,
+                                  @NotNull PropertyMemberType memberType,
+                                  final PsiAnnotation[] annotations) {
     myClass = aClass;
     myName = name;
     myType = type;
diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/AntLikePropertySelectionHandler.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/AntLikePropertySelectionHandler.java
index ffd75c7..7b87a8c 100644
--- a/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/AntLikePropertySelectionHandler.java
+++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/wordSelection/AntLikePropertySelectionHandler.java
@@ -15,9 +15,10 @@
  */
 package com.intellij.codeInsight.editorActions.wordSelection;
 
-import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandler;
+import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase;
 import com.intellij.lang.Language;
 import com.intellij.lang.StdLanguages;
+import com.intellij.lang.java.JavaLanguage;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiComment;
@@ -28,11 +29,11 @@
 import java.util.Collections;
 import java.util.List;
 
-public class AntLikePropertySelectionHandler implements ExtendWordSelectionHandler {
+public class AntLikePropertySelectionHandler extends ExtendWordSelectionHandlerBase {
   @Override
   public boolean canSelect(PsiElement e) {
     Language l = e.getLanguage();
-    if (!(l.equals(StdLanguages.JAVA)
+    if (!(l.equals(JavaLanguage.INSTANCE)
           || l.equals(StdLanguages.XML)
           || l.equals(StdLanguages.ANT))) {
       return false;
diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithIfExpressionSurrounder.java b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithIfExpressionSurrounder.java
index 0c492c9..38fd5a9 100644
--- a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithIfExpressionSurrounder.java
+++ b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithIfExpressionSurrounder.java
@@ -24,6 +24,7 @@
 import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.util.IncorrectOperationException;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NonNls;
 
 class JavaWithIfExpressionSurrounder extends JavaExpressionSurrounder{
@@ -35,7 +36,7 @@
     PsiElement parent = expr.getParent();
     if (!(parent instanceof PsiExpressionStatement)) return false;
     final PsiElement element = parent.getParent();
-    if (!(element instanceof PsiCodeBlock) && !(JspPsiUtil.isInJspFile(element)  && element instanceof PsiFile)) return false;
+    if (!(element instanceof PsiCodeBlock) && !(FileTypeUtils.isInServerPageFile(element)  && element instanceof PsiFile)) return false;
     return true;
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithNullCheckSurrounder.java b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithNullCheckSurrounder.java
index aa258ab..c6a1221 100644
--- a/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithNullCheckSurrounder.java
+++ b/java/java-impl/src/com/intellij/codeInsight/generation/surroundWith/JavaWithNullCheckSurrounder.java
@@ -24,6 +24,7 @@
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.IncorrectOperationException;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NonNls;
 
 class JavaWithNullCheckSurrounder extends JavaExpressionSurrounder{
@@ -36,7 +37,7 @@
     PsiElement parent = PsiTreeUtil.getParentOfType(expr, PsiExpressionStatement.class);
     if (parent == null) return false;
     final PsiElement element = parent.getParent();
-    if (!(element instanceof PsiCodeBlock) && !(JspPsiUtil.isInJspFile(element)  && element instanceof PsiFile)) return false;
+    if (!(element instanceof PsiCodeBlock) && !(FileTypeUtils.isInServerPageFile(element)  && element instanceof PsiFile)) return false;
     return true;
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java
index c55a21b..6ba29bb 100644
--- a/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java
+++ b/java/java-impl/src/com/intellij/codeInsight/intention/impl/config/QuickFixFactoryImpl.java
@@ -32,6 +32,7 @@
  * @author cdr
  */
 public class QuickFixFactoryImpl extends QuickFixFactory {
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createModifierListFix(@NotNull PsiModifierList modifierList,
                                                                            @NotNull String modifier,
@@ -40,6 +41,7 @@
     return new ModifierFix(modifierList, modifier, shouldHave,showContainingClass);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createModifierListFix(@NotNull PsiModifierListOwner owner,
                                                                            @NotNull final String modifier,
@@ -48,6 +50,7 @@
     return new ModifierFix(owner, modifier, shouldHave, showContainingClass);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createMethodReturnFix(@NotNull PsiMethod method,
                                                                            @NotNull PsiType toReturn,
@@ -55,28 +58,33 @@
     return new MethodReturnTypeFix(method, toReturn, fixWholeHierarchy);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createAddMethodFix(@NotNull PsiMethod method, @NotNull PsiClass toClass) {
     return new AddMethodFix(method, toClass);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createAddMethodFix(@NotNull String methodText,
                                                                         @NotNull PsiClass toClass,
-                                                                        String... exceptions) {
+                                                                        @NotNull String... exceptions) {
     return new AddMethodFix(methodText, toClass, exceptions);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createImplementMethodsFix(@NotNull PsiClass aClass) {
     return new ImplementMethodsFix(aClass);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createImplementMethodsFix(@NotNull PsiElement psiElement) {
     return new ImplementMethodsFix(psiElement);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixOnPsiElement createMethodThrowsFix(@NotNull PsiMethod method,
                                                          @NotNull PsiClassType exceptionClass,
@@ -85,16 +93,18 @@
     return new MethodThrowsFix(method, exceptionClass, shouldThrow, showContainingClass);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createAddDefaultConstructorFix(@NotNull PsiClass aClass) {
     return new AddDefaultConstructorFix(aClass);
   }
 
   @Override
-  public LocalQuickFixAndIntentionActionOnPsiElement createAddConstructorFix(@NotNull PsiClass aClass, String modifier) {
+  public LocalQuickFixAndIntentionActionOnPsiElement createAddConstructorFix(@NotNull PsiClass aClass, @NotNull String modifier) {
     return aClass.getName() != null ? new AddDefaultConstructorFix(aClass, modifier) : null;
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createMethodParameterTypeFix(@NotNull PsiMethod method,
                                                                                   int index,
@@ -103,16 +113,19 @@
     return new MethodParameterFix(method, newType, index, fixWholeHierarchy);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createMakeClassInterfaceFix(@NotNull PsiClass aClass) {
     return new MakeClassInterfaceFix(aClass, true);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createMakeClassInterfaceFix(@NotNull PsiClass aClass, final boolean makeInterface) {
     return new MakeClassInterfaceFix(aClass, makeInterface);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createExtendsListFix(@NotNull PsiClass aClass,
                                                                           @NotNull PsiClassType typeToExtendFrom,
@@ -120,11 +133,13 @@
     return new ExtendsListFix(aClass, typeToExtendFrom, toAdd);
   }
 
+  @NotNull
   @Override
   public LocalQuickFixAndIntentionActionOnPsiElement createRemoveUnusedParameterFix(@NotNull PsiParameter parameter) {
     return new RemoveUnusedParameterFix(parameter);
   }
 
+  @NotNull
   @Override
   public IntentionAction createRemoveUnusedVariableFix(@NotNull PsiVariable variable) {
     return new RemoveUnusedVariableFix(variable);
@@ -142,8 +157,9 @@
     return CreateClassOrPackageFix.createFix(qualifiedName, context, createClass ? ClassKind.CLASS : ClassKind.INTERFACE, superClass);
   }
 
+  @NotNull
   @Override
-  public IntentionAction createCreateFieldOrPropertyFix(final PsiClass aClass, final String name, final PsiType type, final PropertyMemberType targetMember, final PsiAnnotation... annotations) {
+  public IntentionAction createCreateFieldOrPropertyFix(@NotNull final PsiClass aClass, @NotNull final String name, @NotNull final PsiType type, @NotNull final PropertyMemberType targetMember, @NotNull final PsiAnnotation... annotations) {
     return new CreateFieldOrPropertyFix(aClass, name, type, targetMember, annotations);
   }
 
diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java
index 866e2ce..c465975 100644
--- a/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java
+++ b/java/java-impl/src/com/intellij/ide/hierarchy/call/CallHierarchyNodeDescriptor.java
@@ -34,12 +34,13 @@
 import com.intellij.pom.Navigatable;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.jsp.jspJava.JspHolderMethod;
-import com.intellij.psi.jsp.JspFile;
 import com.intellij.psi.presentation.java.ClassPresentationUtil;
 import com.intellij.psi.util.PsiFormatUtil;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtilBase;
+import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.ui.LayeredIcon;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
@@ -146,8 +147,8 @@
         myHighlightedText.getEnding().addText(buffer.toString(), mainTextAttributes);
       }
     }
-    else if (JspPsiUtil.isInJspFile(enclosingElement) && enclosingElement instanceof PsiFile) {
-      final JspFile file = JspPsiUtil.getJspFile(enclosingElement);
+    else if (FileTypeUtils.isInServerPageFile(enclosingElement) && enclosingElement instanceof PsiFile) {
+      final PsiFile file = PsiUtilCore.getTemplateLanguageFile(enclosingElement);
       myHighlightedText.getEnding().addText(file.getName(), mainTextAttributes);
     }
     else {
@@ -156,7 +157,7 @@
     if (myUsageCount > 1) {
       myHighlightedText.getEnding().addText(IdeBundle.message("node.call.hierarchy.N.usages", myUsageCount), HierarchyNodeDescriptor.getUsageCountPrefixAttributes());
     }
-    if (!(JspPsiUtil.isInJspFile(enclosingElement) && enclosingElement instanceof PsiFile)) {
+    if (!(FileTypeUtils.isInServerPageFile(enclosingElement) && enclosingElement instanceof PsiFile)) {
       final PsiClass containingClass = enclosingElement instanceof PsiMethod
                                        ? ((PsiMethod)enclosingElement).getContainingClass()
                                        : (PsiClass)enclosingElement;
diff --git a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java
index 08ecb6a..6b1a322 100644
--- a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java
+++ b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java
@@ -93,7 +93,7 @@
   }
 
   public RunProfileState getState(@NotNull final Executor executor, @NotNull final ExecutionEnvironment env) throws ExecutionException {
-    return new MyJavaCommandLineState(myProject, myGenerationScope);
+    return new MyJavaCommandLineState(myProject, myGenerationScope, env);
   }
 
   public String getName() {
@@ -132,8 +132,8 @@
     private final Project myProject;
     @NonNls private static final String INDEX_HTML = "index.html";
 
-    public MyJavaCommandLineState(Project project, AnalysisScope generationOptions) {
-      super(null);
+    public MyJavaCommandLineState(Project project, AnalysisScope generationOptions, ExecutionEnvironment env) {
+      super(env);
       myGenerationOptions = generationOptions;
       myProject = project;
       addConsoleFilters(new RegexpFilter(project, "$FILE_PATH$:$LINE$:[^\\^]+\\^"),
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java
index 0fe403b..2822fcf 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaCodeStyleManagerImpl.java
@@ -38,6 +38,7 @@
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.ContainerUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -157,7 +158,7 @@
 
     Set<PsiImportStatementBase> allImports = new THashSet<PsiImportStatementBase>(Arrays.asList(imports));
     final Collection<PsiImportStatementBase> redundant;
-    if (JspPsiUtil.isInJspFile(file)) {
+    if (FileTypeUtils.isInServerPageFile(file)) {
       // remove only duplicate imports
       redundant = ContainerUtil.newIdentityTroveSet();
       ContainerUtil.addAll(redundant, imports);
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/CommentFormatter.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/CommentFormatter.java
index 624c537..aaf47cf 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/CommentFormatter.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/CommentFormatter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,6 +20,7 @@
 import com.intellij.lang.java.JavaLanguage;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.LanguageLevelProjectExtension;
 import com.intellij.openapi.util.text.LineTokenizer;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
@@ -45,7 +46,7 @@
 
   public CommentFormatter(@NotNull Project project) {
     mySettings = CodeStyleSettingsManager.getSettings(project);
-    myParser = new JDParser(mySettings);
+    myParser = new JDParser(mySettings, LanguageLevelProjectExtension.getInstance(project).getLanguageLevel());
     myProject = project;
   }
 
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java
index f4ba000..5dbc025 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/javadoc/JDParser.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,6 +17,7 @@
 
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.codeStyle.CodeStyleSettings;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -39,9 +40,11 @@
   private static final String SELF_CLOSED_P_TAG = "<p/>";
 
   private final CodeStyleSettings mySettings;
+  private final LanguageLevel myLanguageLevel;
 
-  public JDParser(@NotNull CodeStyleSettings settings) {
+  public JDParser(@NotNull CodeStyleSettings settings, @NotNull LanguageLevel languageLevel) {
     mySettings = settings;
+    myLanguageLevel = languageLevel;
   }
 
   private static final char lineSeparator = '\n';
@@ -514,7 +517,13 @@
         if (line.length() == 0 && !mySettings.JD_KEEP_EMPTY_LINES) continue;
         if (i != 0) sb.append(prefix);
         if (line.length() == 0 && mySettings.JD_P_AT_EMPTY_LINES && !insidePreTag) {
-          sb.append(SELF_CLOSED_P_TAG);
+          if (myLanguageLevel.isAtLeast(LanguageLevel.JDK_1_8)) {
+            //Self-closing elements are not allowed for javadoc tool from JDK8
+            sb.append(P_START_TAG);
+          }
+          else {
+            sb.append(SELF_CLOSED_P_TAG);
+          }
         }
         else {
           sb.append(line);
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PathListReferenceProvider.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PathListReferenceProvider.java
index b21c395..3685ef7 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PathListReferenceProvider.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/PathListReferenceProvider.java
@@ -16,22 +16,18 @@
 
 package com.intellij.psi.impl.source.resolve.reference.impl.providers;
 
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiReference;
-import com.intellij.psi.ElementManipulator;
-import com.intellij.psi.ElementManipulators;
-import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProviderBase;
+import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.util.text.CharFilter;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.psi.*;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.ProcessingContext;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.util.text.CharFilter;
-import com.intellij.openapi.util.TextRange;
 import org.jetbrains.annotations.NotNull;
 
 /**
  * @author davdeev
  */
-public class PathListReferenceProvider extends PsiReferenceProviderBase {
+public class PathListReferenceProvider extends PsiReferenceProvider {
 
   @Override
   @NotNull
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java
index 59e311a..d485130 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/injected/JavaConcatenationInjectorManager.java
@@ -159,7 +159,7 @@
       }
       if (result != null && result.getResult() != null) {
         for (Pair<Place, PsiFile> p : result.getResult()) {
-          ((MultiHostRegistrarImpl)registrar).addToResults(p.first, p.second);
+          ((MultiHostRegistrarImpl)registrar).addToResults(p.first, p.second, result);
         }
 
         if (data == null) {
diff --git a/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java b/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java
index 71a0c95..346ed4c 100644
--- a/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/anonymousToInner/AnonymousToInnerHandler.java
@@ -37,6 +37,7 @@
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.refactoring.util.classMembers.ElementNeedsThis;
 import com.intellij.util.IncorrectOperationException;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -102,7 +103,7 @@
       return;
     }
     PsiElement targetContainer = findTargetContainer(myAnonClass);
-    if (JspPsiUtil.isInJspFile(targetContainer) && targetContainer instanceof PsiFile) {
+    if (FileTypeUtils.isInServerPageFile(targetContainer) && targetContainer instanceof PsiFile) {
       String message = RefactoringBundle.message("error.not.supported.for.jsp", REFACTORING_NAME);
       showErrorMessage(editor, message);
       return;
@@ -208,7 +209,7 @@
       if (element instanceof PsiNewExpression) {
         final PsiNewExpression newExpression = (PsiNewExpression)element;
         if (newExpression.getAnonymousClass() != null) {
-          return newExpression.getAnonymousClass();          
+          return newExpression.getAnonymousClass();
         }
       }
       element = element.getParent();
diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java
index d186ef9..1aac71d 100644
--- a/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/introduceField/BaseExpressionToFieldHandler.java
@@ -67,6 +67,7 @@
 import com.intellij.refactoring.util.occurrences.OccurrenceManager;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.VisibilityUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -158,7 +159,7 @@
                                            final Project project,
                                            PsiType tempType) {
     if (myParentClass == null) {
-      if (JspPsiUtil.isInJspFile(file)) {
+      if (FileTypeUtils.isInServerPageFile(file)) {
         CommonRefactoringUtil.showErrorHint(project, editor, RefactoringBundle.message("error.not.supported.for.jsp", getRefactoringName()),
                                             getRefactoringName(), getHelpID());
         return true;
diff --git a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java
index 1f9661d..08a6bf6 100644
--- a/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/introduceField/LocalToFieldHandler.java
@@ -38,6 +38,7 @@
 import com.intellij.refactoring.util.RefactoringUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.VisibilityUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 
@@ -69,7 +70,7 @@
       if (parent instanceof PsiClass && !(myIsConstant && parent instanceof PsiAnonymousClass)) {
         classes.add((PsiClass)parent);
       }
-      if (parent instanceof PsiFile && JspPsiUtil.isInJspFile(parent)) {
+      if (parent instanceof PsiFile && FileTypeUtils.isInServerPageFile(parent)) {
         String message = RefactoringBundle.message("error.not.supported.for.jsp", REFACTORING_NAME);
         CommonRefactoringUtil.showErrorHint(myProject, editor, message, REFACTORING_NAME, HelpID.LOCAL_TO_FIELD);
         return false;
diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java
index 7e3838a..930eafc 100644
--- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java
+++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/JavaMoveDirectoryWithClassesHelper.java
@@ -10,6 +10,7 @@
 import com.intellij.usageView.UsageInfo;
 import com.intellij.util.Function;
 import com.intellij.util.containers.MultiMap;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 
 import java.util.*;
 
@@ -76,8 +77,8 @@
     if (!(file instanceof PsiClassOwner)) {
       return false;
     }
-    
-    if (!JspPsiUtil.isInJspFile(file)) {
+
+    if (!FileTypeUtils.isInServerPageFile(file)) {
       return false;
     }
 
diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java
index 2982483..5f3471f 100644
--- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java
+++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesUtil.java
@@ -38,6 +38,7 @@
 import com.intellij.usageView.UsageInfo;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.HashMap;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.Nullable;
 
 import java.io.File;
@@ -231,7 +232,7 @@
     if (!moveDestination.equals(file.getContainingDirectory())) {
       LOG.assertTrue(file.getVirtualFile() != null, aClass);
       MoveFilesOrDirectoriesUtil.doMoveFile(file, moveDestination);
-      if (file instanceof PsiClassOwner && newPackage != null && !JspPsiUtil.isInJspFile(file)) {
+      if (file instanceof PsiClassOwner && newPackage != null && !FileTypeUtils.isInServerPageFile(file)) {
         // Do not rely on class instance identity retention after setPackageName (Scala)
         String aClassName = aClass.getName();
         ((PsiClassOwner)file).setPackageName(newPackage.getQualifiedName());
@@ -304,7 +305,7 @@
     }
     return directory;
   }
-  
+
   public static VirtualFile chooseSourceRoot(final PackageWrapper targetPackage,
                                              final VirtualFile[] contentSourceRoots,
                                              final PsiDirectory initialDirectory) {
diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveJavaFileHandler.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveJavaFileHandler.java
index de994d9..3134f39 100644
--- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveJavaFileHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveJavaFileHandler.java
@@ -29,6 +29,7 @@
 import com.intellij.refactoring.util.MoveRenameUsageInfo;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.util.IncorrectOperationException;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -41,7 +42,7 @@
   @Override
   public boolean canProcessElement(PsiFile element) {
     return element instanceof PsiJavaFile &&
-           !JspPsiUtil.isInJspFile(element) &&
+           !FileTypeUtils.isInServerPageFile(element) &&
            !ProjectRootsUtil.isOutsideSourceRoot(element) &&
            !(element instanceof PsiCompiledElement);
   }
diff --git a/java/java-impl/src/com/intellij/refactoring/rename/JavaVetoRenameCondition.java b/java/java-impl/src/com/intellij/refactoring/rename/JavaVetoRenameCondition.java
index 40ad255..72231dc 100644
--- a/java/java-impl/src/com/intellij/refactoring/rename/JavaVetoRenameCondition.java
+++ b/java/java-impl/src/com/intellij/refactoring/rename/JavaVetoRenameCondition.java
@@ -20,12 +20,13 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.PsiJavaFile;
-import com.intellij.psi.JspPsiUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 
 public class JavaVetoRenameCondition implements Condition<PsiElement> {
+  @Override
   public boolean value(final PsiElement element) {
     return element instanceof PsiJavaFile &&
-           !JspPsiUtil.isInJspFile(element) &&
+           !FileTypeUtils.isInServerPageFile(element) &&
            !ProjectRootsUtil.isOutsideSourceRoot((PsiFile)element) &&
            ((PsiJavaFile) element).getClasses().length > 0;
   }
diff --git a/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java b/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java
index 7f13923..0dfd748 100644
--- a/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java
+++ b/java/java-impl/src/com/intellij/refactoring/util/ConflictsUtil.java
@@ -24,6 +24,8 @@
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.resolve.FileContextUtil;
 import com.intellij.psi.search.searches.ClassInheritorsSearch;
+import com.intellij.psi.util.MethodSignature;
+import com.intellij.psi.util.MethodSignatureUtil;
 import com.intellij.psi.util.PsiFormatUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.refactoring.RefactoringBundle;
@@ -59,9 +61,19 @@
                                           final PsiMethod prototype,
                                           final MultiMap<PsiElement,String> conflicts) {
     if (prototype == null) return;
-    final String protoMethodInfo = getMethodPrototypeString(prototype);
+    String protoMethodInfo = getMethodPrototypeString(prototype);
 
     PsiMethod method = aClass != null ? aClass.findMethodBySignature(prototype, true) : null;
+    if (method == null && aClass != null) {
+      final MethodSignature signature = prototype.getSignature(PsiSubstitutor.EMPTY);
+      for (PsiMethod classMethod : aClass.getMethods()) {
+        if (MethodSignatureUtil.areSignaturesErasureEqual(signature, classMethod.getSignature(PsiSubstitutor.EMPTY))) {
+          method = classMethod;
+          protoMethodInfo = "with same erasure";
+          break;
+        }
+      }
+    }
 
     if (method != null && method != refactoredMethod) {
       if (aClass.equals(method.getContainingClass())) {
@@ -69,7 +81,7 @@
                                   RefactoringBundle.message("current.class") :
                                   RefactoringUIUtil.getDescription(aClass, false);
         conflicts.putValue(method, RefactoringBundle.message("method.0.is.already.defined.in.the.1",
-                                                getMethodPrototypeString(prototype),
+                                                protoMethodInfo,
                                                 classDescr));
       }
       else { // method somewhere in base class
diff --git a/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java b/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java
index 8cd8471..b4f6127 100644
--- a/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java
+++ b/java/java-impl/src/com/intellij/usages/impl/rules/ClassGroupingRule.java
@@ -33,6 +33,7 @@
 import com.intellij.usages.UsageView;
 import com.intellij.usages.rules.PsiElementUsage;
 import com.intellij.usages.rules.UsageGroupingRule;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
@@ -79,7 +80,7 @@
     }
     else {
       // skip JspClass synthetic classes.
-      if (containingClass.getParent() instanceof PsiFile && JspPsiUtil.isInJspFile(containingClass)) {
+      if (containingClass.getParent() instanceof PsiFile && FileTypeUtils.isInServerPageFile(containingClass)) {
         containingClass = null;
       }
     }
diff --git a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java
index ff3543a3..4132f23 100644
--- a/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/GenericsUtil.java
@@ -239,24 +239,73 @@
     supers.add(classToAdd);
   }
 
-  public static boolean isTypeArgumentsApplicable(PsiTypeParameter[] typeParams, PsiSubstitutor substitutor, final PsiElement context) {
+  public static boolean isTypeArgumentsApplicable(final PsiTypeParameter[] typeParams,
+                                                  final PsiSubstitutor substitutor,
+                                                  final PsiElement context) {
+    return isTypeArgumentsApplicable(typeParams, substitutor, context, true);
+  }
+
+  public static boolean isTypeArgumentsApplicable(final PsiTypeParameter[] typeParams,
+                                                  final PsiSubstitutor substitutor,
+                                                  final PsiElement context,
+                                                  final boolean allowUncheckedConversion) {
+    return findTypeParameterWithBoundError(typeParams, substitutor, context, allowUncheckedConversion) == null;
+  }
+
+  public static Pair<PsiTypeParameter, PsiType> findTypeParameterWithBoundError(final PsiTypeParameter[] typeParams,
+                                                                                final PsiSubstitutor substitutor,
+                                                                                final PsiElement context,
+                                                                                final boolean allowUncheckedConversion) {
     nextTypeParam:
     for (PsiTypeParameter typeParameter : typeParams) {
       PsiType substituted = substitutor.substitute(typeParameter);
-      if (substituted == null) return true;
+      if (substituted == null) return null;
       substituted = PsiUtil.captureToplevelWildcards(substituted, context);
 
       PsiClassType[] extendsTypes = typeParameter.getExtendsListTypes();
       for (PsiClassType type : extendsTypes) {
         PsiType extendsType = substitutor.substitute(type);
-        if (extendsType.isAssignableFrom(substituted)) {
-          continue nextTypeParam;
+        if (substituted instanceof PsiWildcardType) {
+          if (((PsiWildcardType)substituted).isSuper()) {
+            continue;
+          }
+          final PsiType extendsBound = ((PsiWildcardType)substituted).getExtendsBound();
+          if (Comparing.equal(TypeConversionUtil.erasure(extendsType), TypeConversionUtil.erasure(extendsBound))) {
+            if (extendsBound instanceof PsiClassType) {
+              if (acceptExtendsBound((PsiClassType)extendsBound, 0)) continue;
+            } else if (extendsBound instanceof PsiIntersectionType) {
+              for (PsiType psiType : ((PsiIntersectionType)extendsBound).getConjuncts()) {
+                if (psiType instanceof PsiClassType) {
+                  if (acceptExtendsBound((PsiClassType)psiType, 0)) continue nextTypeParam;
+                }
+              }
+            }
+          }
+        }
+        if (extendsType != null && !TypeConversionUtil.isAssignable(extendsType, substituted, allowUncheckedConversion)) {
+          return Pair.create(typeParameter, extendsType);
         }
       }
-      if (extendsTypes.length > 0) return false;
     }
+    return null;
+  }
 
-    return true;
+  private static boolean acceptExtendsBound(PsiClassType extendsBound, int depth) {
+    PsiType[] parameters = extendsBound.getParameters();
+    if (parameters.length == 1) {
+      PsiType argType = parameters[0];
+      if (argType instanceof PsiCapturedWildcardType && depth == 0) {
+        argType = ((PsiCapturedWildcardType)argType).getWildcard();
+      }
+      if (argType instanceof PsiWildcardType) {
+        if (!((PsiWildcardType)argType).isBounded()) return true;
+        final PsiType bound = ((PsiWildcardType)argType).getExtendsBound();
+        if (bound instanceof PsiClassType && TypeConversionUtil.erasure(bound).equals(TypeConversionUtil.erasure(extendsBound))) {
+          return acceptExtendsBound((PsiClassType)bound, depth + 1);
+        }
+      }
+    }
+    return false;
   }
 
   public static boolean isFromExternalTypeLanguage(@NotNull PsiType type) {
diff --git a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
index 94f4cd30..299575e 100644
--- a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
+++ b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
@@ -94,6 +94,10 @@
     return myApplicabilityLevel;
   }
 
+  public PsiSubstitutor getSiteSubstitutor() {
+    return super.getSubstitutor();
+  }
+  
   @Override
   public PsiSubstitutor getSubstitutor() {
     if (myCalcedSubstitutor == null) {
diff --git a/java/openapi/src/com/intellij/psi/util/EnclosingLoopMatcherExpression.java b/java/java-psi-api/src/com/intellij/psi/util/EnclosingLoopMatcherExpression.java
similarity index 100%
rename from java/openapi/src/com/intellij/psi/util/EnclosingLoopMatcherExpression.java
rename to java/java-psi-api/src/com/intellij/psi/util/EnclosingLoopMatcherExpression.java
diff --git a/java/openapi/src/com/intellij/psi/util/EnclosingLoopOrSwitchMatcherExpression.java b/java/java-psi-api/src/com/intellij/psi/util/EnclosingLoopOrSwitchMatcherExpression.java
similarity index 100%
rename from java/openapi/src/com/intellij/psi/util/EnclosingLoopOrSwitchMatcherExpression.java
rename to java/java-psi-api/src/com/intellij/psi/util/EnclosingLoopOrSwitchMatcherExpression.java
diff --git a/java/openapi/src/com/intellij/psi/util/JavaMatchers.java b/java/java-psi-api/src/com/intellij/psi/util/JavaMatchers.java
similarity index 100%
rename from java/openapi/src/com/intellij/psi/util/JavaMatchers.java
rename to java/java-psi-api/src/com/intellij/psi/util/JavaMatchers.java
diff --git a/java/java-psi-api/src/com/intellij/psi/util/MethodSignatureUtil.java b/java/java-psi-api/src/com/intellij/psi/util/MethodSignatureUtil.java
index 077dc80..b514fa2 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/MethodSignatureUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/MethodSignatureUtil.java
@@ -58,7 +58,7 @@
       }
     };
 
-  private static boolean areErasedParametersEqual(@NotNull MethodSignature method1, @NotNull MethodSignature method2) {
+  public static boolean areErasedParametersEqual(@NotNull MethodSignature method1, @NotNull MethodSignature method2) {
     PsiType[] erased1 = method1 instanceof MethodSignatureBase
                         ? ((MethodSignatureBase)method1).getErasedParameterTypes() : calcErasedParameterTypes(method1);
     PsiType[] erased2 = method2 instanceof MethodSignatureBase
diff --git a/java/openapi/src/com/intellij/psi/util/PropertyMemberType.java b/java/java-psi-api/src/com/intellij/psi/util/PropertyMemberType.java
similarity index 100%
rename from java/openapi/src/com/intellij/psi/util/PropertyMemberType.java
rename to java/java-psi-api/src/com/intellij/psi/util/PropertyMemberType.java
diff --git a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java
index 020881b..642d855 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/PsiUtil.java
@@ -466,8 +466,20 @@
   }
 
   @MethodCandidateInfo.ApplicabilityLevelConstant
-  public static int getApplicabilityLevel(@NotNull final PsiMethod method, @NotNull final PsiSubstitutor substitutorForMethod, @NotNull final PsiType[] args,
-                                           @NotNull final LanguageLevel languageLevel) {
+  public static int getApplicabilityLevel(@NotNull final PsiMethod method,
+                                          @NotNull final PsiSubstitutor substitutorForMethod,
+                                          @NotNull final PsiType[] args,
+                                          @NotNull final LanguageLevel languageLevel) {
+    return getApplicabilityLevel(method, substitutorForMethod, args, languageLevel, true, true);
+  }
+
+  @MethodCandidateInfo.ApplicabilityLevelConstant
+  public static int getApplicabilityLevel(@NotNull final PsiMethod method,
+                                          @NotNull final PsiSubstitutor substitutorForMethod,
+                                          @NotNull final PsiType[] args,
+                                          @NotNull final LanguageLevel languageLevel,
+                                                   final boolean allowUncheckedConversion,
+                                                   final boolean checkVarargs) {
     final PsiParameter[] parms = method.getParameterList().getParameters();
     if (args.length < parms.length - 1) return ApplicabilityLevel.NOT_APPLICABLE;
 
@@ -479,7 +491,7 @@
       PsiType parmType = getParameterType(parms[parms.length - 1], languageLevel, substitutorForMethod);
       PsiType argType = args[args.length - 1];
       if (argType == null) return ApplicabilityLevel.NOT_APPLICABLE;
-      if (TypeConversionUtil.isAssignable(parmType, argType)) return ApplicabilityLevel.FIXED_ARITY;
+      if (TypeConversionUtil.isAssignable(parmType, argType, allowUncheckedConversion)) return ApplicabilityLevel.FIXED_ARITY;
 
       if (isRaw) {
         final PsiType erasedParamType = TypeConversionUtil.erasure(parmType);
@@ -491,7 +503,7 @@
       }
     }
 
-    if (method.isVarArgs() && languageLevel.compareTo(LanguageLevel.JDK_1_5) >= 0) {
+    if (checkVarargs && method.isVarArgs() && languageLevel.compareTo(LanguageLevel.JDK_1_5) >= 0) {
       if (args.length < parms.length) return ApplicabilityLevel.VARARGS;
       PsiParameter lastParameter = parms[parms.length - 1];
       if (!lastParameter.isVarArgs()) return ApplicabilityLevel.NOT_APPLICABLE;
diff --git a/java/java-impl/src/com/intellij/codeInsight/JavaContainerProvider.java b/java/java-psi-impl/src/com/intellij/codeInsight/JavaContainerProvider.java
similarity index 100%
rename from java/java-impl/src/com/intellij/codeInsight/JavaContainerProvider.java
rename to java/java-psi-impl/src/com/intellij/codeInsight/JavaContainerProvider.java
diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java b/java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java
similarity index 100%
rename from java/java-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java
rename to java/java-psi-impl/src/com/intellij/codeInsight/highlighting/JavaHighlightUsagesDescriptionProvider.java
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java
index d24bfd9..bbe39b3 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/PsiResolveHelperImpl.java
@@ -526,6 +526,44 @@
         substitutor = substitutor.put(typeParameter, substitution);
       }
     }
+    for (int i = 0; i < typeParameters.length; i++) {
+      PsiTypeParameter typeParameter = typeParameters[i];
+      if (!substitutor.getSubstitutionMap().containsKey(typeParameter)) {
+        PsiType substitutionFromBounds = PsiType.NULL;
+        OtherParameters:
+        for (int j = 0; j < typeParameters.length; j++) {
+          if (i != j) {
+            PsiTypeParameter other = typeParameters[j];
+            final PsiType otherSubstitution = substitutor.substitute(other);
+            if (otherSubstitution == null) continue;
+            final PsiClassType[] bounds = other.getExtendsListTypes();
+            for (PsiClassType bound : bounds) {
+              final PsiType substitutedBound = substitutor.substitute(bound);
+              final Pair<PsiType, ConstraintType> currentConstraint =
+                getSubstitutionForTypeParameterConstraint(typeParameter, substitutedBound, otherSubstitution, true, languageLevel);
+              if (currentConstraint == null) continue;
+              final PsiType currentSubstitution = currentConstraint.getFirst();
+              final ConstraintType currentConstraintType = currentConstraint.getSecond();
+              if (currentConstraintType == ConstraintType.EQUALS) {
+                substitutionFromBounds = currentSubstitution;
+                break OtherParameters;
+              }
+              else if (currentConstraintType == ConstraintType.SUPERTYPE) {
+                if (PsiType.NULL.equals(substitutionFromBounds)) {
+                  substitutionFromBounds = currentSubstitution;
+                }
+                else {
+                  substitutionFromBounds = GenericsUtil.getLeastUpperBound(substitutionFromBounds, currentSubstitution, myManager);
+                }
+              }
+            }
+          }
+        }
+        if (substitutionFromBounds != PsiType.NULL) {
+          substitutor = substitutor.put(typeParameter, substitutionFromBounds);
+        }
+      }
+    }
     return substitutor;
   }
 
@@ -534,10 +572,6 @@
                                                               final boolean captureWildcard) {
     if (arg instanceof PsiWildcardType && !captureWildcard) return FAILED_INFERENCE;
     if (arg != PsiType.NULL) {
-      if (arg instanceof PsiWildcardType) {
-        final PsiType bound = ((PsiWildcardType)arg).getBound();
-        if (bound instanceof PsiClassType && ((PsiClassType)bound).isRaw()) return Pair.create(null, constraintType);
-      }
       return new Pair<PsiType, ConstraintType>(arg, constraintType);
     }
     return null;
@@ -1163,15 +1197,18 @@
           }
         }
 
-        PsiClassType[] superTypes = typeParameter.getSuperTypes();
+        PsiType[] superTypes = typeParameter.getSuperTypes();
         if (superTypes.length == 0) return null;
-        PsiType superType = substitutor.substitute(superTypes[0]);
-        if (superType instanceof PsiClassType && ((PsiClassType)superType).isRaw()) {
-          superType = TypeConversionUtil.erasure(superType);
+        for (int i = 0; i < superTypes.length; i++) {
+          PsiType superType = substitutor.substitute(superTypes[i]);
+          if (superType instanceof PsiClassType && ((PsiClassType)superType).isRaw()) {
+            superType = TypeConversionUtil.erasure(superType);
+          }
+          if (superType == null) superType = PsiType.getJavaLangObject(myManager, scope);
+          if (superType == null) return null;
+          superTypes[i] = superType;
         }
-        if (superType == null) superType = PsiType.getJavaLangObject(myManager, scope);
-        if (superType == null) return null;
-        return policy.getInferredTypeWithNoConstraint(myManager, superType);
+        return policy.getInferredTypeWithNoConstraint(myManager, PsiIntersectionType.createIntersection(superTypes));
       }
       return null;
     }
diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java
index 4e6fa6c..0f54e49 100644
--- a/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java
+++ b/java/java-psi-impl/src/com/intellij/psi/scope/conflictResolvers/JavaMethodsConflictResolver.java
@@ -33,9 +33,11 @@
 import gnu.trove.THashSet;
 import gnu.trove.TIntArrayList;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
-import java.util.*;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 /**
  * Created by IntelliJ IDEA.
@@ -71,7 +73,7 @@
     boolean atLeastOneMatch = checkParametersNumber(conflicts, myActualParameterTypes.length, true);
     if (conflicts.size() == 1) return conflicts.get(0);
 
-    checkSameSignatures(conflicts, myLanguageLevel);
+    checkSameSignatures(conflicts);
     if (conflicts.size() == 1) return conflicts.get(0);
 
     checkAccessStaticLevels(conflicts, true);
@@ -193,7 +195,7 @@
     }
   }
 
-  private void checkSameSignatures(@NotNull List<CandidateInfo> conflicts, @NotNull LanguageLevel languageLevel) {
+  private void checkSameSignatures(@NotNull List<CandidateInfo> conflicts) {
     // candidates should go in order of class hierarchy traversal
     // in order for this to work
     Map<MethodSignature, CandidateInfo> signatures = new THashMap<MethodSignature, CandidateInfo>(conflicts.size());
@@ -307,14 +309,17 @@
             if (MethodSignatureUtil.areSignaturesEqual(existingMethod.getSignature(eSubstitutor), method.getSignature(cSubstitutor))) {
               final PsiType returnType = eSubstitutor.substitute(existingMethod.getReturnType());
               final PsiType returnType1 = cSubstitutor.substitute(method.getReturnType());
-              if (returnType != null && returnType1 != null && !returnType1.equals(returnType) && TypeConversionUtil.isAssignable(returnType, returnType1, false)) {
-                if (class1.isInterface() && !existingClass.isInterface()) continue;
-                conflicts.remove(existing);
-              } else {
-                conflicts.remove(i);
+              if (returnType != null && returnType1 != null && !returnType1.equals(returnType)) {
+                if (TypeConversionUtil.isAssignable(returnType, returnType1, false)) {
+                  if (class1.isInterface() && !existingClass.isInterface()) continue;
+                  conflicts.remove(existing);
+                } else {
+                  if (!TypeConversionUtil.isAssignable(returnType1, returnType, false)) continue;
+                  conflicts.remove(i);
+                }
+                i--;
+                break;
               }
-              i--;
-              break;
             }
           }
         }
@@ -420,42 +425,6 @@
     NEITHER
   }
 
-  private static Specifics checkSubtyping(PsiType type1, PsiType type2, PsiMethod method1, PsiMethod method2) {
-    return checkSubtyping(type1, type2, method1, method2, true);
-  }
-
-  @Nullable
-  private static Specifics checkSubtyping(PsiType type1,
-                                          PsiType type2,
-                                          PsiMethod method1,
-                                          PsiMethod method2,
-                                          boolean boxingHappening) {
-    boolean noBoxing = boxingHappening || type1 instanceof PsiPrimitiveType == type2 instanceof PsiPrimitiveType;
-    boolean allowUncheckedConversion =
-      !method1.hasModifierProperty(PsiModifier.STATIC) && !method2.hasModifierProperty(PsiModifier.STATIC);
-
-    if (!allowUncheckedConversion) {
-      final PsiClass containingClass1 = method1.getContainingClass();
-      final PsiClass containingClass2 = method2.getContainingClass();
-      if (containingClass1 != null && containingClass2 != null) {
-        allowUncheckedConversion = !containingClass1.isInheritor(containingClass2, true) &&
-                                   !containingClass2.isInheritor(containingClass1, true);
-      }
-    }
-
-    final boolean assignable2From1 = noBoxing && TypeConversionUtil.isAssignable(type2, type1, allowUncheckedConversion);
-    final boolean assignable1From2 = noBoxing && TypeConversionUtil.isAssignable(type1, type2, allowUncheckedConversion);
-    if (assignable1From2 || assignable2From1) {
-      if (assignable1From2 && assignable2From1) {
-        return null;
-      }
-
-      return assignable1From2 ? Specifics.SECOND : Specifics.FIRST;
-    }
-
-    return allowUncheckedConversion ? Specifics.NEITHER : null;
-  }
-
   private static boolean isBoxingHappened(PsiType argType, PsiType parameterType, @NotNull LanguageLevel languageLevel) {
     if (argType == null) return parameterType instanceof PsiPrimitiveType;
     if (parameterType instanceof PsiClassType) {
@@ -485,12 +454,14 @@
     final int max = Math.max(params1.length, params2.length);
     PsiType[] types1 = new PsiType[max];
     PsiType[] types2 = new PsiType[max];
+    final boolean varargsPosition = applicabilityLevel == MethodCandidateInfo.ApplicabilityLevel.VARARGS;
     for (int i = 0; i < max; i++) {
       ProgressManager.checkCanceled();
       PsiType type1 = params1.length > 0 ? params1[Math.min(i, params1.length - 1)].getType() : null;
       PsiType type2 = params2.length > 0 ? params2[Math.min(i, params2.length - 1)].getType() : null;
-      if (applicabilityLevel == MethodCandidateInfo.ApplicabilityLevel.VARARGS) {
+      if (varargsPosition) {
         if (type1 instanceof PsiEllipsisType && type2 instanceof PsiEllipsisType &&
+            params1.length == params2.length &&
             (!JavaVersionService.getInstance().isAtLeast(class1, JavaSdkVersion.JDK_1_7) || ((PsiArrayType)type1).getComponentType().equalsToText(CommonClassNames.JAVA_LANG_OBJECT) || ((PsiArrayType)type2).getComponentType().equalsToText(CommonClassNames.JAVA_LANG_OBJECT))) {
           type1 = ((PsiEllipsisType)type1).toArrayType();
           type2 = ((PsiEllipsisType)type2).toArrayType();
@@ -505,6 +476,7 @@
       types2[i] = type2;
     }
 
+    boolean sameBoxing = true;
     int[] boxingHappened = new int[2];
     for (int i = 0; i < types1.length; i++) {
       ProgressManager.checkCanceled();
@@ -512,231 +484,125 @@
       PsiType type2 = classSubstitutor2.substitute(types2[i]);
       PsiType argType = i < myActualParameterTypes.length ? myActualParameterTypes[i] : null;
 
-      boxingHappened[0] += isBoxingHappened(argType, type1, languageLevel) ? 1 : 0;
-      boxingHappened[1] += isBoxingHappened(argType, type2, languageLevel) ? 1 : 0;
+      boolean boxingInFirst = false;
+      if (isBoxingHappened(argType, type1, languageLevel)) {
+        boxingHappened[0] += 1;
+        boxingInFirst = true;
+      }
+
+      boolean boxingInSecond = false;
+      if (isBoxingHappened(argType, type2, languageLevel)) {
+        boxingHappened[1] += 1;
+        boxingInSecond = true;
+      }
+      sameBoxing &= boxingInFirst == boxingInSecond;
     }
     if (boxingHappened[0] == 0 && boxingHappened[1] > 0) return Specifics.FIRST;
     if (boxingHappened[0] > 0 && boxingHappened[1] == 0) return Specifics.SECOND;
 
-    Specifics isMoreSpecific = null;
-    for (int i = 0; i < types1.length; i++) {
-      ProgressManager.checkCanceled();
-      Specifics specifics = checkSubstitutorSpecific(method1, method2, classSubstitutor1, classSubstitutor2, types1[i], types2[i]);
-      if (specifics == null) {
-        PsiSubstitutor methodSubstitutor1 = PsiSubstitutor.EMPTY;
-        PsiSubstitutor methodSubstitutor2 = PsiSubstitutor.EMPTY;
-        if (typeParameters1.length == 0 || typeParameters2.length == 0) {
-          if (typeParameters1.length > 0) {
-            final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(myArgumentsList.getProject()).getResolveHelper();
-            methodSubstitutor1 = calculateMethodSubstitutor(typeParameters1, types1, types2, resolveHelper, languageLevel);
-          }
-          else if (typeParameters2.length > 0) {
-            final PsiResolveHelper resolveHelper = JavaPsiFacade.getInstance(myArgumentsList.getProject()).getResolveHelper();
-            methodSubstitutor2 = calculateMethodSubstitutor(typeParameters2, types2, types1, resolveHelper, languageLevel);
-          }
+    if (sameBoxing) {
+      final PsiSubstitutor siteSubstitutor1 = ((MethodCandidateInfo)info1).getSiteSubstitutor();
+      final PsiSubstitutor siteSubstitutor2 = ((MethodCandidateInfo)info2).getSiteSubstitutor();
+
+      final PsiType[] types2AtSite = typesAtSite(types2, siteSubstitutor2);
+      final PsiType[] types1AtSite = typesAtSite(types1, siteSubstitutor1);
+
+      final PsiSubstitutor methodSubstitutor1 = calculateMethodSubstitutor(typeParameters1, method1, siteSubstitutor1, types1, types2AtSite, languageLevel);
+      final PsiSubstitutor methodSubstitutor2 = calculateMethodSubstitutor(typeParameters2, method2, siteSubstitutor2, types2, types1AtSite, languageLevel);
+
+      final boolean applicable12 = isApplicableTo(types2AtSite, method1, typeParameters1, languageLevel, methodSubstitutor1, varargsPosition);
+      final boolean applicable21 = isApplicableTo(types1AtSite, method2, typeParameters2, languageLevel, methodSubstitutor2, varargsPosition);
+
+      if (applicable12 || applicable21) {
+
+        if (applicable12 && !applicable21) return Specifics.SECOND;
+        if (applicable21 && !applicable12) return Specifics.FIRST;
+
+        final boolean abstract1 = method1.hasModifierProperty(PsiModifier.ABSTRACT);
+        final boolean abstract2 = method2.hasModifierProperty(PsiModifier.ABSTRACT);
+        if (abstract1 && !abstract2) {
+          return Specifics.SECOND;
         }
-        else {
-          PsiElementFactory factory = JavaPsiFacade.getInstance(myArgumentsList.getProject()).getElementFactory();
-          methodSubstitutor1 = factory.createRawSubstitutor(PsiSubstitutor.EMPTY, typeParameters1);
-          methodSubstitutor2 = factory.createRawSubstitutor(PsiSubstitutor.EMPTY, typeParameters2);
-        }
-        PsiType type1 = classSubstitutor1.substitute(methodSubstitutor1.substitute(types1[i]));
-        PsiType type2 = classSubstitutor2.substitute(methodSubstitutor2.substitute(types2[i]));
-        specifics = type1 == null || type2 == null ? null : checkSubtyping(type1, type2, method1, method2, boxingHappened[0] == 0 || boxingHappened[1] == 0);
-        if (specifics == null) {
-          continue;
+        if (abstract2 && !abstract1) {
+          return Specifics.FIRST;
         }
       }
-
-      switch (specifics) {
-        case FIRST:
-          if (isMoreSpecific == Specifics.SECOND) return Specifics.NEITHER;
-          isMoreSpecific = specifics;
-          break;
-        case SECOND:
-          if (isMoreSpecific == Specifics.FIRST) return Specifics.NEITHER;
-          isMoreSpecific = specifics;
-          break;
-        case NEITHER:
-          return Specifics.NEITHER;
+    } 
+    else if (varargsPosition) {
+      final PsiType lastParamType1 = classSubstitutor1.substitute(types1[types1.length - 1]);
+      final PsiType lastParamType2 = classSubstitutor2.substitute(types2[types1.length - 1]);
+      final boolean assignable1 = TypeConversionUtil.isAssignable(lastParamType2, lastParamType1);
+      final boolean assignable2 = TypeConversionUtil.isAssignable(lastParamType1, lastParamType2);
+      if (assignable1 && !assignable2) {
+        return Specifics.FIRST;
+      }
+      if (assignable2 && !assignable1) {
+        return Specifics.SECOND;
       }
     }
 
-    if (isMoreSpecific == null && class1 != class2) {
+    if (class1 != class2) {
       if (class2.isInheritor(class1, true) || class1.isInterface() && !class2.isInterface()) {
         if (MethodSignatureUtil.isSubsignature(method1.getSignature(info1.getSubstitutor()), method2.getSignature(info2.getSubstitutor()))) {
-          isMoreSpecific = Specifics.SECOND;
+          return Specifics.SECOND;
         }
         else if (method1.hasModifierProperty(PsiModifier.STATIC) && method2.hasModifierProperty(PsiModifier.STATIC) && boxingHappened[0] == 0) {
-          isMoreSpecific = Specifics.SECOND;
+          return Specifics.SECOND;
         }
       }
       else if (class1.isInheritor(class2, true) || class2.isInterface()) {
-        if (MethodSignatureUtil.isSubsignature(method2.getSignature(info2.getSubstitutor()), method1.getSignature(info1.getSubstitutor()))) {
-          isMoreSpecific = Specifics.FIRST;
+        if (MethodSignatureUtil.areErasedParametersEqual(method1.getSignature(PsiSubstitutor.EMPTY), method2.getSignature(PsiSubstitutor.EMPTY)) && 
+            MethodSignatureUtil.isSubsignature(method2.getSignature(info2.getSubstitutor()), method1.getSignature(info1.getSubstitutor()))) {
+          return Specifics.FIRST;
         }
         else if (method1.hasModifierProperty(PsiModifier.STATIC) && method2.hasModifierProperty(PsiModifier.STATIC) && boxingHappened[0] == 0) {
-          isMoreSpecific = Specifics.FIRST;
+          return Specifics.FIRST;
         }
       }
     }
-    if (isMoreSpecific == null) {
-      if (!JavaVersionService.getInstance().isAtLeast(myArgumentsList, JavaSdkVersion.JDK_1_7) ||
-          !MethodSignatureUtil.areParametersErasureEqual(method1, method2) ||
-           InheritanceUtil.isInheritorOrSelf(class1, class2, true) ||
-           InheritanceUtil.isInheritorOrSelf(class2, class1, true)) {
-        if (typeParameters1.length < typeParameters2.length) return Specifics.FIRST;
-        if (typeParameters1.length > typeParameters2.length) return Specifics.SECOND;
-      }
-      return Specifics.NEITHER;
+
+    final boolean raw1 = PsiUtil.isRawSubstitutor(method1, classSubstitutor1);
+    final boolean raw2 = PsiUtil.isRawSubstitutor(method2, classSubstitutor2);
+    if (raw1 ^ raw2) {
+      return raw1 ? Specifics.SECOND : Specifics.FIRST;
     }
 
-    return isMoreSpecific;
+    return Specifics.NEITHER;
   }
 
-  @Nullable
-  private static Specifics checkSubstitutorSpecific(PsiMethod method1,
-                                                    PsiMethod method2,
-                                                    PsiSubstitutor classSubstitutor1,
-                                                    PsiSubstitutor classSubstitutor2,
-                                                    PsiType type1,
-                                                    PsiType type2) {
-    final PsiClass aClass1 = PsiUtil.resolveClassInType(type1);
-    final PsiClass aClass2 = PsiUtil.resolveClassInType(type2);
-    if (aClass1 instanceof PsiTypeParameter && aClass2 instanceof PsiTypeParameter) {
-      return checkTypeParams(method1, method2, classSubstitutor1, classSubstitutor2, type1, type2, (PsiTypeParameter)aClass1, (PsiTypeParameter)aClass2);
+  private boolean isApplicableTo(PsiType[] argTypes,
+                                 PsiMethod method,
+                                 PsiTypeParameter[] typeParameters,
+                                 LanguageLevel languageLevel, PsiSubstitutor methodSubstitutor, boolean checkVarargs) {
+    final int applicabilityLevel = PsiUtil.getApplicabilityLevel(method, methodSubstitutor, argTypes, languageLevel, false, checkVarargs);
+    final boolean applicable = applicabilityLevel > MethodCandidateInfo.ApplicabilityLevel.NOT_APPLICABLE;
+    if (applicable && !GenericsUtil.isTypeArgumentsApplicable(typeParameters, methodSubstitutor, myArgumentsList, false)) {
+      return false;
     }
-    if (aClass1 instanceof PsiTypeParameter && aClass2 != null) {
-      return chooseHigherDimension(type1, type2);
-    }
-    else if (aClass2 instanceof PsiTypeParameter && aClass1 != null) {
-      return chooseHigherDimension(type2, type1);
-    }
-
-    final Map<PsiTypeParameter, PsiType> map1 = classSubstitutor1.getSubstitutionMap();
-    final Map<PsiTypeParameter, PsiType> map2 = classSubstitutor2.getSubstitutionMap();
-    if (map1.size() == 1 && map2.size() == 1) {
-      boolean leftAssignable = InheritanceUtil.isInheritorOrSelf(aClass2, aClass1, true);
-      boolean rightAssignable = InheritanceUtil.isInheritorOrSelf(aClass1, aClass2, true);
-      final PsiType t1 = map1.values().iterator().next();
-      final PsiType t2 = map2.values().iterator().next();
-
-      boolean raw1 = t1 instanceof PsiClassType && ((PsiClassType)t1).hasParameters();
-      boolean raw2 = t2 instanceof PsiClassType && ((PsiClassType)t2).hasParameters();
-      if (!raw1 && raw2) return leftAssignable ? Specifics.FIRST : Specifics.NEITHER;
-      if (raw1 && !raw2) return rightAssignable ? Specifics.SECOND : Specifics.NEITHER;
-
-      final PsiTypeParameter p1 = map1.keySet().iterator().next();
-      final PsiTypeParameter p2 = map2.keySet().iterator().next();
-      Specifics specifics = checkTypeParams(method1, method2, classSubstitutor1, classSubstitutor2, type1, type2, p1, p2);
-      if (specifics == null) {
-        specifics = chooseHigherDimension(t1, t2);
-      }
-      if (specifics != null) {
-        if (specifics == Specifics.FIRST) {
-          if (leftAssignable && !rightAssignable) return Specifics.NEITHER;
-        }
-        else if (specifics == Specifics.SECOND) {
-          if (rightAssignable && !leftAssignable) return Specifics.NEITHER;
-        }
-      }
-      return specifics;
-    }
-    return null;
+    return applicable;
   }
 
-  private static Specifics chooseHigherDimension(PsiType type1, PsiType type2) {
-    if (type1 != null && type1.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return null;
-    if (type2 != null && type2.equalsToText(CommonClassNames.JAVA_LANG_OBJECT)) return null;
-    int d1 = type1 != null ? type1.getArrayDimensions() : 0;
-    int d2 = type2 != null ? type2.getArrayDimensions() : 0;
-    if (d1 > d2) {
-      return Specifics.SECOND;
+  private static PsiType[] typesAtSite(PsiType[] types1, PsiSubstitutor siteSubstitutor1) {
+    final PsiType[] types = new PsiType[types1.length];
+    for (int i = 0; i < types1.length; i++) {
+      types[i] = siteSubstitutor1.substitute(types1[i]);
     }
-    else if (d2 > d1) {
-      return Specifics.FIRST;
-    }
-    return null;
-  }
-
-  @Nullable
-  private static Specifics checkTypeParams(PsiMethod method1,
-                                           PsiMethod method2,
-                                           PsiSubstitutor classSubstitutor1,
-                                           PsiSubstitutor classSubstitutor2,
-                                           PsiType type1,
-                                           PsiType type2,
-                                           PsiTypeParameter p1,
-                                           PsiTypeParameter p2) {
-    final Map<PsiClass, PsiClassType> resolved1 = new HashMap<PsiClass, PsiClassType>();
-    for (PsiClassType referenceElement : p1.getExtendsList().getReferencedTypes()) {
-      ProgressManager.checkCanceled();
-      final PsiClass aClass = referenceElement.resolve();
-      if (aClass != null) {
-        resolved1.put(aClass, referenceElement);
-      }
-    }
-
-    final Map<PsiClass, PsiClassType> resolved2 = new HashMap<PsiClass, PsiClassType>();
-    for (PsiClassType referenceElement : p2.getExtendsList().getReferencedTypes()) {
-      ProgressManager.checkCanceled();
-      final PsiClass aClass = referenceElement.resolve();
-      if (aClass != null) {
-        resolved2.put(aClass, referenceElement);
-      }
-    }
-
-    Specifics specifics = null;
-    if (resolved1.size() > resolved2.size()){
-      specifics = checkExtendsList(resolved1, resolved2, Specifics.FIRST);
-    } else if (resolved2.size() > resolved1.size()) {
-      specifics = checkExtendsList(resolved2, resolved1, Specifics.SECOND);
-    }
-    if (specifics != null) return specifics;
-    specifics = checkSubtyping(TypeConversionUtil.erasure(PsiSubstitutor.EMPTY.substitute(p1)),
-                               TypeConversionUtil.erasure(PsiSubstitutor.EMPTY.substitute(p2)), method1, method2);
-    if (specifics != null) {
-      return specifics;
-    } else {
-      final PsiType ctype1 = classSubstitutor1.substitute(type1);
-      final PsiType ctype2 = classSubstitutor2.substitute(type2);
-      return checkSubtyping(ctype1, ctype2, method1, method2);
-    }
-  }
-
-  private static Specifics checkExtendsList(Map<PsiClass, PsiClassType> resolved1,
-                                            Map<PsiClass, PsiClassType> resolved2,
-                                            Specifics preferred) {
-    if (resolved1.keySet().containsAll(resolved2.keySet())){
-      resolved1.keySet().removeAll(resolved2.keySet());
-      for (Iterator<PsiClass> iterator = resolved1.keySet().iterator(); iterator.hasNext(); ) {
-        PsiClass psiClass = iterator.next();
-        final PsiClassType baseType = resolved1.get(psiClass);
-        for (PsiClassType childType : resolved2.values()) {
-          ProgressManager.checkCanceled();
-          if (TypeConversionUtil.isAssignable(baseType, childType, false)) {
-            iterator.remove();
-            break;
-          }
-        }
-      }
-      if (!resolved1.isEmpty()) return preferred;
-      return Specifics.NEITHER;
-    }
-    return null;
+    return types;
   }
 
   private static PsiSubstitutor calculateMethodSubstitutor(final PsiTypeParameter[] typeParameters,
+                                                           final PsiMethod method, 
+                                                           final PsiSubstitutor siteSubstitutor, 
                                                            final PsiType[] types1,
                                                            final PsiType[] types2,
-                                                           final PsiResolveHelper resolveHelper,
                                                            @NotNull LanguageLevel languageLevel) {
-    PsiSubstitutor substitutor = resolveHelper.inferTypeArguments(typeParameters, types1, types2, languageLevel);
-    for (PsiTypeParameter typeParameter : typeParameters) {
+    PsiSubstitutor substitutor = PsiResolveHelper.SERVICE.getInstance(method.getProject())
+      .inferTypeArguments(typeParameters, types1, types2, languageLevel);
+    for (PsiTypeParameter typeParameter : PsiUtil.typeParametersIterable(method)) {
       ProgressManager.checkCanceled();
       LOG.assertTrue(typeParameter != null);
       if (!substitutor.getSubstitutionMap().containsKey(typeParameter)) {
-        substitutor = substitutor.put(typeParameter, TypeConversionUtil.typeParameterErasure(typeParameter));
+        substitutor = substitutor.put(typeParameter, siteSubstitutor.substitute(typeParameter));
       }
     }
     return substitutor;
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/AmbiguousMethodCallIDEA67668.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/AmbiguousMethodCallIDEA67668.java
index 2de2b0e..b93cc27 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/AmbiguousMethodCallIDEA67668.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/AmbiguousMethodCallIDEA67668.java
@@ -12,6 +12,6 @@
 {
     public static void main(String[] args) {
         A a = null;
-        a.foo<error descr="Ambiguous method call: both 'A.foo(Collection<?>)' and 'A.foo(List<?>)' match">(null)</error>;
+        a.foo<error descr="Ambiguous method call: both 'A.foo(List<?>)' and 'A.foo(List<?>)' match">(null)</error>;
     }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA57569/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA57569/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..ac6a0ce
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA57569/pck/AmbiguousMethodCall.java
@@ -0,0 +1,11 @@
+package pck;
+abstract class C<T>  {
+    abstract Object foo(T x);
+    String foo(String x) { return null; }
+}
+
+class D extends C<String>{
+    {
+        foo("");
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA57633/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA57633/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..6bd05e0
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA57633/pck/AmbiguousMethodCall.java
@@ -0,0 +1,12 @@
+package pck;
+
+import java.io.Serializable;
+
+abstract class A {
+    abstract <T extends Comparable<?> & Serializable> void foo(T x, Integer y);
+    abstract <T extends Serializable & Comparable<?>> void foo(T x, Object y);
+
+    {
+        foo("", 1);
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67519/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67519/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..f663da2
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67519/pck/AmbiguousMethodCall.java
@@ -0,0 +1,18 @@
+package pck;
+class A<T extends C<String> & D>
+{
+    void bar(T x)
+    {
+        x.foo<error descr="Ambiguous method call: both 'C.foo(String)' and 'D.foo(String)' match">("")</error>;
+    }
+}
+
+interface D
+{
+    abstract void foo(String s);
+}
+
+interface C<T>
+{
+     abstract void foo(T s);
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67576/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67576/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..82706d3
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67576/pck/AmbiguousMethodCall.java
@@ -0,0 +1,21 @@
+package pck;
+
+interface A<T>
+{
+     <S> T foo();
+}
+
+interface B
+{
+    <S> Object foo();
+}
+
+interface C extends A, B { }
+
+class D
+{
+    void bar(C x)
+    {
+        x.foo();
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67836/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67836/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..b42af5a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67836/pck/AmbiguousMethodCall.java
@@ -0,0 +1,19 @@
+package pck;
+import static pck.D.foo;
+import static pck.C.foo;
+
+public class C {
+     public static <T> String foo(Comparable<? extends Comparable<T>> x){
+         return null;
+     }
+}
+
+class D {
+    public static <T> void foo(Comparable<? extends T> x){}
+}
+
+class B{
+    public static void bar(){
+        foo(1).toLowerCase();
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67864/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67864/pck/AmbiguousMethodCall.java
new file mode 100644
index 0000000..8240e7a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousIDEA67864/pck/AmbiguousMethodCall.java
@@ -0,0 +1,26 @@
+package pck;
+
+import java.util.List;
+
+import static pck.C.foo;
+import static pck.C.foo1;
+import static pck.D.foo;
+import static pck.D.foo1;
+
+class C {
+    static <T> void foo(List<T> x) { }
+    static <T extends List> void foo1(List<T> x) { }
+}
+
+class D {
+    static <T extends List<S>, S> String foo(List<T> x) { return null; }
+    static <T extends List<?>, S> String foo1(List<T> x) { return null; }
+}
+
+public class Main {
+    public static void main(String[] args){
+        List<List<String>> x = null;
+        foo(x).toCharArray();
+        foo1(x).toCharArray();
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousVarargs/pck/AmbiguousMethodCall.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousVarargs/pck/AmbiguousMethodCall.java
index d1b1202..b4ce3a4 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousVarargs/pck/AmbiguousMethodCall.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/advHighlighting7/ambiguousVarargs/pck/AmbiguousMethodCall.java
@@ -19,7 +19,7 @@
     abstract void foo(int... x);
 
     {
-        foo<error descr="Ambiguous method call: both 'A.foo(Object...)' and 'A.foo(int...)' match">(1)</error>;
+        foo(1);
     }
 }
 abstract class A1 {
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/AmbiguousTypeParamVsConcrete.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/AmbiguousTypeParamVsConcrete.java
new file mode 100644
index 0000000..272fb29
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/AmbiguousTypeParamVsConcrete.java
@@ -0,0 +1,22 @@
+public class CssPropertyValueImpl extends CssTableValueBase<CssPropertyValue, Object> implements CssPropertyValue {
+  public CssPropertyValueImpl(final Type type) {
+    super(type);
+  }
+}
+
+public abstract class CssTableValueBase<V extends CssTableValue, T> implements CssTableValue<V, T> {
+
+  protected CssTableValueBase(final Type type) {
+  }
+
+  protected CssTableValueBase(final T value) {
+  }
+}
+
+enum Type {}
+
+interface CssTableValue<A, B> {
+}
+
+interface CssPropertyValue extends CssTableValue<CssPropertyValue, Object> {
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/BoxingSpecific.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/BoxingSpecific.java
new file mode 100644
index 0000000..382f4e7
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/BoxingSpecific.java
@@ -0,0 +1,7 @@
+import java.util.*;
+
+abstract class A {
+    void computeCostIfNeeded(Map<Object, Integer> costMap) {
+        Math.min(costMap.get(null), 1);
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA112122.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA112122.java
new file mode 100644
index 0000000..bb1e1ab
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA112122.java
@@ -0,0 +1,16 @@
+class Cast<T> implements SemElement {
+
+    {
+        final SemKey<? extends Cast> key = null;
+        final Cast semElement =    getSemElement(key);
+    }
+
+    public <T extends SemElement> T getSemElement(SemKey<T> key) {
+        return null;
+    }
+
+
+    class SemKey<T extends SemElement> {}
+}
+
+interface SemElement {}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67843.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67843.java
new file mode 100644
index 0000000..69b359f
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA67843.java
@@ -0,0 +1,10 @@
+import java.util.List;
+
+class B{
+    public static void bar(){
+        <error descr="Inferred type 'java.util.List<java.lang.Comparable>' for type parameter 'T' is not within its bound; should implement 'java.util.List<java.lang.Comparable<java.util.List<java.lang.Comparable>>>'">foo(null)</error>.get(0).compareTo(null);
+    }
+    static <T extends List<Comparable<T>>> T foo(T x) {
+        return x;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEADEV15534.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEADEV15534.java
index d4042a5..0fc7639 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEADEV15534.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEADEV15534.java
@@ -18,7 +18,7 @@
         list.add(t1);
         SortTest<?> t2 = new SortTest<Integer>(0);
         list.add(t2);
-        <error descr="Inferred type 'SortTest<capture<?>>' for type parameter 'T' is not within its bound; should implement 'java.lang.Comparable<? super SortTest<?>>'">Collections.sort(list)</error>;
+        <error descr="Inferred type 'SortTest<?>' for type parameter 'T' is not within its bound; should implement 'java.lang.Comparable<? super SortTest<?>>'">Collections.sort(list)</error>;
         t1.compareTo<error descr="'compareTo(SortTest<capture<? extends java.lang.Comparable<capture<?>>>>)' in 'SortTest' cannot be applied to '(SortTest<capture<?>>)'">(t2)</error>;
 
         //this should be OK
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/Varargs.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/Varargs.java
index 24a51a2..66f4e07 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/Varargs.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/Varargs.java
@@ -22,7 +22,7 @@
         I i2 = MyTest1 :: m2;
         i2.m(42,42);
 
-        <error descr="Incompatible types. Found: '<method reference>', required: 'MyTest1.I'">I i3 = MyTest1 :: m3;</error>  
+        I i3 = MyTest1 :: m3;  
     }
 }
 
diff --git a/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log b/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log
index 1c40adc..4badc88 100644
--- a/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log
+++ b/java/java-tests/testData/compileServer/incremental/markDirty/recompileTwinDependencies.log
@@ -8,9 +8,3 @@
 src/package2/A.java
 src/package2/C.java
 End of files
-Cleaning output files:
-out/production/RecompileTwinDependencies/com/B.class
-End of files
-Compiling files:
-src/com/B.java
-End of files
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/empty.txt b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/empty.txt
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/pack1/empty.txt b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/pack1/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/pack1/empty.txt
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/pack1/subPack/empty.txt b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/pack1/subPack/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src1/target/pack1/subPack/empty.txt
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src2/pack1/S2.java b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src2/pack1/S2.java
new file mode 100644
index 0000000..0bd2d20
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/after/src2/pack1/S2.java
@@ -0,0 +1,3 @@
+package pack1;
+
+public class S2{}
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/pack1/empty.txt b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/pack1/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/pack1/empty.txt
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/pack1/subPack/Foo.java b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/pack1/subPack/Foo.java
new file mode 100644
index 0000000..2f3c2ed
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/pack1/subPack/Foo.java
@@ -0,0 +1,2 @@
+package pack1.subPack;
+public class Foo {}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/target/empty.txt b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/target/empty.txt
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src1/target/empty.txt
diff --git a/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src2/pack1/S2.java b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src2/pack1/S2.java
new file mode 100644
index 0000000..0bd2d20
--- /dev/null
+++ b/java/java-tests/testData/refactoring/movePackageAsDir/emptySubDirs/before/src2/pack1/S2.java
@@ -0,0 +1,3 @@
+package pack1;
+
+public class S2{}
diff --git a/java/java-tests/testData/refactoring/renameCollisions/RenameMethodCollisionSameSignature.java b/java/java-tests/testData/refactoring/renameCollisions/RenameMethodCollisionSameSignature.java
new file mode 100644
index 0000000..28dedc7
--- /dev/null
+++ b/java/java-tests/testData/refactoring/renameCollisions/RenameMethodCollisionSameSignature.java
@@ -0,0 +1,7 @@
+class RenameTest<T> {
+    void f<caret>oo(T t) {
+    }
+
+    void foo1(Object t) {
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java
index b35c8ff..dcac106 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/AdvHighlightingJdk7Test.java
@@ -199,7 +199,31 @@
     doTestAmbiguous();
   }
 
+  public void testAmbiguousIDEA67864() throws Exception {
+    doTestAmbiguous();
+  }
+
+  public void testAmbiguousIDEA67836() throws Exception {
+    doTestAmbiguous();
+  }
+
+  public void testAmbiguousIDEA67576() throws Exception {
+    doTestAmbiguous();
+  }
+
+  public void testAmbiguousIDEA67519() throws Exception {
+    doTestAmbiguous();
+  }
+
+  public void testAmbiguousIDEA57569() throws Exception {
+    doTestAmbiguous();
+  }
+
   public void testAmbiguousMethodsFromSameClassAccess() throws Exception {
     doTestAmbiguous();
   }
+
+  public void testAmbiguousIDEA57633() throws Exception {
+    doTestAmbiguous();
+  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
index efc253f..a0c0ffa 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
@@ -300,7 +300,8 @@
   public void testIDEA67682() { doTest5(false); }
   public void testIDEA57391() { doTest5(false); }
   public void testIDEA110869() { doTest5(false); }
-  public void testIDEA110947() { doTest5(false); }
+  public void _testIDEA110947() { doTest5(false); }
+  public void testIDEA112122() { doTest5(false); }
   public void testNoInferenceFromTypeCast() { doTest5(false); }
   public void testCaptureWildcardsInTypeCasts() { doTest5(false); }
   public void testIDEA111085() { doTest5(false); }
@@ -310,6 +311,9 @@
   public void testIDEA57439() { doTest5(false); }
   public void testIDEA57312() { doTest5(false); }
   public void testIDEA67865() { doTest5(false); }
+  public void testBoxingSpecific() { doTest5(false); }
+  public void testIDEA67843() { doTest5(false); }
+  public void testAmbiguousTypeParamVsConcrete() { doTest5(false); }
 
   public void testJavaUtilCollections_NoVerify() throws Exception {
     PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule()));
diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java
index 24adb29..d4c7274 100644
--- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java
+++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavadocFormatterTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
 
 
 import com.intellij.lang.java.JavaLanguage;
+import com.intellij.openapi.roots.LanguageLevelProjectExtension;
+import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.codeStyle.CommonCodeStyleSettings;
 
 /**
@@ -95,6 +97,7 @@
     getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true;
     getSettings().getRootSettings().WRAP_COMMENTS = true;
     getSettings().getRootSettings().RIGHT_MARGIN = 20;
+    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
 
     doTextTest("/**\n" + " * <p />\n" + " * Another paragraph of the description placed after blank line.\n" + " */\n" + "class A{}",
                "/**\n" +
@@ -107,11 +110,31 @@
                "class A {\n" +
                "}");
   }
-  
+
+  public void testSCR2632_JDK8_LanguageLevel() throws Exception {
+    getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true;
+    getSettings().getRootSettings().WRAP_COMMENTS = true;
+    getSettings().getRootSettings().RIGHT_MARGIN = 20;
+    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_8);
+
+    doTextTest("/**\n" + " * <p />\n" + " * Another paragraph of the description placed after blank line.\n" + " */\n" + "class A{}",
+               "/**\n" +
+               " * <p>\n" +
+               " * Another paragraph\n" +
+               " * of the description\n" +
+               " * placed after\n" +
+               " * blank line.\n" +
+               " */\n" +
+               "class A {\n" +
+               "}");
+  }
+
+
   public void testParagraphTagGeneration() {
     // Inspired by IDEA-61811
     getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true;
     getSettings().getRootSettings().JD_P_AT_EMPTY_LINES = true;
+    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
     doTextTest(
       "/**\n" +
       " * line 1\n" +
@@ -618,4 +641,47 @@
                     "}";
     doTextTest(before, before);
   }
+
+
+  public void testNotGenerateSelfClosingPTagIfLanguageLevelJava8() throws Exception {
+    getSettings().getRootSettings().JD_P_AT_EMPTY_LINES = true;
+    getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true;
+    String before = "/**\n" +
+                    " * Super method\n" +
+                    " *\n" +
+                    " * Super multiple times\n" +
+                    " */\n" +
+                    "public void voo() {\n" +
+                    "}\n";
+    String after = "/**\n" +
+                    " * Super method\n" +
+                    " * <p>\n" +
+                    " * Super multiple times\n" +
+                    " */\n" +
+                    "public void voo() {\n" +
+                    "}\n";
+    doClassTest(before, after);
+  }
+
+  public void testGenerateSelfClosingPTagIfLanguageLevelNotJava8() throws Exception {
+    getSettings().getRootSettings().JD_P_AT_EMPTY_LINES = true;
+    getSettings().getRootSettings().ENABLE_JAVADOC_FORMATTING = true;
+    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
+    String before = "/**\n" +
+                    " * Super method\n" +
+                    " *\n" +
+                    " * Super multiple times\n" +
+                    " */\n" +
+                    "public void voo() {\n" +
+                    "}\n";
+    String after = "/**\n" +
+                   " * Super method\n" +
+                   " * <p/>\n" +
+                   " * Super multiple times\n" +
+                   " */\n" +
+                   "public void voo() {\n" +
+                   "}\n";
+    doClassTest(before, after);
+  }
+
 }
\ No newline at end of file
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java
index 589f935..01b8604 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/MovePackageAsDirectoryTest.java
@@ -22,10 +22,8 @@
 import com.intellij.openapi.vfs.VirtualFileAdapter;
 import com.intellij.openapi.vfs.VirtualFileEvent;
 import com.intellij.openapi.vfs.VirtualFileManager;
-import com.intellij.psi.JavaPsiFacade;
-import com.intellij.psi.PsiDirectory;
-import com.intellij.psi.PsiFile;
-import com.intellij.psi.PsiPackage;
+import com.intellij.psi.*;
+import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.refactoring.move.moveClassesOrPackages.MoveDirectoryWithClassesProcessor;
 import com.intellij.testFramework.PsiTestUtil;
 import junit.framework.Assert;
@@ -80,10 +78,10 @@
     doTest(createAction("pack1", "target"));
   }
 
+  private static final String EMPTY_TXT = "empty.txt";
   public void testXmlEmptyDirRefs() throws Exception {
     final String packageName = "pack1";
     doTest(new MyPerformAction(packageName, "target"){
-      private static final String EMPTY_TXT = "empty.txt";
       @Override
       protected void preprocessSrcDir(PsiDirectory srcDirectory) {
         final PsiFile empty = srcDirectory.findFile(EMPTY_TXT);
@@ -108,6 +106,36 @@
     });
   }
 
+  public void testEmptySubDirs() throws Exception {
+    final String packageName = "pack1";
+    doTest(new MyPerformAction(packageName, "target"){
+      private static final String FOO = "pack1.subPack.Foo";
+      @Override
+      protected void preprocessSrcDir(PsiDirectory srcDirectory) {
+        final PsiClass empty = JavaPsiFacade.getInstance(getProject()).findClass(FOO, GlobalSearchScope.projectScope(getProject()));
+        assert empty != null;
+        ApplicationManager.getApplication().runWriteAction(new Runnable() {
+          public void run() {
+            empty.delete();
+          }
+        });
+      }
+
+      @Override
+      protected void postProcessTargetDir(PsiDirectory targetDirectory) {
+       final PsiDirectory subdirectory = targetDirectory.findSubdirectory(packageName);
+        assert subdirectory != null;
+        final PsiDirectory emptyDir = subdirectory.findSubdirectory("subPack");
+        assert emptyDir != null;
+        ApplicationManager.getApplication().runWriteAction(new Runnable() {
+          public void run() {
+            emptyDir.createFile(EMPTY_TXT);
+          }
+        });
+      }
+    });
+  }
+
   private PerformAction createAction(final String packageName, final String targetPackageName) {
     return new MyPerformAction(packageName, targetPackageName);
   }
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java b/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java
index 5fe6fbe..2caa921 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/RenameCollisionsTest.java
@@ -167,6 +167,17 @@
     fail("Conflicts were not found");
   }
 
+  public void testRenameMethodCollisionSameSignature() throws Exception {
+    try {
+      doTest("foo1");
+    }
+    catch (BaseRefactoringProcessor.ConflictsInTestsException e) {
+      Assert.assertEquals("Method with same erasure is already defined in the class <b><code>RenameTest</code></b>.", e.getMessage());
+      return;
+    }
+    fail("Conflicts were not found");
+  }
+
   public void testRenameMethodNoCollisionWithOtherSignature() throws Exception {
     doTest("foo2");
   }
diff --git a/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java b/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java
index 406dc3c..3a41315 100644
--- a/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java
+++ b/platform/analysis-api/src/com/intellij/codeInspection/InspectionManager.java
@@ -21,7 +21,6 @@
 import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
-import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -29,7 +28,6 @@
  * @author max
  */
 public abstract class InspectionManager {
-  @NonNls public static final String INSPECTION_GROUP_ID = "Inspections";  // for use in notifications
   public static final ExtensionPointName<Condition<PsiElement>> CANT_BE_STATIC_EXTENSION = ExtensionPointName.create("com.intellij.cantBeStatic");
 
   public static InspectionManager getInstance(Project project) {
@@ -158,4 +156,7 @@
                                                             final boolean showTooltip,
                                                             @NotNull ProblemHighlightType highlightType,
                                                             final LocalQuickFix... fixes);
+
+  @NotNull
+  public abstract GlobalInspectionContext createNewGlobalContext(boolean reuse);
 }
diff --git a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java
index 922403e..f932072 100644
--- a/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java
+++ b/platform/analysis-impl/src/com/intellij/codeInsight/daemon/impl/SeverityRegistrar.java
@@ -20,10 +20,13 @@
 import com.intellij.lang.annotation.HighlightSeverity;
 import com.intellij.openapi.editor.markup.TextAttributes;
 import com.intellij.openapi.extensions.Extensions;
+import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.JDOMExternalizable;
 import com.intellij.openapi.util.JDOMExternalizableStringList;
 import com.intellij.openapi.util.WriteExternalException;
+import com.intellij.profile.codeInspection.InspectionProfileManager;
+import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
 import com.intellij.util.containers.ContainerUtil;
 import gnu.trove.THashMap;
 import gnu.trove.TObjectIntHashMap;
@@ -68,6 +71,13 @@
     STANDARD_SEVERITIES.put(highlightSeverity.toString(), highlightInfoType);
   }
 
+  @NotNull
+  public static SeverityRegistrar getSeverityRegistrar(@Nullable Project project) {
+    return project == null
+           ? InspectionProfileManager.getInstance().getSeverityRegistrar()
+           : InspectionProjectProfileManager.getInstance(project).getSeverityRegistrar();
+  }
+
   public void registerSeverity(@NotNull SeverityBasedTextAttributes info, Color renderColor){
     final HighlightSeverity severity = info.getType().getSeverity(null);
     myMap.put(severity.toString(), info);
diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/InspectionManagerBase.java b/platform/analysis-impl/src/com/intellij/codeInspection/InspectionManagerBase.java
index 3e34f18..4eee9c2 100644
--- a/platform/analysis-impl/src/com/intellij/codeInspection/InspectionManagerBase.java
+++ b/platform/analysis-impl/src/com/intellij/codeInspection/InspectionManagerBase.java
@@ -23,7 +23,7 @@
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 
-public class InspectionManagerBase extends InspectionManager {
+public abstract class InspectionManagerBase extends InspectionManager {
   private final Project myProject;
   @NonNls protected String myCurrentProfileName;
 
diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/ProblemDescriptorBase.java b/platform/analysis-impl/src/com/intellij/codeInspection/ProblemDescriptorBase.java
index a7286d5..42dfa58 100644
--- a/platform/analysis-impl/src/com/intellij/codeInspection/ProblemDescriptorBase.java
+++ b/platform/analysis-impl/src/com/intellij/codeInspection/ProblemDescriptorBase.java
@@ -45,7 +45,7 @@
 
   public ProblemDescriptorBase(@NotNull PsiElement startElement,
                                @NotNull PsiElement endElement,
-                               String descriptionTemplate,
+                               @NotNull String descriptionTemplate,
                                LocalQuickFix[] fixes,
                                @NotNull ProblemHighlightType highlightType,
                                boolean isAfterEndOfLine,
diff --git a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProfileManager.java b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProfileManager.java
index 3a443ce..f5d6960 100644
--- a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProfileManager.java
+++ b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProfileManager.java
@@ -38,7 +38,7 @@
  * User: anna
  * Date: 29-Nov-2005
  */
-public abstract class InspectionProfileManager extends ApplicationProfileManager implements NamedComponent {
+public abstract class InspectionProfileManager extends ApplicationProfileManager implements SeverityProvider, NamedComponent {
   @NonNls protected static final String INSPECTION_DIR = "inspection";
   @NonNls protected static final String FILE_SPEC = "$ROOT_CONFIG$/" + INSPECTION_DIR;
 
diff --git a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManager.java b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManager.java
index 3eff813..93406e6 100644
--- a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManager.java
+++ b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManager.java
@@ -33,7 +33,7 @@
  * User: anna
  * Date: 30-Nov-2005
  */
-public abstract class InspectionProjectProfileManager extends DefaultProjectProfileManager implements ProjectComponent, PersistentStateComponent<Element> {
+public abstract class InspectionProjectProfileManager extends DefaultProjectProfileManager implements ProjectComponent, SeverityProvider, PersistentStateComponent<Element> {
   public InspectionProjectProfileManager(@NotNull Project project,
                                          @NotNull InspectionProfileManager inspectionProfileManager,
                                          @NotNull DependencyValidationManager holder) {
diff --git a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java
index eecc207..412a5373 100644
--- a/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java
+++ b/platform/analysis-impl/src/com/intellij/profile/codeInspection/InspectionProjectProfileManagerImpl.java
@@ -54,7 +54,7 @@
              stateSplitter = InspectionProjectProfileManagerImpl.ProfileStateSplitter.class)
   }
 )
-public class InspectionProjectProfileManagerImpl extends InspectionProjectProfileManager implements SeverityProvider, ProjectComponent, PersistentStateComponent<Element> {
+public class InspectionProjectProfileManagerImpl extends InspectionProjectProfileManager implements ProjectComponent, PersistentStateComponent<Element> {
   private final Map<String, InspectionProfileWrapper>  myName2Profile = new ConcurrentHashMap<String, InspectionProfileWrapper>();
   private final SeverityRegistrar mySeverityRegistrar;
   private final NamedScopeManager myLocalScopesHolder;
diff --git a/platform/annotations/src/org/intellij/lang/annotations/Language.java b/platform/annotations/src/org/intellij/lang/annotations/Language.java
index 23ced5e..7f8c080 100644
--- a/platform/annotations/src/org/intellij/lang/annotations/Language.java
+++ b/platform/annotations/src/org/intellij/lang/annotations/Language.java
@@ -18,11 +18,12 @@
 
 import org.jetbrains.annotations.NonNls;
 
-import static java.lang.annotation.ElementType.*;
 import java.lang.annotation.Retention;
 import java.lang.annotation.RetentionPolicy;
 import java.lang.annotation.Target;
 
+import static java.lang.annotation.ElementType.*;
+
 @Retention(RetentionPolicy.CLASS)
 @Target({ METHOD, FIELD, PARAMETER, LOCAL_VARIABLE, ANNOTATION_TYPE })
 
diff --git a/java/openapi/src/com/intellij/codeInsight/ContainerProvider.java b/platform/core-api/src/com/intellij/codeInsight/ContainerProvider.java
similarity index 100%
rename from java/openapi/src/com/intellij/codeInsight/ContainerProvider.java
rename to platform/core-api/src/com/intellij/codeInsight/ContainerProvider.java
diff --git a/platform/lang-api/src/com/intellij/psi/ElementDescriptionLocation.java b/platform/core-api/src/com/intellij/psi/ElementDescriptionLocation.java
similarity index 100%
rename from platform/lang-api/src/com/intellij/psi/ElementDescriptionLocation.java
rename to platform/core-api/src/com/intellij/psi/ElementDescriptionLocation.java
diff --git a/platform/lang-api/src/com/intellij/psi/ElementDescriptionProvider.java b/platform/core-api/src/com/intellij/psi/ElementDescriptionProvider.java
similarity index 100%
rename from platform/lang-api/src/com/intellij/psi/ElementDescriptionProvider.java
rename to platform/core-api/src/com/intellij/psi/ElementDescriptionProvider.java
diff --git a/platform/lang-api/src/com/intellij/psi/ElementDescriptionUtil.java b/platform/core-api/src/com/intellij/psi/ElementDescriptionUtil.java
similarity index 100%
rename from platform/lang-api/src/com/intellij/psi/ElementDescriptionUtil.java
rename to platform/core-api/src/com/intellij/psi/ElementDescriptionUtil.java
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesDescriptionLocation.java b/platform/core-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesDescriptionLocation.java
similarity index 100%
rename from platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesDescriptionLocation.java
rename to platform/core-impl/src/com/intellij/codeInsight/highlighting/HighlightUsagesDescriptionLocation.java
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemIdeNotificationManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemIdeNotificationManager.java
index 97379e8..bdcb5b4 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemIdeNotificationManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemIdeNotificationManager.java
@@ -29,7 +29,7 @@
  * show corresponding message to the end-user.
  * <p/>
  * Thread-safe.
- *
+ * 
  * @author Denis Zhdanov
  * @since 3/21/12 4:04 PM
  */
@@ -65,7 +65,7 @@
         ShowSettingsUtil.getInstance().editConfigurable(project, configurable);
       }
     };
-
+    
     for (ExternalSystemNotificationExtension extension : ExternalSystemNotificationExtension.EP_NAME.getExtensions()) {
       if (!externalSystemId.equals(extension.getTargetExternalSystemId())) {
         continue;
@@ -113,12 +113,12 @@
         }
 
         Notification notification = group.createNotification(title, message, type, listener);
-        applyNotification(notification, project);
+        applyNotification(notification, project); 
       }
     });
-
+    
   }
-
+  
   private void applyNotification(@NotNull final Notification notification, @NotNull final Project project) {
     final Notification oldNotification = myNotification.get();
     if (oldNotification != null && myNotification.compareAndSet(oldNotification, null)) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemNotificationExtension.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemNotificationExtension.java
index d6906b1..1a0d50c 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemNotificationExtension.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/notification/ExternalSystemNotificationExtension.java
@@ -25,7 +25,7 @@
 
 /**
  * Allows to customize {@link ExternalSystemIdeNotificationManager external system notifications} shown to end-user by the ide.
- *
+ * 
  * @author Denis Zhdanov
  * @since 8/5/13 8:52 AM
  */
@@ -33,13 +33,13 @@
 
   ExtensionPointName<ExternalSystemNotificationExtension> EP_NAME
     = ExtensionPointName.create("com.intellij.externalSystemNotificationExtension");
-
+  
   @NotNull
   ProjectSystemId getTargetExternalSystemId();
 
   /**
    * Allows to customize external system processing error.
-   *
+   * 
    * @param project  target ide project
    * @param error    error occurred during external system processing
    * @param hint     hint for a use-case during processing of which given error occurs
@@ -47,7 +47,7 @@
    */
   @Nullable
   CustomizationResult customize(@NotNull Project project, @NotNull Throwable error, @Nullable UsageHint hint);
-
+  
   enum UsageHint {
     PROJECT_REFRESH
   }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java
index 8527c63..24a18bf 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java
@@ -332,7 +332,7 @@
 
     for (Map.Entry<ProjectSystemId, Set<String>> entry : copy.entrySet()) {
       for (String path : entry.getValue()) {
-        ExternalSystemUtil.refreshProject(myProject, entry.getKey(), path, myRefreshCallback, true, false);
+        ExternalSystemUtil.refreshProject(myProject, entry.getKey(), path, myRefreshCallback, true, false, false);
       }
     }
   }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
index bca23a8..a603bd0 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
@@ -82,7 +82,7 @@
         final ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
         final ModifiableRootModel model = moduleRootManager.getModifiableModel();
         final ContentEntry[] contentEntries = model.getContentEntries();
-        final Map<String, ContentEntry> contentEntriesMap = new HashMap<String, ContentEntry>(contentEntries.length);
+        final Map<String, ContentEntry> contentEntriesMap = ContainerUtilRt.newHashMap();
         for(ContentEntry contentEntry : contentEntries) {
           contentEntriesMap.put(contentEntry.getUrl(), contentEntry);
         }
@@ -91,7 +91,7 @@
             ContentRootData contentRoot = data.getData();
             ContentEntry contentEntry = findOrCreateContentRoot(model, contentRoot.getRootPath());
             LOG.info(String.format("Importing content root '%s' for module '%s'", contentRoot.getRootPath(), module.getName()));
-            final Set<String> retainedPaths = new HashSet<String>();
+            final Set<String> retainedPaths = ContainerUtilRt.newHashSet();
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.SOURCE)) {
               createSourceRootIfAbsent(contentEntry, path, module.getName());
               retainedPaths.add(ExternalSystemApiUtil.toCanonicalPath(path));
@@ -118,15 +118,15 @@
     });
   }
 
-  private static void removeOutdatedContentFolders(final ContentEntry entry, final Set<String> retainedContentFolders) {
-    final List<SourceFolder> sourceFolders = new ArrayList<SourceFolder>(Arrays.asList(entry.getSourceFolders()));
+  private static void removeOutdatedContentFolders(@NotNull final ContentEntry entry, @NotNull final Set<String> retainedContentFolders) {
+    final List<SourceFolder> sourceFolders = ContainerUtilRt.newArrayList(entry.getSourceFolders());
     for(final SourceFolder sourceFolder : sourceFolders) {
       final String path = VirtualFileManager.extractPath(sourceFolder.getUrl());
       if(!retainedContentFolders.contains(path)) {
         entry.removeSourceFolder(sourceFolder);
       }
     }
-    final List<ExcludeFolder> excludeFolders = new ArrayList<ExcludeFolder>(Arrays.asList(entry.getExcludeFolders()));
+    final List<ExcludeFolder> excludeFolders =  ContainerUtilRt.newArrayList(entry.getExcludeFolders());
     for(final ExcludeFolder excludeFolder : excludeFolders) {
       final String path = VirtualFileManager.extractPath(excludeFolder.getUrl());
       if(!(excludeFolder instanceof ExcludedOutputFolder) && !retainedContentFolders.contains(path)) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java
index 174992b..bab6a66 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/wizard/AbstractExternalProjectImportBuilder.java
@@ -122,7 +122,10 @@
         AbstractExternalSystemSettings systemSettings = ExternalSystemApiUtil.getSettings(project, myExternalSystemId);
         final ExternalProjectSettings projectSettings = getCurrentExternalProjectSettings();
         Set<ExternalProjectSettings> projects = ContainerUtilRt.newHashSet(systemSettings.getLinkedProjectsSettings());
+        // add current importing project settings to linked projects settings or replace if similar already exist
+        projects.remove(projectSettings);
         projects.add(projectSettings);
+
         systemSettings.copyFrom(myControl.getSystemSettings());
         systemSettings.setLinkedProjectsSettings(projects);
 
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModel.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModel.java
index b428938..16ba604 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModel.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModel.java
@@ -79,7 +79,8 @@
     int toAdd = elementsNumber - size();
     if (toAdd == 0) {
       return;
-    } if(toAdd < 0) {
+    }
+    if(toAdd < 0) {
       removeRange(elementsNumber, size() - 1);
     }
     while (--toAdd >= 0) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksPanel.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksPanel.java
index ef214dd..442418b 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksPanel.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksPanel.java
@@ -49,7 +49,6 @@
 
 import javax.swing.*;
 import java.awt.*;
-import java.awt.event.ActionEvent;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
 
@@ -97,7 +96,7 @@
     };
 
     myAllTasksModel = new ExternalSystemTasksTreeModel(externalSystemId);
-    myAllTasksTree = new ExternalSystemTasksTree(myAllTasksModel, settings.getExpandStates()) {
+    myAllTasksTree = new ExternalSystemTasksTree(myAllTasksModel, settings.getExpandStates(), project, externalSystemId) {
       @Override
       protected void processMouseEvent(MouseEvent e) {
         if (e.getClickCount() > 0) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java
index 5c297ef..3ee91ab 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java
@@ -15,7 +15,10 @@
  */
 package com.intellij.openapi.externalSystem.service.task.ui;
 
+import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo;
+import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
+import com.intellij.openapi.project.Project;
 import com.intellij.ui.TreeSpeedSearch;
 import com.intellij.ui.treeStructure.Tree;
 import com.intellij.util.Alarm;
@@ -25,11 +28,14 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import javax.swing.*;
 import javax.swing.event.TreeExpansionEvent;
 import javax.swing.event.TreeModelEvent;
 import javax.swing.event.TreeWillExpandListener;
 import javax.swing.tree.ExpandVetoException;
 import javax.swing.tree.TreePath;
+import java.awt.event.ActionEvent;
+import java.awt.event.KeyEvent;
 import java.util.*;
 
 /**
@@ -57,7 +63,9 @@
   private boolean mySuppressCollapseTracking;
 
   public ExternalSystemTasksTree(@NotNull ExternalSystemTasksTreeModel model,
-                                 @NotNull Map<String/*tree path*/, Boolean/*expanded*/> expandedStateHolder)
+                                 @NotNull Map<String/*tree path*/, Boolean/*expanded*/> expandedStateHolder,
+                                 @NotNull final Project project,
+                                 @NotNull final ProjectSystemId externalSystemId)
   {
     super(model);
     myExpandedStateHolder = expandedStateHolder;
@@ -91,6 +99,18 @@
       }
     });
     new TreeSpeedSearch(this);
+
+    getInputMap().put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), "Enter");
+    getActionMap().put("Enter", new AbstractAction() {
+      @Override
+      public void actionPerformed(ActionEvent e) {
+        ExternalTaskExecutionInfo task = produce();
+        if (task == null) {
+          return;
+        }
+        ExternalSystemUtil.runTask(task.getSettings(), task.getExecutorId(), project, externalSystemId);
+      }
+    });
   }
 
   /**
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalProjectPathField.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalProjectPathField.java
index 7ae9e19..da6c6e17 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalProjectPathField.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ui/ExternalProjectPathField.java
@@ -148,7 +148,7 @@
   @NotNull
   private static Tree buildRegisteredProjectsTree(@NotNull Project project, @NotNull ProjectSystemId externalSystemId) {
     ExternalSystemTasksTreeModel model = new ExternalSystemTasksTreeModel(externalSystemId);
-    ExternalSystemTasksTree result = new ExternalSystemTasksTree(model, ContainerUtilRt.<String, Boolean>newHashMap());
+    ExternalSystemTasksTree result = new ExternalSystemTasksTree(model, ContainerUtilRt.<String, Boolean>newHashMap(), project, externalSystemId);
     
     ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
     assert manager != null;
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
index 97f013e..b9692ef 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
@@ -357,10 +357,10 @@
   /**
    * Queries slave gradle process to refresh target gradle project.
    *
-   * @param project             target intellij project to use
-   * @param externalProjectPath path of the target gradle project's file
-   * @param callback            callback to be notified on refresh result
-   * @param resolveLibraries    flag that identifies whether gradle libraries should be resolved during the refresh
+   * @param project               target intellij project to use
+   * @param externalProjectPath   path of the target gradle project's file
+   * @param callback              callback to be notified on refresh result
+   * @param resolveLibraries      flag that identifies whether gradle libraries should be resolved during the refresh
    * @return the most up-to-date gradle project (if any)
    */
   public static void refreshProject(@NotNull final Project project,
@@ -368,7 +368,27 @@
                                     @NotNull final String externalProjectPath,
                                     @NotNull final ExternalProjectRefreshCallback callback,
                                     final boolean resolveLibraries,
-                                    final boolean modal)
+                                    final boolean modal) {
+    refreshProject(project, externalSystemId, externalProjectPath, callback, resolveLibraries, modal, true);
+  }
+
+  /**
+   * Queries slave gradle process to refresh target gradle project.
+   *
+   * @param project               target intellij project to use
+   * @param externalProjectPath   path of the target gradle project's file
+   * @param callback              callback to be notified on refresh result
+   * @param resolveLibraries      flag that identifies whether gradle libraries should be resolved during the refresh
+   * @param reportRefreshError    prevent to show annoying error notification, e.g. if auto-import mode used
+   * @return the most up-to-date gradle project (if any)
+   */
+  public static void refreshProject(@NotNull final Project project,
+                                    @NotNull final ProjectSystemId externalSystemId,
+                                    @NotNull final String externalProjectPath,
+                                    @NotNull final ExternalProjectRefreshCallback callback,
+                                    final boolean resolveLibraries,
+                                    final boolean modal,
+                                    final boolean reportRefreshError)
   {
     File projectFile = new File(externalProjectPath);
     final String projectName;
@@ -407,6 +427,15 @@
 
         callback.onFailure(message, extractDetails(error));
 
+        ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
+        if(manager == null) {
+          return;
+        }
+        AbstractExternalSystemSettings<?, ?, ?> settings = manager.getSettingsProvider().fun(project);
+        ExternalProjectSettings projectSettings = settings.getLinkedProjectSettings(externalProjectPath);
+        if (projectSettings == null || !reportRefreshError) {
+          return;
+        }
         ExternalSystemIdeNotificationManager notificationManager = ServiceManager.getService(ExternalSystemIdeNotificationManager.class);
         if (notificationManager != null) {
           notificationManager.processExternalProjectRefreshError(error, project, projectName, externalSystemId);
diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy
index 70a0b6e..b763920 100644
--- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy
+++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy
@@ -17,16 +17,15 @@
 
 import com.intellij.openapi.components.ServiceManager
 import com.intellij.openapi.externalSystem.model.DataNode
-import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType
 import com.intellij.openapi.externalSystem.model.project.ProjectData
 import com.intellij.openapi.externalSystem.test.AbstractExternalSystemTest
-import com.intellij.openapi.externalSystem.test.ExternalProjectBuilder
 import com.intellij.openapi.externalSystem.test.ExternalSystemTestUtil
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil
 import com.intellij.openapi.roots.LibraryOrderEntry
 import com.intellij.openapi.roots.ModuleSourceOrderEntry
-import com.intellij.openapi.roots.OrderEntry;
+import com.intellij.openapi.roots.OrderEntry
 
+import static com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType.*
 /**
  * @author Denis Zhdanov
  * @since 8/8/13 5:17 PM
@@ -60,35 +59,27 @@
 
   void 'test changes in a project layout (content roots) could be detected on Refresh'() {
 
-    String rootPath = ExternalSystemApiUtil.toCanonicalPath("/project1");
+    String rootPath = ExternalSystemApiUtil.toCanonicalPath(project.basePath);
 
-    DataNode<ProjectData> projectNodeInitial = buildExternalProjectInfo {
-      project {
-        module('module') {
-          contentRoot(rootPath) {
-            folder(type: ExternalSystemSourceType.TEST, path: rootPath + '/src/test/resources')
-            folder(type: ExternalSystemSourceType.TEST, path: rootPath + '/src/test/java')
-            folder(type: ExternalSystemSourceType.TEST, path: rootPath + '/src/test/groovy')
-            folder(type: ExternalSystemSourceType.SOURCE, path: rootPath + '/src/main/resources')
-            folder(type: ExternalSystemSourceType.SOURCE, path: rootPath + '/src/main/java')
-            folder(type: ExternalSystemSourceType.SOURCE, path: rootPath + '/src/main/groovy')
-            folder(type: ExternalSystemSourceType.EXCLUDED, path: rootPath + '/.gradle')
-            folder(type: ExternalSystemSourceType.EXCLUDED, path: rootPath + '/build')
-          } } }
-    }
+    def contentRoots = [
+      (TEST): ['src/test/resources', '/src/test/java', 'src/test/groovy'],
+      (SOURCE): ['src/main/resources', 'src/main/java', 'src/main/groovy'],
+      (EXCLUDED): ['.gradle', 'build']
+    ]
 
-    DataNode<ProjectData> projectNodeRefreshed = buildExternalProjectInfo {
-      project {
-        module('module') {
-          contentRoot(rootPath) {
-            folder(type: ExternalSystemSourceType.TEST, path: rootPath + '/src/test/resources')
-            folder(type: ExternalSystemSourceType.TEST, path: rootPath + '/src/test/java')
-            folder(type: ExternalSystemSourceType.SOURCE, path: rootPath + '/src/main/resources')
-            folder(type: ExternalSystemSourceType.SOURCE, path: rootPath + '/src/main/java')
-            folder(type: ExternalSystemSourceType.EXCLUDED, path: rootPath + '/.gradle')
-            folder(type: ExternalSystemSourceType.EXCLUDED, path: rootPath + '/build')
-          } } }
-    }
+    def projectRootBuilder = {
+      buildExternalProjectInfo {
+        project {
+          module {
+            contentRoot(rootPath) {
+              contentRoots.each { key, values -> values.each { folder(type: key, path: "$rootPath/$it") } }
+            } } } } }
+
+    DataNode<ProjectData> projectNodeInitial = projectRootBuilder()
+
+    contentRoots[(SOURCE)].remove(0)
+    contentRoots[(TEST)].remove(0)
+    DataNode<ProjectData> projectNodeRefreshed = projectRootBuilder()
 
     applyProjectState([projectNodeInitial, projectNodeRefreshed])
 
diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModelTest.java b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModelTest.java
index 241479d..9bed36f 100644
--- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModelTest.java
+++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemRecentTaskListModelTest.java
@@ -16,14 +16,15 @@
 package com.intellij.openapi.externalSystem.service.task.ui;
 
 import com.intellij.openapi.command.impl.DummyProject;
-import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings;
 import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo;
+import com.intellij.openapi.externalSystem.test.ExternalSystemTestUtil;
 import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
+import com.intellij.util.containers.ContainerUtilRt;
 import org.junit.Assert;
+import org.junit.Before;
 import org.junit.Test;
 
-import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -31,44 +32,46 @@
  * @since 8/13/13
  */
 public class ExternalSystemRecentTaskListModelTest {
+  
+  private ExternalSystemRecentTaskListModel myModel;
+
+  @Before
+  public void setUp() {
+    myModel = new ExternalSystemRecentTaskListModel(ExternalSystemTestUtil.TEST_EXTERNAL_SYSTEM_ID, DummyProject.getInstance());
+  }
+  
   @Test
   public void testSetFirst() throws Exception {
-    ExternalSystemRecentTaskListModel model =
-      new ExternalSystemRecentTaskListModel(new ProjectSystemId("test"), DummyProject.getInstance());
-
-    List<ExternalTaskExecutionInfo> tasks = new ArrayList<ExternalTaskExecutionInfo>();
+    List<ExternalTaskExecutionInfo> tasks = ContainerUtilRt.newArrayList();
     for (int i = 0; i <= ExternalSystemConstants.RECENT_TASKS_NUMBER; i++) {
       new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task" + i);
     }
-    model.setTasks(tasks);
+    myModel.setTasks(tasks);
 
-    model.setFirst(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "newTask"));
+    myModel.setFirst(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "newTask"));
 
-    Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER, model.getSize());
-    model.setFirst(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task1"));
-    Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER, model.getSize());
+    Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
+    myModel.setFirst(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task1"));
+    Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
   }
 
   @Test
   public void testEnsureSize() throws Exception {
-    ExternalSystemRecentTaskListModel model =
-      new ExternalSystemRecentTaskListModel(new ProjectSystemId("test"), DummyProject.getInstance());
-
-    List<ExternalTaskExecutionInfo> tasks = new ArrayList<ExternalTaskExecutionInfo>();
+    List<ExternalTaskExecutionInfo> tasks = ContainerUtilRt.newArrayList();
 
     // test task list widening
-    model.setTasks(tasks);
-    model.ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
-    Assert.assertEquals("task list widening failed", ExternalSystemConstants.RECENT_TASKS_NUMBER, model.getSize());
+    myModel.setTasks(tasks);
+    myModel.ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
+    Assert.assertEquals("task list widening failed", ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
 
     // test task list reduction
     for (int i = 0; i < ExternalSystemConstants.RECENT_TASKS_NUMBER + 1; i++) {
       tasks.add(new ExternalTaskExecutionInfo(new ExternalSystemTaskExecutionSettings(), "task" + i));
     }
-    model.setTasks(tasks);
-    Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER + 1, model.getSize());
+    myModel.setTasks(tasks);
+    Assert.assertEquals(ExternalSystemConstants.RECENT_TASKS_NUMBER + 1, myModel.getSize());
 
-    model.ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
-    Assert.assertEquals("task list reduction failed", ExternalSystemConstants.RECENT_TASKS_NUMBER, model.getSize());
+    myModel.ensureSize(ExternalSystemConstants.RECENT_TASKS_NUMBER);
+    Assert.assertEquals("task list reduction failed", ExternalSystemConstants.RECENT_TASKS_NUMBER, myModel.getSize());
   }
 }
diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy
index 541d177..f80d50d 100644
--- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy
+++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy
@@ -67,7 +67,7 @@
         String externalConfigPath = attributes.externalConfigPath ?: projectDir.path
         ModuleData moduleData = new ModuleData(TEST_EXTERNAL_SYSTEM_ID,
                                                ModuleTypeId.JAVA_MODULE,
-                                               attributes.name,
+                                               attributes.name ?: name as String,
                                                moduleFilePath,
                                                externalConfigPath)
         return (current as DataNode).createChild(ProjectKeys.MODULE, moduleData)
diff --git a/platform/lang-api/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandler.java b/platform/lang-api/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandler.java
index b443b74..b555f99 100644
--- a/platform/lang-api/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandler.java
+++ b/platform/lang-api/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandler.java
@@ -20,6 +20,7 @@
 import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
 
 import java.util.List;
 
@@ -29,4 +30,19 @@
   boolean canSelect(PsiElement e);
 
   List<TextRange> select(PsiElement e, CharSequence editorText, int cursorOffset, Editor editor);
+
+  /**
+   * Returns minimal selection length for given element.
+   * 
+   * Sometimes the length of word selection should be bounded below. 
+   * E.g. it is useful in languages that requires prefixes for variable (php, less, etc.).
+   * By default this kind of variables will be selected without prefix: @<selection>variable</selection>,
+   * but it make sense to exclude this range from selection list. 
+   * So if this method returns 9 as a minimal length of selection
+   * then first selection range for @variable will be: <selection>@variable</selection>.
+   * 
+   * @param element element at caret
+   * @return minimal selection length for given element
+   */
+  int getMinimalTextRangeLength(@NotNull PsiElement element);
 }
\ No newline at end of file
diff --git a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java
index 6db7b29..cbe0535 100644
--- a/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java
+++ b/platform/lang-api/src/com/intellij/execution/configurations/CommandLineState.java
@@ -67,9 +67,7 @@
   }
 
   public void addConsoleFilters(Filter... filters) {
-    for (Filter filter : filters) {
-      myConsoleBuilder.addFilter(filter);
-    }
+    myConsoleBuilder.filters(filters);
   }
 
   @Override
diff --git a/platform/lang-api/src/com/intellij/execution/configurations/UnknownRunConfiguration.java b/platform/lang-api/src/com/intellij/execution/configurations/UnknownRunConfiguration.java
index 20953b0..aa2082e 100644
--- a/platform/lang-api/src/com/intellij/execution/configurations/UnknownRunConfiguration.java
+++ b/platform/lang-api/src/com/intellij/execution/configurations/UnknownRunConfiguration.java
@@ -182,9 +182,5 @@
     protected JComponent createEditor() {
       return myPanel;
     }
-
-    @Override
-    protected void disposeEditor() {
-    }
   }
 }
diff --git a/platform/lang-api/src/com/intellij/execution/filters/TextConsoleBuilder.java b/platform/lang-api/src/com/intellij/execution/filters/TextConsoleBuilder.java
index 30b4dda..8bf589b 100644
--- a/platform/lang-api/src/com/intellij/execution/filters/TextConsoleBuilder.java
+++ b/platform/lang-api/src/com/intellij/execution/filters/TextConsoleBuilder.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,6 +17,8 @@
 
 import com.intellij.execution.ui.ConsoleView;
 
+import java.util.List;
+
 /**
  * @author dyoma
  */
@@ -24,5 +26,20 @@
   public abstract ConsoleView getConsole();
 
   public abstract void addFilter(Filter filter);
+
   public abstract void setViewer(boolean isViewer);
-}
+
+  public TextConsoleBuilder filters(Filter... filters) {
+    for (Filter filter : filters) {
+      addFilter(filter);
+    }
+    return this;
+  }
+
+  public TextConsoleBuilder filters(List<Filter> filters) {
+    for (Filter filter : filters) {
+      addFilter(filter);
+    }
+    return this;
+  }
+}
\ No newline at end of file
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java
index 42179ac..23f337b 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonCodeAnalyzerImpl.java
@@ -528,7 +528,7 @@
                                           @NotNull final Processor<HighlightInfo> processor) {
     LOG.assertTrue(ApplicationManager.getApplication().isReadAccessAllowed());
 
-    final SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     MarkupModelEx model = (MarkupModelEx)DocumentMarkupModel.forDocument(document, project, true);
     return model.processRangeHighlightersOverlappingWith(startOffset, endOffset, new Processor<RangeHighlighterEx>() {
       @Override
@@ -551,7 +551,7 @@
                                                      @NotNull final Processor<HighlightInfo> processor) {
     LOG.assertTrue(ApplicationManager.getApplication().isReadAccessAllowed());
 
-    final SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     MarkupModelEx model = (MarkupModelEx)DocumentMarkupModel.forDocument(document, project, true);
     return model.processRangeHighlightersOutside(startOffset, endOffset, new Processor<RangeHighlighterEx>() {
       @Override
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
index a6b6dcb..c37adbf 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
@@ -84,7 +84,7 @@
       ContainerUtil.quickSort(infos, new Comparator<HighlightInfo>() {
         @Override
         public int compare(final HighlightInfo o1, final HighlightInfo o2) {
-          int i = SeverityUtil.getSeverityRegistrar(myProject).compare(o2.getSeverity(), o1.getSeverity());
+          int i = SeverityRegistrar.getSeverityRegistrar(myProject).compare(o2.getSeverity(), o1.getSeverity());
           if (i != 0) return i;
           return o1.getToolTip().compareTo(o2.getToolTip());
         }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitor.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitor.java
index 686a1fc..35980dd 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitor.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DefaultHighlightVisitor.java
@@ -70,7 +70,7 @@
     myDumbService = DumbService.getInstance(project);
     myBatchMode = batchMode;
   }
-                                                     
+
   @Override
   public boolean suitableForFile(@NotNull final PsiFile file) {
     return true;
@@ -178,8 +178,10 @@
         builder.descriptionAndTooltip(errorDescription);
       }
       final HighlightInfo info = builder.create();
-      for(ErrorQuickFixProvider provider: Extensions.getExtensions(ErrorQuickFixProvider.EP_NAME)) {
-        provider.registerErrorQuickFix(element, info);
+      if (info != null) {
+        for(ErrorQuickFixProvider provider: Extensions.getExtensions(ErrorQuickFixProvider.EP_NAME)) {
+          provider.registerErrorQuickFix(element, info);
+        }
       }
       return info;
     }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java
index 1831fa9..1fecb3e 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/GotoNextErrorHandler.java
@@ -51,7 +51,7 @@
   }
 
   private void gotoNextError(Project project, Editor editor, PsiFile file, int caretOffset) {
-    final SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     DaemonCodeAnalyzerSettings settings = DaemonCodeAnalyzerSettings.getInstance();
     int maxSeverity = settings.NEXT_ERROR_ACTION_GOES_TO_ERRORS_FIRST ? severityRegistrar.getSeveritiesCount() - 1 : 0;
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java
index 6b81cb5..1c61666 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/HighlightInfo.java
@@ -187,7 +187,7 @@
   public static TextAttributes getAttributesByType(@Nullable final PsiElement element,
                                                    @NotNull HighlightInfoType type,
                                                    @NotNull TextAttributesScheme colorsScheme) {
-    final SeverityRegistrar severityRegistrar = SeverityUtil
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar
       .getSeverityRegistrar(element != null ? element.getProject() : null);
     final TextAttributes textAttributes = severityRegistrar.getTextAttributesBySeverity(type.getSeverity(element));
     if (textAttributes != null) {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/SeverityUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/SeverityUtil.java
index 6faadd2..de2e353 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/SeverityUtil.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/SeverityUtil.java
@@ -18,12 +18,7 @@
 import com.intellij.openapi.editor.colors.EditorColorsManager;
 import com.intellij.openapi.editor.colors.EditorColorsScheme;
 import com.intellij.openapi.editor.markup.TextAttributes;
-import com.intellij.openapi.project.Project;
-import com.intellij.profile.codeInspection.InspectionProfileManager;
-import com.intellij.profile.codeInspection.InspectionProfileManagerImpl;
-import com.intellij.profile.codeInspection.InspectionProjectProfileManagerImpl;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import java.util.Collection;
 
@@ -45,11 +40,4 @@
     }
     return new SeverityRegistrar.SeverityBasedTextAttributes(registrar.getTextAttributesBySeverity(type.getSeverity(null)), (HighlightInfoType.HighlightInfoTypeImpl)type);
   }
-
-  @NotNull
-  public static SeverityRegistrar getSeverityRegistrar(@Nullable Project project) {
-    return project == null
-           ? ((InspectionProfileManagerImpl)InspectionProfileManager.getInstance()).getSeverityRegistrar()
-           : InspectionProjectProfileManagerImpl.getInstanceImpl(project).getSeverityRegistrar();
-  }
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java
index 3f8e595..bdc05b5 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficLightRenderer.java
@@ -80,7 +80,7 @@
     myDaemonCodeAnalyzer = project == null ? null : (DaemonCodeAnalyzerImpl)DaemonCodeAnalyzer.getInstance(project);
     myDocument = document;
     myFile = file;
-    mySeverityRegistrar = SeverityUtil.getSeverityRegistrar(myProject);
+    mySeverityRegistrar = SeverityRegistrar.getSeverityRegistrar(myProject);
     refresh();
 
     if (project != null) {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficProgressPanel.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficProgressPanel.java
index 0a85456..46abc69 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficProgressPanel.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficProgressPanel.java
@@ -224,7 +224,7 @@
       String text = "<html><body>";
       for (int i = status.errorCount.length - 1; i >= 0; i--) {
         if (status.errorCount[i] > 0) {
-          final HighlightSeverity severity = SeverityUtil.getSeverityRegistrar(myTrafficLightRenderer.getProject()).getSeverityByIndex(i);
+          final HighlightSeverity severity = SeverityRegistrar.getSeverityRegistrar(myTrafficLightRenderer.getProject()).getSeverityByIndex(i);
           String name =
             status.errorCount[i] > 1 ? StringUtil.pluralize(severity.toString().toLowerCase()) : severity.toString().toLowerCase();
           text += status.errorAnalyzingFinished
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficTooltipRendererImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficTooltipRendererImpl.java
index 98ef163..22eebb5 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficTooltipRendererImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/TrafficTooltipRendererImpl.java
@@ -47,7 +47,7 @@
   @Override
   public void repaintTooltipWindow() {
     if (myPanel != null) {
-      SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(myTrafficLightRenderer.getProject());
+      SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(myTrafficLightRenderer.getProject());
       TrafficLightRenderer.DaemonCodeAnalyzerStatus status = myTrafficLightRenderer.getDaemonCodeAnalyzerStatus(true, severityRegistrar);
       myPanel.updatePanel(status, false);
     }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java
index 17c6db5..4e41c37 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/UpdateHighlightersUtil.java
@@ -164,7 +164,7 @@
     if (info.getStartOffset() < startOffset || info.getEndOffset() > endOffset) return;
 
     MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);
-    final SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     final boolean myInfoIsError = isSevere(info, severityRegistrar);
     Processor<HighlightInfo> otherHighlightInTheWayProcessor = new Processor<HighlightInfo>() {
       @Override
@@ -236,7 +236,7 @@
     final MarkupModel markup = DocumentMarkupModel.forDocument(document, project, true);
     assertMarkupConsistent(markup, project);
 
-    final SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     final HighlightersRecycler infosToRemove = new HighlightersRecycler();
     ContainerUtil.quickSort(infos, BY_START_OFFSET_NODUPS);
 
@@ -309,7 +309,7 @@
                                      final int group) {
     ApplicationManager.getApplication().assertIsDispatchThread();
 
-    final SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    final SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     final HighlightersRecycler infosToRemove = new HighlightersRecycler();
     DaemonCodeAnalyzerImpl.processHighlights(document, project, null, range.getStartOffset(), range.getEndOffset(), new Processor<HighlightInfo>() {
       @Override
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/ErrorQuickFixProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/ErrorQuickFixProvider.java
index 292375f..3a87ff3 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/ErrorQuickFixProvider.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/analysis/ErrorQuickFixProvider.java
@@ -19,12 +19,13 @@
 import com.intellij.codeInsight.daemon.impl.HighlightInfo;
 import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.psi.PsiErrorElement;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * @author yole
  */
 public interface ErrorQuickFixProvider {
   ExtensionPointName<ErrorQuickFixProvider> EP_NAME = ExtensionPointName.create("com.intellij.errorQuickFixProvider");
-  
-  void registerErrorQuickFix(PsiErrorElement errorElement, HighlightInfo highlightInfo);
+
+  void registerErrorQuickFix(@NotNull PsiErrorElement errorElement, @NotNull HighlightInfo highlightInfo);
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandlerBase.java
index e91ebdd..aebbcf3 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandlerBase.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/ExtendWordSelectionHandlerBase.java
@@ -21,8 +21,9 @@
 import com.intellij.openapi.util.TextRange;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.PsiElement;
-import com.intellij.util.containers.CollectionFactory;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.text.CharArrayUtil;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.util.ArrayList;
@@ -50,6 +51,11 @@
     return ranges;
   }
 
+  @Override
+  public int getMinimalTextRangeLength(@NotNull PsiElement element) {
+    return 0;
+  }
+
   public static List<TextRange> expandToWholeLine(CharSequence text, @Nullable TextRange range, boolean isSymmetric) {
     List<TextRange> result = new ArrayList<TextRange>();
 
@@ -113,7 +119,7 @@
   }
 
   public static List<TextRange> expandToWholeLinesWithBlanks(CharSequence text, TextRange range) {
-    List<TextRange> result = CollectionFactory.arrayList();
+    List<TextRange> result = ContainerUtil.newArrayList();
     result.addAll(expandToWholeLine(text, range, true));
 
     TextRange last = result.isEmpty() ? range : result.get(result.size() - 1);
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java
index d727a5c..642069f 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/SelectWordUtil.java
@@ -29,6 +29,7 @@
 import com.intellij.psi.StringEscapesTokenTypes;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Processor;
+import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -191,14 +192,22 @@
                                      Editor editor) {
     boolean stop = false;
 
-    for (ExtendWordSelectionHandler selectioner : getExtendWordSelectionHandlers()) {
-      if (!selectioner.canSelect(element)) continue;
-
+    ExtendWordSelectionHandler[] extendWordSelectionHandlers = getExtendWordSelectionHandlers();
+    int minimalTextRangeLength = 0;
+    List<ExtendWordSelectionHandler> availableSelectioners = ContainerUtil.newLinkedList();
+    for (ExtendWordSelectionHandler selectioner : extendWordSelectionHandlers) {
+      if (selectioner.canSelect(element)) {
+        int selectionerMinimalTextRange = selectioner.getMinimalTextRangeLength(element);
+        minimalTextRangeLength = Math.max(minimalTextRangeLength, selectionerMinimalTextRange);
+        availableSelectioners.add(selectioner);
+      }
+    }
+    for (ExtendWordSelectionHandler selectioner : availableSelectioners) {
       List<TextRange> ranges = selectioner.select(element, text, cursorOffset, editor);
       if (ranges == null) continue;
 
       for (TextRange range : ranges) {
-        if (range == null) continue;
+        if (range == null || range.getLength() < minimalTextRangeLength) continue;
 
         stop |= processor.process(range);
       }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java
index f912221..03f3ee3 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/FileLevelIntentionComponent.java
@@ -17,7 +17,7 @@
 package com.intellij.codeInsight.intention.impl;
 
 import com.intellij.codeInsight.daemon.impl.HighlightInfo;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.codeInsight.daemon.impl.ShowIntentionsPass;
 import com.intellij.codeInsight.intention.EmptyIntentionAction;
 import com.intellij.codeInsight.intention.IntentionAction;
@@ -72,7 +72,7 @@
     }
 
     myLabel.setText(description);
-    myLabel.setIcon(SeverityUtil.getSeverityRegistrar(project).compare(severity, HighlightSeverity.ERROR) >= 0 ? AllIcons.Actions.QuickfixBulb : AllIcons.Actions.IntentionBulb);
+    myLabel.setIcon(SeverityRegistrar.getSeverityRegistrar(project).compare(severity, HighlightSeverity.ERROR) >= 0 ? AllIcons.Actions.QuickfixBulb : AllIcons.Actions.IntentionBulb);
 
     new ClickListener() {
       @Override
@@ -97,11 +97,11 @@
   }
 
   private  Color getColor(HighlightSeverity severity) {
-    if (SeverityUtil.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.ERROR) >= 0) {
+    if (SeverityRegistrar.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.ERROR) >= 0) {
       return LightColors.RED;
     }
 
-    if (SeverityUtil.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.WARNING) >= 0) {
+    if (SeverityRegistrar.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.WARNING) >= 0) {
       return LightColors.YELLOW;
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
index fa62ee9..0d8a17c 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupCellRenderer.java
@@ -65,8 +65,6 @@
   static final Color PREFIX_FOREGROUND_COLOR = new JBColor(new Color(176, 0, 176), new Color(209, 122, 214));
   private static final Color SELECTED_PREFIX_FOREGROUND_COLOR = new JBColor(new Color(249, 236, 204), new Color(209, 122, 214));
 
-  private static final Color EMPTY_ITEM_FOREGROUND_COLOR = FOREGROUND_COLOR;
-
   private final LookupImpl myLookup;
 
   private final SimpleColoredComponent myNameComponent;
@@ -144,7 +142,7 @@
 
     myTypeLabel.clear();
     if (allowedWidth > 0) {
-      allowedWidth -= setTypeTextLabel(item, background, foreground, presentation, isSelected ? getMaxWidth() : allowedWidth, isSelected);
+      allowedWidth -= setTypeTextLabel(item, background, foreground, presentation, isSelected ? getMaxWidth() : allowedWidth, isSelected, nonFocusedSelection);
     }
 
     myTailComponent.clear();
@@ -237,6 +235,14 @@
     return text.substring(0, i) + ELLIPSIS;
   }
 
+  private static Color getTypeTextColor(LookupElement item, Color foreground, LookupElementPresentation presentation, boolean selected, boolean nonFocusedSelection) {
+    if (nonFocusedSelection) {
+      return foreground;
+    }
+
+    return presentation.isTypeGrayed() ? getGrayedForeground(selected) : item instanceof EmptyLookupItem ? JBColor.foreground() : foreground;
+  }
+
   private static Color getTailTextColor(boolean isSelected, LookupElementPresentation.TextFragment fragment, Color defaultForeground, boolean nonFocusedSelection) {
     if (nonFocusedSelection) {
       return defaultForeground;
@@ -317,7 +323,7 @@
                                Color foreground,
                                final LookupElementPresentation presentation,
                                int allowedWidth,
-                               boolean selected) {
+                               boolean selected, boolean nonFocusedSelection) {
     final String givenText = presentation.getTypeText();
     final String labelText = trimLabelText(StringUtil.isEmpty(givenText) ? "" : " " + givenText, allowedWidth, myNormalMetrics);
 
@@ -346,7 +352,7 @@
     }
 
     myTypeLabel.setBackground(sampleBackground);
-    myTypeLabel.setForeground(presentation.isTypeGrayed() ? getGrayedForeground(selected) : item instanceof EmptyLookupItem ? JBColor.foreground() : foreground);
+    myTypeLabel.setForeground(getTypeTextColor(item, foreground, presentation, selected, nonFocusedSelection));
     return used;
   }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
index d2b99fd..904c3da 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
@@ -425,7 +425,7 @@
       }
       catch (IndexNotReadyException e) {
         showDumbModeNotification(myTargetElement.getProject());
-        return null;
+        return DocInfo.EMPTY;
       }
       finally {
         token.finish();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java
index c3bd803..05fcba4 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateLookupActionProvider.java
@@ -4,6 +4,7 @@
 import com.intellij.codeInsight.lookup.LookupActionProvider;
 import com.intellij.codeInsight.lookup.LookupElement;
 import com.intellij.codeInsight.lookup.LookupElementAction;
+import com.intellij.icons.AllIcons;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.options.ShowSettingsUtil;
 import com.intellij.openapi.project.Project;
@@ -13,7 +14,7 @@
 /**
  * @author peter
  */
-public class LiveTemplateLookupActionProvider implements LookupActionProvider{
+public class LiveTemplateLookupActionProvider implements LookupActionProvider {
   @Override
   public void fillActions(LookupElement element, final Lookup lookup, Consumer<LookupElementAction> consumer) {
     if (element instanceof LiveTemplateLookupElement) {
@@ -41,6 +42,22 @@
           return Result.HIDE_LOOKUP;
         }
       });
+
+      final TemplateImpl templateFromSettings = TemplateSettings.getInstance().getTemplate(template.getKey(), template.getGroupName());
+      if (templateFromSettings != null) {
+        consumer.consume(new LookupElementAction(AllIcons.Actions.Delete, String.format("Disable '%s' template", template.getKey())) {
+          @Override
+          public Result performLookupAction() {
+            ApplicationManager.getApplication().invokeLater(new Runnable() {
+              @Override
+              public void run() {
+                templateFromSettings.setDeactivated(true);
+              }
+            });
+            return Result.HIDE_LOOKUP;
+          }
+        });
+      }
     }
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java b/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java
index afba5fb..adb1c29 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/actions/CleanupInspectionIntention.java
@@ -16,13 +16,11 @@
 
 package com.intellij.codeInspection.actions;
 
-import com.intellij.CommonBundle;
 import com.intellij.codeInsight.FileModificationService;
 import com.intellij.codeInsight.intention.EmptyIntentionAction;
 import com.intellij.codeInsight.intention.HighPriorityAction;
 import com.intellij.codeInsight.intention.IntentionAction;
 import com.intellij.codeInspection.*;
-import com.intellij.codeInspection.ex.InspectionManagerEx;
 import com.intellij.codeInspection.ex.InspectionToolWrapper;
 import com.intellij.codeInspection.ex.LocalInspectionToolWrapper;
 import com.intellij.openapi.application.ApplicationManager;
@@ -34,7 +32,6 @@
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
-import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NotNull;
 
@@ -50,7 +47,7 @@
   private final InspectionToolWrapper myToolWrapper;
   private final Class myQuickfixClass;
 
-  public CleanupInspectionIntention(@NotNull InspectionToolWrapper toolWrapper, Class quickFixClass) {
+  public CleanupInspectionIntention(@NotNull InspectionToolWrapper toolWrapper, @NotNull Class quickFixClass) {
     myToolWrapper = toolWrapper;
     myQuickfixClass = quickFixClass;
   }
@@ -74,7 +71,7 @@
       ProgressManager.getInstance().runProcess(new Computable<List<ProblemDescriptor>>() {
         @Override
         public List<ProblemDescriptor> compute() {
-          InspectionManagerEx inspectionManager = (InspectionManagerEx)InspectionManager.getInstance(project);
+          InspectionManager inspectionManager = InspectionManager.getInstance(project);
           return InspectionEngine.runInspectionOnFile(file, myToolWrapper, inspectionManager.createNewGlobalContext(false));
         }
       }, new EmptyProgressIndicator());
@@ -87,45 +84,32 @@
         return d2.getTextRange().getStartOffset() - d1.getTextRange().getStartOffset();
       }
     });
-    boolean fixesWereAvailable = false;
     for (final ProblemDescriptor descriptor : descriptions) {
       final QuickFix[] fixes = descriptor.getFixes();
       if (fixes != null && fixes.length > 0) {
-        fixesWereAvailable = true;
         for (final QuickFix<CommonProblemDescriptor> fix : fixes) {
           if (fix != null && fix.getClass().isAssignableFrom(myQuickfixClass)) {
             final PsiElement element = descriptor.getPsiElement();
             if (element != null && element.isValid()) {
-              if (fix instanceof IntentionAction && ((IntentionAction)fix).startInWriteAction()) {
-                ApplicationManager.getApplication().runWriteAction(new Runnable() {
-                  @Override
-                  public void run() {
-                    fix.applyFix(project, descriptor);
-                  }
-                });
-              }
-              else {
-                fix.applyFix(project, descriptor);
-              }
-              PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
+              ApplicationManager.getApplication().runWriteAction(new Runnable() {
+                @Override
+                public void run() {
+                  fix.applyFix(project, descriptor);
+                }
+              });
+              PsiDocumentManager.getInstance(project).commitAllDocuments();
             }
             break;
           }
         }
       }
     }
-    if (!fixesWereAvailable) {
-      CommonRefactoringUtil.showErrorHint(project, editor, "No fixes are available in batch mode", CommonBundle.getWarningTitle(), null);
-    }
   }
 
-
-
-
   @Override
   public boolean isAvailable(@NotNull final Project project, final Editor editor, final PsiFile file) {
-    return myQuickfixClass != null && myQuickfixClass != EmptyIntentionAction.class && !(myToolWrapper instanceof LocalInspectionToolWrapper &&
-                                                                                         ((LocalInspectionToolWrapper)myToolWrapper).isUnfair());
+    return myQuickfixClass != EmptyIntentionAction.class &&
+           !(myToolWrapper instanceof LocalInspectionToolWrapper && ((LocalInspectionToolWrapper)myToolWrapper).isUnfair());
   }
 
   @Override
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java
index 537e85c..fd5eef8 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/InspectionRVContentProviderImpl.java
@@ -118,9 +118,8 @@
     final RefEntity refElement = refElementDescriptor.getUserObject();
     InspectionToolPresentation presentation = context.getPresentation(toolWrapper);
     if (context.getUIOptions().SHOW_ONLY_DIFF && presentation.getElementStatus(refElement) == FileStatus.NOT_CHANGED) return;
-    if (toolWrapper instanceof LocalInspectionToolWrapper) {
-      final CommonProblemDescriptor[] problems = refElementDescriptor.getProblemDescriptors();
-      if (problems != null) {
+    final CommonProblemDescriptor[] problems = refElementDescriptor.getProblemDescriptors();
+    if (problems != null) {
         final RefElementNode elemNode = addNodeToParent(container, presentation, pNode);
         for (CommonProblemDescriptor problem : problems) {
           assert problem != null;
@@ -132,7 +131,6 @@
             elemNode.setProblem(problems[0]);
           }
         }
-      }
     }
     else {
       if (canPackageRepeat) {
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java
index 2955f36..0cae317 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/ProblemDescriptorImpl.java
@@ -30,7 +30,7 @@
 
   public ProblemDescriptorImpl(@NotNull PsiElement startElement,
                                @NotNull PsiElement endElement,
-                               String descriptionTemplate,
+                               @NotNull String descriptionTemplate,
                                LocalQuickFix[] fixes,
                                @NotNull ProblemHighlightType highlightType,
                                boolean isAfterEndOfLine,
@@ -41,7 +41,7 @@
 
   public ProblemDescriptorImpl(@NotNull PsiElement startElement,
                                @NotNull PsiElement endElement,
-                               String descriptionTemplate,
+                               @NotNull String descriptionTemplate,
                                LocalQuickFix[] fixes,
                                @NotNull ProblemHighlightType highlightType,
                                boolean isAfterEndOfLine,
@@ -53,7 +53,7 @@
 
   public ProblemDescriptorImpl(@NotNull PsiElement startElement,
                                @NotNull PsiElement endElement,
-                               String descriptionTemplate,
+                               @NotNull String descriptionTemplate,
                                LocalQuickFix[] fixes,
                                @NotNull ProblemHighlightType highlightType,
                                boolean isAfterEndOfLine,
@@ -61,7 +61,6 @@
                                final boolean tooltip,
                                @Nullable HintAction hintAction,
                                boolean onTheFly) {
-
     super(startElement, endElement, descriptionTemplate, fixes, highlightType, isAfterEndOfLine, rangeInElement, tooltip, onTheFly);
     myHintAction = hintAction;
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java
index 7d0575d..b9aa7ec 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/QuickFixAction.java
@@ -79,11 +79,12 @@
       return;
     }
 
+    e.getPresentation().setVisible(false);
+    e.getPresentation().setEnabled(false);
+
     final InspectionTree tree = view.getTree();
     final InspectionToolWrapper toolWrapper = tree.getSelectedToolWrapper();
     if (!view.isSingleToolInSelection() || toolWrapper != myToolWrapper) {
-      e.getPresentation().setVisible(false);
-      e.getPresentation().setEnabled(false);
       return;
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewComparator.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewComparator.java
index 49cc04b..cab3fbe 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewComparator.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionResultsViewComparator.java
@@ -24,7 +24,7 @@
  */
 package com.intellij.codeInspection.ui;
 
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.codeInspection.CommonProblemDescriptor;
 import com.intellij.codeInspection.ProblemDescriptor;
 import com.intellij.codeInspection.offline.OfflineProblemDescriptor;
@@ -56,7 +56,7 @@
     if (node1 instanceof InspectionSeverityGroupNode && node2 instanceof InspectionSeverityGroupNode) {
       final InspectionSeverityGroupNode groupNode1 = (InspectionSeverityGroupNode)node1;
       final InspectionSeverityGroupNode groupNode2 = (InspectionSeverityGroupNode)node2;
-      return -SeverityUtil.getSeverityRegistrar(groupNode1.getProject()).compare(groupNode1.getSeverityLevel().getSeverity(), groupNode2.getSeverityLevel().getSeverity());
+      return -SeverityRegistrar.getSeverityRegistrar(groupNode1.getProject()).compare(groupNode1.getSeverityLevel().getSeverity(), groupNode2.getSeverityLevel().getSeverity());
     }
     if (node1 instanceof InspectionSeverityGroupNode) return -1;
     if (node2 instanceof InspectionSeverityGroupNode) return 1;
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java
index 295e608..d50bddc 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/InspectionTree.java
@@ -165,7 +165,7 @@
 
   public CommonProblemDescriptor[] getSelectedDescriptors() {
     final InspectionToolWrapper toolWrapper = getSelectedToolWrapper();
-    if (getSelectionCount() == 0 || !(toolWrapper instanceof LocalInspectionToolWrapper)) return EMPTY_DESCRIPTORS;
+    if (getSelectionCount() == 0) return EMPTY_DESCRIPTORS;
     final TreePath[] paths = getSelectionPaths();
     final LinkedHashSet<CommonProblemDescriptor> descriptors = new LinkedHashSet<CommonProblemDescriptor>();
     for (TreePath path : paths) {
diff --git a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConfigurationPanel.java b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConfigurationPanel.java
index 5115871..b043b3e 100644
--- a/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConfigurationPanel.java
+++ b/platform/lang-impl/src/com/intellij/diagnostic/logging/LogConfigurationPanel.java
@@ -285,10 +285,6 @@
     return myWholePanel;
   }
 
-  @Override
-  protected void disposeEditor() {
-  }
-
   private static boolean showEditorDialog(@NotNull LogFileOptions options) {
     EditLogPatternDialog dialog = new EditLogPatternDialog();
     dialog.init(options.getName(), options.getPathPattern(), options.isShowAll());
diff --git a/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java b/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java
index bcc6d33..ae36cc5 100644
--- a/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java
+++ b/platform/lang-impl/src/com/intellij/execution/RunContentExecutor.java
@@ -86,9 +86,7 @@
 
   private ConsoleView createConsole(@NotNull Project project, @NotNull ProcessHandler processHandler) {
     TextConsoleBuilder consoleBuilder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
-    for (Filter filter : myFilterList) {
-      consoleBuilder.addFilter(filter);
-    }
+    consoleBuilder.filters(myFilterList);
     ConsoleView console = consoleBuilder.getConsole();
     console.attachToProcess(processHandler);
     return console;
diff --git a/platform/lang-impl/src/com/intellij/execution/filters/TextConsoleBuilderImpl.java b/platform/lang-impl/src/com/intellij/execution/filters/TextConsoleBuilderImpl.java
index 3227b94..dac15cf 100644
--- a/platform/lang-impl/src/com/intellij/execution/filters/TextConsoleBuilderImpl.java
+++ b/platform/lang-impl/src/com/intellij/execution/filters/TextConsoleBuilderImpl.java
@@ -23,6 +23,7 @@
 import org.jetbrains.annotations.NotNull;
 
 import java.util.ArrayList;
+import java.util.List;
 
 /**
  * @author dyoma
@@ -62,6 +63,12 @@
   }
 
   @Override
+  public TextConsoleBuilder filters(List<Filter> filters) {
+    myFilters.addAll(filters);
+    return this;
+  }
+
+  @Override
   public void setViewer(boolean isViewer) {
     myViewer = isViewer;
   }
@@ -89,4 +96,4 @@
   public boolean isUsePredefinedMessageFilter() {
     return myUsePredefinedMessageFilter;
   }
-}
+}
\ No newline at end of file
diff --git a/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java b/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java
index ffa4bd0..72a9e3b 100644
--- a/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java
+++ b/platform/lang-impl/src/com/intellij/execution/impl/ConfigurationSettingsEditorWrapper.java
@@ -96,10 +96,6 @@
   }
 
   @Override
-  protected void disposeEditor() {
-  }
-
-  @Override
   public void resetEditorFrom(final RunnerAndConfigurationSettings settings) {
     myEditor.resetEditorFrom(settings);
     doReset(settings);
diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java
index a67764a..f0d6aa1e 100644
--- a/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java
+++ b/platform/lang-impl/src/com/intellij/execution/impl/RunnerAndConfigurationSettingsImpl.java
@@ -54,8 +54,8 @@
   private static final String TEMPLATE_FLAG_ATTRIBUTE = "default";
   @NonNls
   public static final String NAME_ATTR = "name";
-  @NonNls
-  public static final String UNIQUE_ID = "id";
+  //@NonNls
+  //public static final String UNIQUE_ID = "id";
   @NonNls
   protected static final String DUMMY_ELEMENT_NANE = "dummy";
   @NonNls
@@ -84,7 +84,7 @@
   private boolean myEditBeforeRun;
   private boolean mySingleton;
   private String myFolderName;
-  private String myID = null;
+  //private String myID = null;
 
   public RunnerAndConfigurationSettingsImpl(RunManagerImpl manager) {
     myManager = manager;
@@ -145,10 +145,12 @@
 
   @Override
   public String getUniqueID() {
-    if (myID == null) {
-      myID = UUID.randomUUID().toString();
-    }
-    return myID;
+    return myConfiguration.getType().getDisplayName() + "." + myConfiguration.getName() +
+           (myConfiguration instanceof UnknownRunConfiguration ? myConfiguration.getUniqueID() : "");
+    //if (myID == null) {
+    //  myID = UUID.randomUUID().toString();
+    //}
+    //return myID;
   }
 
   @Override
@@ -195,8 +197,8 @@
     myTemporary = Boolean.valueOf(element.getAttributeValue(TEMPORARY_ATTRIBUTE)).booleanValue() || TEMP_CONFIGURATION.equals(element.getName());
     myEditBeforeRun = Boolean.valueOf(element.getAttributeValue(EDIT_BEFORE_RUN)).booleanValue();
     myFolderName = element.getAttributeValue(FOLDER_NAME);
-    assert myID == null: "myId must be null at readExternal() stage";
-    myID = element.getAttributeValue(UNIQUE_ID, UUID.randomUUID().toString());
+    //assert myID == null: "myId must be null at readExternal() stage";
+    //myID = element.getAttributeValue(UNIQUE_ID, UUID.randomUUID().toString());
     // singleton is not configurable by user for template
     if (!myIsTemplate) {
       mySingleton = Boolean.valueOf(element.getAttributeValue(SINGLETON)).booleanValue();
@@ -269,7 +271,7 @@
       if (myFolderName != null) {
         element.setAttribute(FOLDER_NAME, myFolderName);
       }
-      element.setAttribute(UNIQUE_ID, getUniqueID());
+      //element.setAttribute(UNIQUE_ID, getUniqueID());
 
       if (isEditBeforeRun()) element.setAttribute(EDIT_BEFORE_RUN, String.valueOf(true));
       if (isSingleton()) element.setAttribute(SINGLETON, String.valueOf(true));
diff --git a/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java b/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java
index 456e72c..d3ea9a0 100644
--- a/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java
+++ b/platform/lang-impl/src/com/intellij/find/EditorSearchComponent.java
@@ -21,6 +21,7 @@
 import com.intellij.find.impl.FindManagerImpl;
 import com.intellij.find.impl.livePreview.*;
 import com.intellij.icons.AllIcons;
+import com.intellij.ide.ui.UISettings;
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
 import com.intellij.openapi.actionSystem.impl.ActionToolbarImpl;
@@ -587,7 +588,6 @@
         replaceCurrent();
       }
     });
-    myReplaceButton.setMnemonic('p');
 
     myReplaceAllButton = new JButton("Replace all");
     myReplaceAllButton.setFocusable(false);
@@ -597,7 +597,6 @@
         myLivePreviewController.performReplaceAll();
       }
     });
-    myReplaceAllButton.setMnemonic('a');
 
     myExcludeButton = new JButton("");
     myExcludeButton.setFocusable(false);
@@ -608,7 +607,12 @@
         moveCursor(SearchResults.Direction.DOWN);
       }
     });
-    myExcludeButton.setMnemonic('l');
+
+    if (!UISettings.getInstance().DISABLE_MNEMONICS_IN_CONTROLS) {
+      myReplaceButton.setMnemonic('p');
+      myReplaceAllButton.setMnemonic('a');
+      myExcludeButton.setMnemonic('l');
+    }
 
 
     ActionGroup actionsGroup = new DefaultActionGroup(new ShowHistoryAction(myReplaceFieldGetter, this));
diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindResultUsageInfo.java b/platform/lang-impl/src/com/intellij/find/impl/FindResultUsageInfo.java
index f3f207a..138af2c 100644
--- a/platform/lang-impl/src/com/intellij/find/impl/FindResultUsageInfo.java
+++ b/platform/lang-impl/src/com/intellij/find/impl/FindResultUsageInfo.java
@@ -83,7 +83,7 @@
 
     assert result.isStringFound();
 
-    if (myFindModel.isRegularExpressions()) {
+    if (myFindModel.isRegularExpressions() || myFindModel.isInCommentsOnly() || myFindModel.isInStringLiteralsOnly()) {
       myAnchor = SmartPointerManager.getInstance(getProject()).createSmartPsiFileRangePointer(file, TextRange.from(offset, 0));
     }
 
diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
index 36f4585..b6b24d8 100644
--- a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
+++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
@@ -266,7 +266,12 @@
       IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
         @Override
         public void run() {
-          GotoActionAction.openOptionOrPerformAction(value, pattern, project, myContextComponent ,myActionEvent);
+          if (value instanceof BooleanOptionDescription) {
+            final BooleanOptionDescription option = (BooleanOptionDescription)value;
+            option.setOptionState(!option.isOptionEnabled());
+          } else {
+            GotoActionAction.openOptionOrPerformAction(value, pattern, project, myContextComponent ,myActionEvent);
+          }
         }
       });
       return;
diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java
index 129105f..fe1a9f9 100644
--- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java
+++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/ChooseByNameBase.java
@@ -498,6 +498,10 @@
               }
               else {
                 Component oppositeComponent = e.getOppositeComponent();
+                if (oppositeComponent == myCheckBox) {
+                  myTextField.requestFocus();
+                  return;
+                }
                 if (oppositeComponent != null && !(oppositeComponent instanceof JFrame) &&
                     myList.isShowing() &&
                     (oppositeComponent == myList || SwingUtilities.isDescendingFrom(myList, oppositeComponent))) {
diff --git a/platform/lang-impl/src/com/intellij/openapi/paths/WebReferencesAnnotatorBase.java b/platform/lang-impl/src/com/intellij/openapi/paths/WebReferencesAnnotatorBase.java
index 01a2535..3414a99 100644
--- a/platform/lang-impl/src/com/intellij/openapi/paths/WebReferencesAnnotatorBase.java
+++ b/platform/lang-impl/src/com/intellij/openapi/paths/WebReferencesAnnotatorBase.java
@@ -29,6 +29,7 @@
 import com.intellij.util.containers.HashMap;
 import org.apache.commons.httpclient.HttpClient;
 import org.apache.commons.httpclient.HttpStatus;
+import org.apache.commons.httpclient.cookie.CookiePolicy;
 import org.apache.commons.httpclient.methods.GetMethod;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -186,11 +187,13 @@
     final HttpClient client = new HttpClient();
     client.setTimeout(3000);
     client.setConnectionTimeout(3000);
+    // see http://hc.apache.org/httpclient-3.x/cookies.html
+    client.getParams().setCookiePolicy(CookiePolicy.BROWSER_COMPATIBILITY);
     try {
       final GetMethod method = new GetMethod(url);
       final int code = client.executeMethod(method);
 
-      return code == HttpStatus.SC_OK || code == HttpStatus.SC_REQUEST_TIMEOUT 
+      return code == HttpStatus.SC_OK || code == HttpStatus.SC_REQUEST_TIMEOUT
              ? MyFetchResult.OK 
              : MyFetchResult.NONEXISTENCE;
     }
diff --git a/platform/lang-impl/src/com/intellij/openapi/vcs/impl/CodeSmellDetectorImpl.java b/platform/lang-impl/src/com/intellij/openapi/vcs/impl/CodeSmellDetectorImpl.java
index 4338dd2..48d7208 100644
--- a/platform/lang-impl/src/com/intellij/openapi/vcs/impl/CodeSmellDetectorImpl.java
+++ b/platform/lang-impl/src/com/intellij/openapi/vcs/impl/CodeSmellDetectorImpl.java
@@ -18,10 +18,7 @@
 import com.intellij.codeInsight.CodeSmellInfo;
 import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
 import com.intellij.codeInsight.daemon.HighlightDisplayKey;
-import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerImpl;
-import com.intellij.codeInsight.daemon.impl.HighlightInfo;
-import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.*;
 import com.intellij.ide.errorTreeView.NewErrorTreeViewPanel;
 import com.intellij.lang.annotation.HighlightSeverity;
 import com.intellij.openapi.application.ApplicationManager;
@@ -176,7 +173,7 @@
     if (highlights == null) return;
     for (HighlightInfo highlightInfo : highlights) {
       final HighlightSeverity severity = highlightInfo.getSeverity();
-      if (SeverityUtil.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.WARNING) >= 0) {
+      if (SeverityRegistrar.getSeverityRegistrar(myProject).compare(severity, HighlightSeverity.WARNING) >= 0) {
         result.add(new CodeSmellInfo(document, getDescription(highlightInfo),
                                      new TextRange(highlightInfo.startOffset, highlightInfo.endOffset), severity));
       }
diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java
index 1673bbf..e82c7fe 100644
--- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java
+++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedLanguageUtil.java
@@ -123,8 +123,14 @@
     }
     List<Pair<Place, PsiFile>> places = registrar.getResult();
     for (Pair<Place, PsiFile> pair : places) {
-      PsiFile injectedPsi = pair.second;
-      visitor.visit(injectedPsi, pair.first);
+      if (visitor instanceof InjectedReferenceVisitor) {
+        if (registrar.getReferenceInjector() != null) {
+          ((InjectedReferenceVisitor)visitor).visitInjectedReference(registrar.getReferenceInjector(), pair.first);
+        }
+      }
+      else if (pair.second != null) {
+        visitor.visit(pair.second, pair.first);
+      }
     }
   }
 
diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedReferenceVisitor.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedReferenceVisitor.java
new file mode 100644
index 0000000..db83a4e
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/InjectedReferenceVisitor.java
@@ -0,0 +1,34 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.impl.source.tree.injected;
+
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiLanguageInjectionHost;
+import com.intellij.psi.injection.ReferenceInjector;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.List;
+
+/**
+ * @author Dmitry Avdeev
+ *         Date: 13.08.13
+ */
+public abstract class InjectedReferenceVisitor implements PsiLanguageInjectionHost.InjectedPsiVisitor {
+  @Override
+  public void visit(@NotNull PsiFile injectedPsi, @NotNull List<PsiLanguageInjectionHost.Shred> places) {}
+
+  public abstract void visitInjectedReference(@NotNull ReferenceInjector injector, @NotNull List<PsiLanguageInjectionHost.Shred> places);
+}
diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java
index 6d6778a..8df0bf2 100644
--- a/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java
+++ b/platform/lang-impl/src/com/intellij/psi/impl/source/tree/injected/MultiHostRegistrarImpl.java
@@ -50,6 +50,7 @@
 import com.intellij.psi.impl.source.tree.LeafElement;
 import com.intellij.psi.impl.source.tree.TreeElement;
 import com.intellij.psi.impl.source.tree.TreeUtil;
+import com.intellij.psi.injection.ReferenceInjector;
 import com.intellij.psi.tree.IElementType;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtilCore;
@@ -79,6 +80,7 @@
   private final VirtualFile myHostVirtualFile;
   private final PsiElement myContextElement;
   private final PsiFile myHostPsiFile;
+  private ReferenceInjector myReferenceInjector;
 
   MultiHostRegistrarImpl(@NotNull Project project,
                          @NotNull PsiFile hostPsiFile,
@@ -115,7 +117,12 @@
     }
 
     if (LanguageParserDefinitions.INSTANCE.forLanguage(language) == null) {
-      throw new UnsupportedOperationException("Cannot inject language '" + language + "' since its getParserDefinition() returns null");
+      ReferenceInjector injector = ReferenceInjector.findById(language.getID());
+      if (injector == null) {
+        throw new UnsupportedOperationException("Cannot inject language '" + language + "' since its getParserDefinition() returns null");
+      }
+      myLanguage = null;
+      myReferenceInjector = injector;
     }
     myLanguage = language;
 
@@ -148,7 +155,7 @@
       throw new IllegalArgumentException("rangeInsideHost must lie within host text range. rangeInsideHost:"+rangeInsideHost+"; host textRange:"+
                                          hostTextRange);
     }
-    if (myLanguage == null) {
+    if (myLanguage == null && myReferenceInjector == null) {
       clear();
       throw new IllegalStateException("Seems you haven't called startInjecting()");
     }
@@ -192,6 +199,10 @@
       if (shreds.isEmpty()) {
         throw new IllegalStateException("Seems you haven't called addPlace()");
       }
+      if (myReferenceInjector != null) {
+        addToResults(new Place(shreds), null);
+        return;
+      }
       PsiDocumentManagerImpl documentManager = (PsiDocumentManagerImpl)PsiDocumentManager.getInstance(myProject);
       //todo restore
       //assert !documentManager.getUncommittedDocumentsUnsafe().contains(myHostDocument) : "document is uncommitted: "+myHostDocument;
@@ -354,7 +365,12 @@
     PsiDocumentManagerImpl.checkConsistency(psiFile, documentWindow);
   }
 
-  void addToResults(Place place, PsiFile psiFile) {
+  void addToResults(Place place, PsiFile psiFile, MultiHostRegistrarImpl from) {
+    addToResults(place, psiFile);
+    myReferenceInjector = from.myReferenceInjector;
+  }
+
+  private void addToResults(Place place, PsiFile psiFile) {
     if (result == null) {
       result = new SmartList<Pair<Place, PsiFile>>();
     }
@@ -527,4 +543,8 @@
   public PsiFile getHostPsiFile() {
     return myHostPsiFile;
   }
+
+  public ReferenceInjector getReferenceInjector() {
+    return myReferenceInjector;
+  }
 }
diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
index fde67af..744f910 100644
--- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
+++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
@@ -19,7 +19,6 @@
  */
 package com.intellij.psi.stubs;
 
-import com.intellij.lang.LangBundle;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.components.*;
@@ -29,7 +28,6 @@
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.ThrowableComputable;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.newvfs.ManagingFS;
@@ -140,20 +138,13 @@
 
     for (int attempt = 0; attempt < 2; attempt++) {
       try {
-        final MapIndexStorage<K, StubIdList> storage = ProgressManager
-          .getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<MapIndexStorage<K, StubIdList>, IOException>() {
-            @Override
-            public MapIndexStorage<K, StubIdList> compute() throws IOException {
-              FileBasedIndexImpl.configureIndexDataLoadingProgress(ProgressManager.getInstance().getProgressIndicator());
+        final MapIndexStorage<K, StubIdList> storage = new MapIndexStorage<K, StubIdList>(
+          IndexInfrastructure.getStorageFile(indexKey),
+          extension.getKeyDescriptor(),
+          new StubIdExternalizer(),
+          extension.getCacheSize()
+        );
 
-              return new MapIndexStorage<K, StubIdList>(
-                IndexInfrastructure.getStorageFile(indexKey),
-                extension.getKeyDescriptor(),
-                new StubIdExternalizer(),
-                extension.getCacheSize()
-              );
-            }
-          }, LangBundle.message("compacting.indices.title"), false, null);
         final MemoryIndexStorage<K, StubIdList> memStorage = new MemoryIndexStorage<K, StubIdList>(storage);
         myIndices.put(indexKey, new MyIndex<K>(memStorage));
         break;
diff --git a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java
index 546ebf8..3848f14 100644
--- a/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java
+++ b/platform/lang-impl/src/com/intellij/psi/templateLanguages/TemplateLanguageErrorQuickFixProvider.java
@@ -38,7 +38,7 @@
 public class TemplateLanguageErrorQuickFixProvider implements ErrorQuickFixProvider{
 
   @Override
-  public void registerErrorQuickFix(final PsiErrorElement errorElement, final HighlightInfo highlightInfo) {
+  public void registerErrorQuickFix(@NotNull final PsiErrorElement errorElement, @NotNull final HighlightInfo highlightInfo) {
     final PsiFile psiFile = errorElement.getContainingFile();
     final FileViewProvider provider = psiFile.getViewProvider();
     if (!(provider instanceof TemplateLanguageFileViewProvider)) return;
diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java
index 5517405..c4ca070 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java
@@ -57,6 +57,7 @@
   private final boolean mySearchInComments;
   private final boolean mySearchInNonJavaFiles;
   private final Map<PsiFile, TargetDirectoryWrapper> myFilesToMove;
+  private final Map<PsiDirectory, TargetDirectoryWrapper> myNestedDirsToMove;
   private NonCodeUsageInfo[] myNonCodeUsages;
   private final MoveCallback myMoveCallback;
 
@@ -84,8 +85,9 @@
     mySearchInNonJavaFiles = searchInNonJavaFiles;
     myMoveCallback = moveCallback;
     myFilesToMove = new HashMap<PsiFile, TargetDirectoryWrapper>();
+    myNestedDirsToMove = new HashMap<PsiDirectory, TargetDirectoryWrapper>();
     for (PsiDirectory dir : directories) {
-      collectFiles2Move(myFilesToMove, dir, includeSelf ? dir.getParentDirectory() : dir, getTargetDirectory(dir));
+      collectFiles2Move(myFilesToMove, myNestedDirsToMove, dir, includeSelf ? dir.getParentDirectory() : dir, getTargetDirectory(dir));
     }
   }
 
@@ -140,6 +142,11 @@
       for (PsiDirectory directory : myDirectories) {
         getResultDirectory(directory).findOrCreateTargetDirectory();
       }
+
+      for (PsiDirectory directory : myNestedDirsToMove.keySet()) {
+        myNestedDirsToMove.get(directory).findOrCreateTargetDirectory();
+      }
+
       for (PsiFile psiFile : myFilesToMove.keySet()) {
         myFilesToMove.get(psiFile).findOrCreateTargetDirectory();
       }
@@ -212,21 +219,23 @@
   }
 
   private static void collectFiles2Move(Map<PsiFile, TargetDirectoryWrapper> files2Move,
-                                     PsiDirectory directory,
-                                     PsiDirectory rootDirectory,
-                                     @NotNull TargetDirectoryWrapper targetDirectory) {
+                                        Map<PsiDirectory, TargetDirectoryWrapper> nestedDirsToMove,
+                                        PsiDirectory directory,
+                                        PsiDirectory rootDirectory,
+                                        @NotNull TargetDirectoryWrapper targetDirectory) {
     final PsiElement[] children = directory.getChildren();
     final String relativePath = VfsUtilCore.getRelativePath(directory.getVirtualFile(), rootDirectory.getVirtualFile(), '/');
 
     final TargetDirectoryWrapper newTargetDirectory = relativePath.length() == 0
                                                       ? targetDirectory
                                                       : targetDirectory.findOrCreateChild(relativePath);
+    nestedDirsToMove.put(directory, newTargetDirectory);
     for (PsiElement child : children) {
       if (child instanceof PsiFile) {
         files2Move.put((PsiFile)child, newTargetDirectory);
       }
       else if (child instanceof PsiDirectory){
-        collectFiles2Move(files2Move, (PsiDirectory)child, directory, newTargetDirectory);
+        collectFiles2Move(files2Move, nestedDirsToMove, (PsiDirectory)child, directory, newTargetDirectory);
       }
     }
   }
diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameToIgnoredDirectoryFileInputValidator.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameToIgnoredDirectoryFileInputValidator.java
index 64b8136..8af7040 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameToIgnoredDirectoryFileInputValidator.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameToIgnoredDirectoryFileInputValidator.java
@@ -46,6 +46,6 @@
 
   @Override
   public boolean isInputValid(String newName, PsiElement element, ProcessingContext context) {
-    return newName != null && newName.length() > 0 && newName.indexOf('\\') < 0 && newName.indexOf('/') < 0;
+    return newName != null && newName.length() > 0 && newName.indexOf('\\') < 0 && newName.indexOf('/') < 0 && newName.indexOf('\n') < 0;
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java
index 05ef6ac..1ff5776 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/InplaceRefactoring.java
@@ -72,6 +72,7 @@
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.ui.awt.RelativePoint;
+import com.intellij.ui.popup.PopupFactoryImpl;
 import com.intellij.util.CommonProcessors;
 import com.intellij.util.Query;
 import com.intellij.util.containers.Stack;
@@ -755,14 +756,15 @@
     if (ApplicationManager.getApplication().isHeadlessEnvironment()) return;
     final BalloonBuilder balloonBuilder = JBPopupFactory.getInstance().createDialogBalloonBuilder(component, null).setSmallVariant(true);
     myBalloon = balloonBuilder.createBalloon();
+    final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
     Disposer.register(myProject, myBalloon);
     Disposer.register(myBalloon, new Disposable() {
       @Override
       public void dispose() {
         releaseIfNotRestart();
+        topLevelEditor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION, null);
       }
     });
-    final Editor topLevelEditor = InjectedLanguageUtil.getTopLevelEditor(myEditor);
     topLevelEditor.getScrollingModel().scrollToCaret(ScrollType.MAKE_VISIBLE);
     final JBPopupFactory popupFactory = JBPopupFactory.getInstance();
     myBalloon.show(new PositionTracker<Balloon>(topLevelEditor.getContentComponent()) {
@@ -771,8 +773,11 @@
         if (myTarget != null && !popupFactory.isBestPopupLocationVisible(topLevelEditor)) {
           return myTarget;
         }
+        if (myCaretRangeMarker != null && myCaretRangeMarker.isValid()) {
+          topLevelEditor.putUserData(PopupFactoryImpl.ANCHOR_POPUP_POSITION,
+                                     topLevelEditor.offsetToVisualPosition(myCaretRangeMarker.getStartOffset()));
+        }
         final RelativePoint target = popupFactory.guessBestPopupLocation(topLevelEditor);
-        if (target == null) return myTarget;
         final Point screenPoint = target.getScreenPoint();
         int y = screenPoint.y;
         if (target.getPoint().getY() > topLevelEditor.getLineHeight() + myBalloon.getPreferredSize().getHeight()) {
diff --git a/platform/lang-impl/src/com/intellij/tools/Tool.java b/platform/lang-impl/src/com/intellij/tools/Tool.java
index cfe34c1..ab59802 100644
--- a/platform/lang-impl/src/com/intellij/tools/Tool.java
+++ b/platform/lang-impl/src/com/intellij/tools/Tool.java
@@ -317,7 +317,7 @@
   @Nullable
   public GeneralCommandLine createCommandLine(DataContext dataContext) {
     if (StringUtil.isEmpty(getWorkingDirectory())) {
-      setWorkingDirectory(null);
+      setWorkingDirectory("$ProjectFileDir$");
     }
 
     GeneralCommandLine commandLine = new GeneralCommandLine();
diff --git a/platform/lang-impl/src/com/intellij/tools/ToolRunProfile.java b/platform/lang-impl/src/com/intellij/tools/ToolRunProfile.java
index d8409d3..cc7598b 100644
--- a/platform/lang-impl/src/com/intellij/tools/ToolRunProfile.java
+++ b/platform/lang-impl/src/com/intellij/tools/ToolRunProfile.java
@@ -19,7 +19,10 @@
 import com.intellij.execution.ExecutionManager;
 import com.intellij.execution.ExecutionResult;
 import com.intellij.execution.Executor;
-import com.intellij.execution.configurations.*;
+import com.intellij.execution.configurations.CommandLineState;
+import com.intellij.execution.configurations.GeneralCommandLine;
+import com.intellij.execution.configurations.ModuleRunProfile;
+import com.intellij.execution.configurations.RunProfileState;
 import com.intellij.execution.filters.RegexpFilter;
 import com.intellij.execution.filters.TextConsoleBuilder;
 import com.intellij.execution.filters.TextConsoleBuilderFactory;
@@ -129,8 +132,8 @@
     };
     TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
     final FilterInfo[] outputFilters = myTool.getOutputFilters();
-    for (int i = 0; i < outputFilters.length; i++) {
-      builder.addFilter(new RegexpFilter(project, outputFilters[i].getRegExp()));
+    for (FilterInfo outputFilter : outputFilters) {
+      builder.addFilter(new RegexpFilter(project, outputFilter.getRegExp()));
     }
 
     commandLineState.setConsoleBuilder(builder);
diff --git a/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java b/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java
index 5e4c12f..169b11c 100644
--- a/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java
+++ b/platform/lang-impl/src/com/intellij/unscramble/AnalyzeStacktraceUtil.java
@@ -19,7 +19,9 @@
 import com.intellij.execution.ExecutionManager;
 import com.intellij.execution.Executor;
 import com.intellij.execution.executors.DefaultRunExecutor;
-import com.intellij.execution.filters.*;
+import com.intellij.execution.filters.Filter;
+import com.intellij.execution.filters.TextConsoleBuilder;
+import com.intellij.execution.filters.TextConsoleBuilderFactory;
 import com.intellij.execution.impl.ConsoleViewImpl;
 import com.intellij.execution.ui.ConsoleView;
 import com.intellij.execution.ui.ConsoleViewContentType;
@@ -91,9 +93,7 @@
                                                 String text,
                                                 @Nullable Icon icon) {
     final TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
-    for(Filter filter: Extensions.getExtensions(EP_NAME, project)) {
-      builder.addFilter(filter);
-    }
+    builder.filters(Extensions.getExtensions(EP_NAME, project));
     final ConsoleView consoleView = builder.getConsole();
 
     final DefaultActionGroup toolbarActions = new DefaultActionGroup();
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
index e0671c4..642c455 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
@@ -21,11 +21,13 @@
 import com.intellij.ide.caches.CacheUpdater;
 import com.intellij.ide.util.DelegatingProgressIndicator;
 import com.intellij.lang.ASTNode;
-import com.intellij.lang.LangBundle;
 import com.intellij.notification.NotificationDisplayType;
 import com.intellij.notification.NotificationGroup;
 import com.intellij.notification.NotificationType;
-import com.intellij.openapi.application.*;
+import com.intellij.openapi.application.ApplicationAdapter;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.ModalityState;
+import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.highlighter.EditorHighlighter;
@@ -39,7 +41,6 @@
 import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.progress.*;
 import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
-import com.intellij.openapi.progress.util.ProgressWindow;
 import com.intellij.openapi.project.*;
 import com.intellij.openapi.roots.*;
 import com.intellij.openapi.util.*;
@@ -80,7 +81,8 @@
 import java.lang.ref.SoftReference;
 import java.lang.ref.WeakReference;
 import java.util.*;
-import java.util.concurrent.*;
+import java.util.concurrent.ConcurrentLinkedQueue;
+import java.util.concurrent.ScheduledFuture;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicInteger;
 import java.util.concurrent.atomic.AtomicReference;
@@ -94,7 +96,6 @@
   private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.FileBasedIndexImpl");
   @NonNls
   private static final String CORRUPTION_MARKER_NAME = "corruption.marker";
-  private static final int PROGRESS_DELAY_IN_MILLIS = 1000;
   private final Map<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>> myIndices =
     new THashMap<ID<?, ?>, Pair<UpdatableIndex<?, ?, FileContent>, InputFilter>>();
   private final List<ID<?, ?>> myIndicesWithoutFileTypeInfo = new ArrayList<ID<?, ?>>();
@@ -407,20 +408,13 @@
     final ID<K, V> name = extension.getName();
     for (int attempt = 0; attempt < 2; attempt++) {
       try {
-        storage = ProgressManager
-          .getInstance().runProcessWithProgressSynchronously(new ThrowableComputable<MapIndexStorage<K, V>, IOException>() {
-          @Override
-          public MapIndexStorage<K, V> compute() throws IOException {
-            configureIndexDataLoadingProgress(ProgressManager.getInstance().getProgressIndicator());
-            return new MapIndexStorage<K, V>(
-              IndexInfrastructure.getStorageFile(name),
-              extension.getKeyDescriptor(),
-              extension.getValueExternalizer(),
-              extension.getCacheSize(),
-              extension.isKeyHighlySelective()
-            );
-          }
-        }, LangBundle.message("compacting.indices.title"), false, null);
+        storage = new MapIndexStorage<K, V>(
+          IndexInfrastructure.getStorageFile(name),
+          extension.getKeyDescriptor(),
+          extension.getValueExternalizer(),
+          extension.getCacheSize(),
+          extension.isKeyHighlySelective()
+        );
 
         final MemoryIndexStorage<K, V> memStorage = new MemoryIndexStorage<K, V>(storage);
         final UpdatableIndex<K, V, FileContent> index = createIndex(name, extension, memStorage);
@@ -540,43 +534,7 @@
       @Override
       public PersistentHashMap<Integer, Collection<K>> create() {
         try {
-          final ThrowableComputable<PersistentHashMap<Integer, Collection<K>>, IOException> process =
-            new ThrowableComputable<PersistentHashMap<Integer, Collection<K>>, IOException>() {
-              @Override
-              public PersistentHashMap<Integer, Collection<K>> compute() throws IOException {
-                return createIdToDataKeysIndex(indexId, keyDescriptor, storage);
-              }
-            };
-          if (!index.needsCompaction()) {
-            return process.compute();
-          }
-          // this factory method may be called either on index creation from dispatch thread, or on index rebuild
-          // from arbitrary thread and under some existing progress indicator
-          final ProgressManager progressManager = ProgressManager.getInstance();
-          final ProgressIndicator currentProgress = progressManager.getProgressIndicator();
-          if (currentProgress == null && ApplicationManager.getApplication().isDispatchThread()) {
-            return progressManager.runProcessWithProgressSynchronously(
-              new ThrowableComputable<PersistentHashMap<Integer, Collection<K>>, IOException>() {
-                @Override
-                public PersistentHashMap<Integer, Collection<K>> compute() throws IOException {
-                  configureIndexDataLoadingProgress(progressManager.getProgressIndicator());
-                  return process.compute();
-                }
-              }, LangBundle.message("compacting.indices.title"), false, null);
-          }
-          if (currentProgress != null)  {
-            // reuse existing progress indicator if available
-            currentProgress.pushState();
-            currentProgress.setText(LangBundle.message("compacting.indices.title"));
-          }
-          try {
-            return createIdToDataKeysIndex(indexId, keyDescriptor, storage);
-          }
-          finally {
-            if (currentProgress != null) {
-              currentProgress.popState();
-            }
-          }
+          return createIdToDataKeysIndex(indexId, keyDescriptor, storage);
         }
         catch (IOException e) {
           throw new RuntimeException(e);
@@ -587,13 +545,6 @@
     return index;
   }
 
-  public static void configureIndexDataLoadingProgress(ProgressIndicator indicator) {
-    if (indicator != null) {
-      indicator.setIndeterminate(true);
-      if (indicator instanceof ProgressWindow) ((ProgressWindow)indicator).setDelayInMillis(PROGRESS_DELAY_IN_MILLIS);
-    }
-  }
-
   @NotNull
   public static <K> PersistentHashMap<Integer, Collection<K>> createIdToDataKeysIndex(@NotNull final ID<K, ?> indexId,
                                                                                       @NotNull final KeyDescriptor<K> keyDescriptor,
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
index f13a95b..e93ca8b 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
@@ -50,7 +50,6 @@
   private final ReentrantReadWriteLock myLock = new ReentrantReadWriteLock();
 
   private Factory<PersistentHashMap<Integer, Collection<Key>>> myInputsIndexFactory;
-  private boolean myNeedsCompaction = true;
 
   public MapReduceIndex(@Nullable final ID<Key, Value> indexId, DataIndexer<Key, Value, Input> indexer, @NotNull IndexStorage<Key, Value> storage) {
     myIndexId = indexId;
@@ -76,8 +75,6 @@
         catch (IOException ignored) {
         }
 
-        // if we clear index (at arbitrary moment of time) we should run without progress to avoid modality switching issues: IDEA-107265
-        myNeedsCompaction = false;
         FileUtil.delete(baseFile);
         myInputsIndex = createInputsIndex();
       }
@@ -89,7 +86,6 @@
       LOG.error(e);
     }
     finally {
-      myNeedsCompaction = true;
       getWriteLock().unlock();
     }
   }
@@ -299,8 +295,4 @@
       getWriteLock().unlock();
     }
   }
-
-  public boolean needsCompaction() {
-    return myNeedsCompaction;
-  }
 }
diff --git a/platform/platform-api/src/com/intellij/ide/ui/UISettings.java b/platform/platform-api/src/com/intellij/ide/ui/UISettings.java
index 6d8ae2d..e62921d 100644
--- a/platform/platform-api/src/com/intellij/ide/ui/UISettings.java
+++ b/platform/platform-api/src/com/intellij/ide/ui/UISettings.java
@@ -65,7 +65,7 @@
   public boolean ANIMATE_WINDOWS = true;
   public int ANIMATION_SPEED = 2000; // Pixels per second
   public boolean SHOW_TOOL_WINDOW_NUMBERS = true;
-  public boolean HIDE_TOOL_STRIPES = false;
+  public boolean HIDE_TOOL_STRIPES = true;
   public boolean WIDESCREEN_SUPPORT = false;
   public boolean SHOW_MEMORY_INDICATOR = false;
   public boolean ALLOW_MERGE_BUTTONS = true;
diff --git a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java
index 3ff15f9..d9db7d6 100644
--- a/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java
+++ b/platform/platform-api/src/com/intellij/ide/util/treeView/AbstractTreeUpdater.java
@@ -17,8 +17,6 @@
 package com.intellij.ide.util.treeView;
 
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.application.Application;
-import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProcessCanceledException;
@@ -26,7 +24,6 @@
 import com.intellij.openapi.util.Disposer;
 import com.intellij.ui.treeStructure.treetable.TreeTableTree;
 import com.intellij.util.Alarm;
-import com.intellij.util.ui.UIUtil;
 import com.intellij.util.ui.update.Activatable;
 import com.intellij.util.ui.update.MergingUpdateQueue;
 import com.intellij.util.ui.update.UiNotifyConnector;
@@ -120,7 +117,7 @@
     if (myReleaseRequested) return;
 
     assert !toAdd.isExpired();
-    
+
     final AbstractTreeUi ui = myTreeBuilder.getUi();
 
     if (ui.isUpdatingChildrenNow(toAdd.getNode())) {
@@ -301,20 +298,6 @@
     return myTreeBuilder.getUi() == null;
   }
 
-  protected void invokeLater(Runnable runnable) {
-    if (myTreeBuilder.getUi().isPassthroughMode()) {
-      runnable.run();
-    } else {
-      final Application app = ApplicationManager.getApplication();
-      if (app != null) {
-        app.invokeLater(runnable);
-      }
-      else {
-        UIUtil.invokeAndWaitIfNeeded(runnable);
-      }
-    }
-  }
-
   protected ActionCallback beforeUpdate(TreeUpdatePass pass) {
     return new ActionCallback.Done();
   }
diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/AnAction.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/AnAction.java
index c19a51b..87bfa50 100644
--- a/platform/platform-api/src/com/intellij/openapi/actionSystem/AnAction.java
+++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/AnAction.java
@@ -16,12 +16,11 @@
 package com.intellij.openapi.actionSystem;
 
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.project.DumbAware;
 import com.intellij.openapi.project.PossiblyDumbAware;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.IncorrectOperationException;
 import org.intellij.lang.annotations.JdkConstants;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -157,7 +156,7 @@
 
   public final void registerCustomShortcutSet(int keyCode, @JdkConstants.InputEventMask int modifiers, @Nullable JComponent component) {
     registerCustomShortcutSet(new CustomShortcutSet(KeyStroke.getKeyStroke(keyCode, modifiers)), component);
-  } 
+  }
 
   public final void registerCustomShortcutSet(@NotNull ShortcutSet shortcutSet, @NotNull final JComponent component, @NotNull Disposable parentDisposable) {
     registerCustomShortcutSet(shortcutSet, component);
@@ -272,16 +271,11 @@
     myShortcutSet = shortcutSet;
   }
 
+  /**
+   * @deprecated Use KeymapUtil.createTooltipText()
+   */
   public static String createTooltipText(String s, @NotNull AnAction action) {
-    String toolTipText = s == null ? "" : s;
-    while (StringUtil.endsWithChar(toolTipText, '.')) {
-      toolTipText = toolTipText.substring(0, toolTipText.length() - 1);
-    }
-    String shortcutsText = KeymapUtil.getFirstKeyboardShortcutText(action);
-    if (!shortcutsText.isEmpty()) {
-      toolTipText += " (" + shortcutsText + ")";
-    }
-    return toolTipText;
+    throw new IncorrectOperationException("Please use KeymapUtil.createTooltipText()");
   }
 
   /**
diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortcut.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortcut.java
index 34c99e5..8be4cab 100644
--- a/platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortcut.java
+++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/KeyboardModifierGestureShortcut.java
@@ -15,6 +15,8 @@
  */
 package com.intellij.openapi.actionSystem;
 
+import com.intellij.openapi.keymap.KeymapUtil;
+
 import javax.swing.*;
 
 public class KeyboardModifierGestureShortcut extends Shortcut {
@@ -96,4 +98,11 @@
       super(stroke, KeyboardGestureAction.ModifierType.hold);
     }
   }
+
+  @Override
+  public String toString() {
+    String s = getType() == KeyboardGestureAction.ModifierType.dblClick ? "Press, release and hold " : "Hold ";
+    s += KeymapUtil.getKeystrokeText(this.getStroke());
+    return s;
+  }
 }
diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java
index 8c3dd81..2d9f037 100644
--- a/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java
+++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/ex/ComboBoxAction.java
@@ -18,6 +18,7 @@
 import com.intellij.icons.AllIcons;
 import com.intellij.ide.DataManager;
 import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.ui.popup.JBPopup;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.openapi.ui.popup.ListPopup;
@@ -267,7 +268,7 @@
     }
 
     private void updateTooltipText(String description) {
-      String tooltip = AnAction.createTooltipText(description, ComboBoxAction.this);
+      String tooltip = KeymapUtil.createTooltipText(description, ComboBoxAction.this);
       setToolTipText(!tooltip.isEmpty() ? tooltip : null);
     }
 
diff --git a/platform/platform-api/src/com/intellij/openapi/keymap/KeymapUtil.java b/platform/platform-api/src/com/intellij/openapi/keymap/KeymapUtil.java
index 47253b4..670cf3a 100644
--- a/platform/platform-api/src/com/intellij/openapi/keymap/KeymapUtil.java
+++ b/platform/platform-api/src/com/intellij/openapi/keymap/KeymapUtil.java
@@ -23,6 +23,7 @@
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.registry.RegistryValue;
 import com.intellij.openapi.util.registry.RegistryValueListener;
+import com.intellij.openapi.util.text.StringUtil;
 import org.intellij.lang.annotations.JdkConstants;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -148,7 +149,7 @@
 
     final int code = accelerator.getKeyCode();
     String keyText = SystemInfo.isMac ? MacKeymapUtil.getKeyText(code) : KeyEvent.getKeyText(code);
-    // [vova] this is dirty fix for bug #35092 
+    // [vova] this is dirty fix for bug #35092
     if(CANCEL_KEY_TEXT.equals(keyText)){
       keyText = BREAK_KEY_TEXT;
     }
@@ -329,7 +330,7 @@
   public static boolean isEmacsKeymap() {
     return isEmacsKeymap(KeymapManager.getInstance().getActiveKeymap());
   }
-  
+
   public static boolean isEmacsKeymap(@Nullable Keymap keymap) {
     for (; keymap != null; keymap = keymap.getParent()) {
       if ("Emacs".equalsIgnoreCase(keymap.getName())) {
@@ -349,4 +350,17 @@
     }
     return shortcut.getFirstKeyStroke();
   }
+
+  @NotNull
+  public static String createTooltipText(@Nullable String name, @NotNull AnAction action) {
+    String toolTipText = name == null ? "" : name;
+    while (StringUtil.endsWithChar(toolTipText, '.')) {
+      toolTipText = toolTipText.substring(0, toolTipText.length() - 1);
+    }
+    String shortcutsText = getFirstKeyboardShortcutText(action);
+    if (!shortcutsText.isEmpty()) {
+      toolTipText += " (" + shortcutsText + ")";
+    }
+    return toolTipText;
+  }
 }
diff --git a/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java b/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java
index 4c9f51d..cd89fcda 100644
--- a/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java
+++ b/platform/platform-api/src/com/intellij/openapi/options/CompositeSettingsEditor.java
@@ -101,7 +101,6 @@
   }
 
   public void disposeEditor() {
-    Disposer.dispose(this);
     myIsDisposed = true;
   }
 
diff --git a/platform/platform-api/src/com/intellij/openapi/options/SettingsEditor.java b/platform/platform-api/src/com/intellij/openapi/options/SettingsEditor.java
index 30b1247..372467d 100644
--- a/platform/platform-api/src/com/intellij/openapi/options/SettingsEditor.java
+++ b/platform/platform-api/src/com/intellij/openapi/options/SettingsEditor.java
@@ -43,7 +43,9 @@
 
   @NotNull
   protected abstract JComponent createEditor();
-  protected abstract void disposeEditor();
+
+  protected void disposeEditor() {
+  }
 
   public SettingsEditor() {
     this(null);
diff --git a/platform/platform-api/src/com/intellij/openapi/options/SettingsEditorGroup.java b/platform/platform-api/src/com/intellij/openapi/options/SettingsEditorGroup.java
index e987ab2..60abc11 100644
--- a/platform/platform-api/src/com/intellij/openapi/options/SettingsEditorGroup.java
+++ b/platform/platform-api/src/com/intellij/openapi/options/SettingsEditorGroup.java
@@ -49,7 +49,4 @@
   public JComponent createEditor() {
     throw new UnsupportedOperationException("This method should never be called!");
   }
-
-  public void disposeEditor() {
-  }
 }
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
index 7aad006..550465e 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
@@ -86,7 +86,7 @@
    */
   public static final int CLOSE_EXIT_CODE = CANCEL_EXIT_CODE;
   /**
-   * If you use your custom exit codes you have have to start them with
+   * If you use your own custom exit codes you have to start them with
    * this constant.
    */
   public static final int NEXT_USER_EXIT_CODE = 2;
@@ -1510,7 +1510,7 @@
         result.setDone(isOK());
       }
     });
-      
+
     myPeer.show();
 
     return result;
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java
index ffa93cc..e33f9d9 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java
@@ -481,7 +481,7 @@
     showDialog(message, title, new String[]{OK_BUTTON}, 0, getErrorIcon());
   }
 
-  public static void showWarningDialog(Project project, String message, String title) {
+  public static void showWarningDialog(@Nullable Project project, String message, String title) {
     if (canShowMacSheetPanel()) {
       MacMessages.getInstance().showErrorDialog(CommonBundle.getWarningTitle(), message, OK_BUTTON, WindowManager.getInstance().suggestParentWindow(project));
       return;
diff --git a/platform/platform-api/src/com/intellij/ui/PortField.java b/platform/platform-api/src/com/intellij/ui/PortField.java
index 6d139fb..5c96d65 100644
--- a/platform/platform-api/src/com/intellij/ui/PortField.java
+++ b/platform/platform-api/src/com/intellij/ui/PortField.java
@@ -38,4 +38,8 @@
   public int getNumber() {
     return ((SpinnerNumberModel)getModel()).getNumber().intValue();
   }
+
+  public boolean isSpecified() {
+    return getNumber() != 0;
+  }
 }
\ No newline at end of file
diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/ActionButton.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/ActionButton.java
index 514b571..cafd9b6 100644
--- a/platform/platform-api/src/com/intellij/ui/tabs/impl/ActionButton.java
+++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/ActionButton.java
@@ -18,6 +18,7 @@
 import com.intellij.ide.DataManager;
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.actionSystem.ex.ActionUtil;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.ui.popup.IconButton;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Pass;
@@ -62,13 +63,13 @@
   public InplaceButton getComponent() {
     return myButton;
   }
-  
+
   protected void repaintComponent(Component c) {
     c.repaint();
   }
 
   public void setMouseDeadZone(TimedDeadzone.Length deadZone) {
-    myButton.setMouseDeadzone(deadZone);    
+    myButton.setMouseDeadzone(deadZone);
   }
 
   public boolean update() {
@@ -84,7 +85,7 @@
 
     if (changed) {
       myButton.setIcons(this);
-      String tooltipText = AnAction.createTooltipText(p.getText(), myAction);
+      String tooltipText = KeymapUtil.createTooltipText(p.getText(), myAction);
       myButton.setToolTipText(tooltipText.length() > 0 ? tooltipText : null);
       myButton.setVisible(p.isEnabled() && p.isVisible());
     }
diff --git a/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java b/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java
index 6be85ea..94a0f4b 100644
--- a/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java
+++ b/platform/platform-impl/src/com/intellij/execution/process/ScriptRunnerUtil.java
@@ -31,6 +31,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import java.io.File;
+import java.nio.charset.Charset;
 
 /**
  * @author Elena Shaverdova
@@ -114,6 +115,15 @@
                                          @Nullable String workingDirectory,
                                          @Nullable VirtualFile scriptFile,
                                          String[] parameters) throws ExecutionException {
+    return execute(exePath, workingDirectory, scriptFile, parameters, null);
+  }
+
+  @NotNull
+  public static OSProcessHandler execute(@NotNull String exePath,
+                                         @Nullable String workingDirectory,
+                                         @Nullable VirtualFile scriptFile,
+                                         String[] parameters,
+                                         @Nullable Charset charset) throws ExecutionException {
     GeneralCommandLine commandLine = new GeneralCommandLine();
     commandLine.setExePath(exePath);
     commandLine.setPassParentEnvironment(true);
@@ -130,7 +140,9 @@
     LOG.debug("Command line env: " + commandLine.getEnvironment());
 
     final OSProcessHandler processHandler = new ColoredProcessHandler(commandLine.createProcess(), commandLine.getCommandLineString(),
-                                                                      EncodingManager.getInstance().getDefaultCharset());
+                                                                      charset == null
+                                                                      ? EncodingManager.getInstance().getDefaultCharset()
+                                                                      : charset);
     if (LOG.isDebugEnabled()) {
       processHandler.addProcessListener(new ProcessAdapter() {
         @Override
diff --git a/platform/platform-impl/src/com/intellij/help/impl/FXHelpBrowser.java b/platform/platform-impl/src/com/intellij/help/impl/FXHelpBrowser.java
deleted file mode 100644
index b32da95..0000000
--- a/platform/platform-impl/src/com/intellij/help/impl/FXHelpBrowser.java
+++ /dev/null
@@ -1,414 +0,0 @@
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-/*
-package com.intellij.help.impl;
-
-import com.intellij.openapi.application.impl.LaterInvocator;
-import com.intellij.openapi.diagnostic.Logger;
-import javafx.application.Platform;
-import javafx.beans.value.ChangeListener;
-import javafx.beans.value.ObservableValue;
-import javafx.embed.swing.JFXPanel;
-import javafx.event.ActionEvent;
-import javafx.event.EventHandler;
-import javafx.scene.Group;
-import javafx.scene.Scene;
-import javafx.scene.control.*;
-import javafx.scene.control.TextField;
-import javafx.scene.control.TreeItem;
-import javafx.scene.layout.HBox;
-import javafx.scene.layout.Priority;
-import javafx.scene.layout.Region;
-import javafx.scene.layout.VBox;
-import javafx.scene.paint.Color;
-import javafx.scene.web.WebEngine;
-import javafx.scene.web.WebView;
-import org.jetbrains.annotations.Nullable;
-import org.w3c.dom.Document;
-import org.xml.sax.Attributes;
-import org.xml.sax.SAXException;
-import org.xml.sax.helpers.DefaultHandler;
-
-import javax.help.*;
-import javax.help.search.*;
-import java.awt.Dialog;
-import java.awt.BorderLayout;
-import javax.swing.*;
-import javax.xml.parsers.ParserConfigurationException;
-import javax.xml.parsers.SAXParser;
-import javax.xml.parsers.SAXParserFactory;
-import java.io.IOException;
-import java.net.MalformedURLException;
-import java.net.URISyntaxException;
-import java.net.URL;
-import java.util.Enumeration;
-import java.util.Locale;
-
-*/
-/**
- * @author Denis.Fokin
- *//*
-
-
-public class FXHelpBrowser  implements SearchListener {
-
-  private static final Logger LOG = Logger.getInstance("#com.intellij.help.impl.FXHelpBrowser");
-
-  private TreeView<TOCItemWrapper> tocTreeView = null;
-  private ListView<SearchItemWrapper> searchResultsList = null;
-  private WebView webView = null;
-
-  final VBox bodyVBox = new VBox(5);
-  final HBox contentHBox = new HBox(5);
-  final HelpSet helpSet;
-  final JHelp jHelp;
-  final JDialog helpDialog;
-  final JFXPanel fxPanel;
-  WebEngine webEngine;
-
-  public FXHelpBrowser(HelpSet helpSet) {
-    this.helpSet = helpSet;
-    jHelp = new JHelp(helpSet);
-    helpDialog = new JDialog(null, jHelp.getModel().getDocumentTitle(), Dialog.ModalityType.MODELESS);
-    fxPanel = new JFXPanel();
-  }
-
-  private boolean isHelpBrowserInitialized = false;
-
-  private void initHelpBrowser () {
-    if (isHelpBrowserInitialized) return ;
-    Platform.runLater(new Runnable() {
-      @Override
-      public void run() {
-        tocTreeView = new TreeView<TOCItemWrapper>();
-        searchResultsList = new ListView<SearchItemWrapper>();
-        webView = new WebView();
-        isHelpBrowserInitialized = true;
-        webEngine = webView.getEngine();
-      }
-    });
-  }
-
-  void showDocumentation(@Nullable String id) {
-
-    initHelpBrowser();
-    loadPageInWebView(id);
-
-    URL url = null;
-
-    try {
-      url = new URL(helpSet.getHelpSetURL(), "HelpTOCij.xml");
-    }
-    catch (IOException e) {
-      LOG.error(e);
-    }
-
-    IdeaHelpTOCParser tocParser = new IdeaHelpTOCParser();
-    final TreeItem<TOCItemWrapper> rootNode = tocParser.parse(url);
-
-    Platform.runLater(new Runnable() {
-      public void run() {
-        initHelpDialog(rootNode);
-        packHelpDialogAndShowOnEDT();
-        tocTreeView.requestFocus();
-      }
-    });
-  }
-
-  private boolean isHelpDialogInitiated = false;
-
-  private void initHelpDialog(TreeItem<TOCItemWrapper> rootNode) {
-    if (isHelpDialogInitiated) return;
-
-    Group root = new Group();
-    Scene scene = new Scene(root, Color.ANTIQUEWHITE);
-
-    fxPanel.setScene(scene);
-
-    tocTreeView.setShowRoot(true);
-    tocTreeView.setRoot(rootNode);
-    rootNode.setExpanded(true);
-
-    tocTreeView.setMaxSize(Double.MAX_VALUE, Double.MAX_VALUE);
-    tocTreeView.setShowRoot(false);
-    tocTreeView.setEditable(false);
-    tocTreeView.getSelectionModel().setSelectionMode(SelectionMode.SINGLE);
-    tocTreeView.getSelectionModel().selectedItemProperty().addListener(new ChangeListener() {
-      @Override
-      public void changed(ObservableValue observable, Object oldValue,
-                          Object newValue) {
-        final TreeItem<TOCItemWrapper> item = tocTreeView.getSelectionModel().getSelectedItem();
-        if (item != null) {
-          webEngine.load(item.getValue().get().getURL().toString());
-        }
-      }
-    });
-
-    searchResultsList.getSelectionModel().selectedItemProperty().addListener(searchResultsListener);
-
-    contentHBox.getChildren().setAll(tocTreeView, webView);
-
-    HBox.setHgrow(tocTreeView, Priority.ALWAYS);
-
-    SearchField searchField = new SearchField();
-
-    bodyVBox.getChildren().addAll(searchField, contentHBox);
-
-    searchField.myField.setOnAction(new EventHandler<ActionEvent>() {
-      @Override
-      public void handle(ActionEvent event) {
-        SearchView searchView = (SearchView)helpSet.getNavigatorView("Search");
-        MergingSearchEngine search = new MergingSearchEngine(searchView);
-
-        try {
-
-          SearchQuery searchquery = search.createQuery();
-          searchquery.addSearchListener(FXHelpBrowser.this);
-
-
-          if (searchquery.isActive()) {
-            searchquery.stop();
-          }
-          searchquery.start("button", Locale.getDefault());
-        }
-        catch (Exception e) {
-          LOG.error(e);
-        }
-      }
-    });
-
-    Tab tab1 = new Tab();
-    tab1.setText("Search");
-
-    root.getChildren().add(bodyVBox);
-
-
-    isHelpDialogInitiated = true;
-  }
-
-  private void packHelpDialogAndShowOnEDT() {
-    LaterInvocator.invokeLater(new Runnable() {
-      @Override
-      public void run() {
-*/
-/*      helpDialog.invalidate();
-        helpDialog.validate();
-        helpDialog.repaint();*//*
-
-
-        helpDialog.getContentPane().add(fxPanel, BorderLayout.CENTER);
-        helpDialog.setDefaultCloseOperation(WindowConstants.DO_NOTHING_ON_CLOSE);
-
-        helpDialog.setSize(800, 600);
-        helpDialog.setVisible(true);
-      }
-    });
-  }
-
-  private void loadPageInWebView(@Nullable final String id) {
-
-    jHelp.setCurrentID(id);
-    final URL currentURL = jHelp.getModel().getCurrentURL();
-
-    Platform.runLater(new Runnable() {
-      @Override
-      public void run() {
-        webEngine.load(currentURL.toString());
-
-        webEngine.documentProperty().addListener(new ChangeListener<Document>() {
-          @Override
-          public void changed(ObservableValue<? extends Document> value, Document document, Document document2) {
-            //highlightText("");
-          }
-        });
-      }
-    });
-  }
-
-  private void highlightText(String text) {
-    webView.getEngine().executeScript("");
-  }
-
-
-
-  private ChangeListener searchResultsListener = new ChangeListener() {
-    @Override
-    public void changed(ObservableValue observable, Object oldValue,
-                        Object newValue) {
-      SearchItemWrapper wrapper = searchResultsList.getSelectionModel().getSelectedItem();
-
-      if (wrapper != null) {
-        final SearchItem item = wrapper.get();
-
-        Platform.runLater(new Runnable() {
-          @Override
-          public void run() {
-            try {
-              webView.getEngine().load(new URL(item.getBase(), item.getFilename()).toString());
-
-            }
-            catch (MalformedURLException e) {
-              LOG.error(e);
-            }
-          }
-        }
-        );
-      } else {
-        Platform.runLater(new Runnable() {
-          @Override
-          public void run() {
-            webView.getEngine().load("about:blank");
-          }
-        }
-        );
-
-      }
-    }
-  };
-
-  @Override
-  public void itemsFound(SearchEvent e) {
-    final Enumeration enumeration = e.getSearchItems();
-
-    Platform.runLater(new Runnable() {
-      public void run () {
-        searchResultsList.getItems().clear();
-
-        while (enumeration.hasMoreElements()) {
-          SearchItem item = (SearchItem)enumeration.nextElement();
-          searchResultsList.getItems().add(new SearchItemWrapper(item));
-        }
-
-        searchResultsList.getSelectionModel().selectFirst();
-
-        contentHBox.getChildren().clear();
-        contentHBox.getChildren().addAll(searchResultsList, webView);
-
-        SearchItem item = searchResultsList.getSelectionModel().getSelectedItem().get();
-        try {
-          webView.getEngine().load(new URL(item.getBase(), item.getFilename()).toString());
-        }
-        catch (MalformedURLException e) {
-          LOG.error(e);
-        }
-
-        searchResultsList.requestFocus();
-      }});
-
-  }
-
-  @Override
-  public void searchStarted(SearchEvent e) {
-    LOG.debug("Search started");
-  }
-
-  @Override
-  public void searchFinished(SearchEvent e) {
-    LOG.debug("Search finished");
-  }
-
-  private static class IdeaHelpTOCParser {
-    SAXParser parser;
-    TreeItem<TOCItemWrapper> root = new TreeItem<TOCItemWrapper>();
-
-    DefaultHandler handler = new DefaultHandler() {
-      @Override
-      public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
-        super.startElement(uri, localName, qName, attributes);
-
-      }
-    };
-
-    private IdeaHelpTOCParser() {
-      SAXParserFactory factory = SAXParserFactory.newInstance();
-      try {
-        parser = factory.newSAXParser();
-      }
-      catch (ParserConfigurationException e) {
-        LOG.error(e);
-      }
-      catch (SAXException e) {
-        LOG.error(e);
-      }
-    }
-
-    private TreeItem<TOCItemWrapper> parse(URL url) {
-      try {
-        parser.parse(url.toURI().toString(), handler);
-      }
-      catch (SAXException e) {
-        LOG.error(e);
-      }
-      catch (IOException e) {
-        LOG.error(e);
-      }
-      catch (URISyntaxException e) {
-        LOG.error(e);
-      }
-      return root;
-    }
-  }
-
-  private static class SearchField extends Region {
-
-    private TextField myField;
-
-    public SearchField() {
-      setMinHeight(24);
-      setPrefSize(200, 24);
-      myField = new TextField();
-      myField.setPromptText("Search");
-      setMaxSize(Control.USE_PREF_SIZE, Control.USE_PREF_SIZE);
-      getChildren().add(myField);
-    }
-  }
-
-  private static class SearchItemWrapper {
-    final SearchItem item;
-
-    SearchItemWrapper(SearchItem item) {
-      this.item = item;
-    }
-
-    SearchItem get() {
-      return item;
-    }
-
-    @Override
-    public String toString() {
-      return item.getTitle();
-    }
-  }
-
-  private static class TOCItemWrapper {
-
-    final private TOCItem item;
-
-    TOCItemWrapper(TOCItem item) {
-      this.item = item;
-    }
-
-    TOCItem get() {
-      return item;
-    }
-
-    @Override
-    public String toString() {
-      return item.getName();
-    }
-  }
-}
-*/
diff --git a/platform/platform-impl/src/com/intellij/help/impl/HelpManagerImpl.java b/platform/platform-impl/src/com/intellij/help/impl/HelpManagerImpl.java
index dd39cd0..dbfd012 100644
--- a/platform/platform-impl/src/com/intellij/help/impl/HelpManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/help/impl/HelpManagerImpl.java
@@ -46,7 +46,7 @@
 
   private HelpSet myHelpSet = null;
   private IdeaHelpBroker myBroker = null;
-  private Object myFXHelpBrowser;
+  private Object myFXHelpBrowser = null;
 
   public void invokeHelp(@Nullable String id) {
 
@@ -87,60 +87,44 @@
     myBroker.setDisplayed(true);
   }
 
-  private void showHelpInFXBrowser(String id) {
+  private void showHelpInFXBrowser(final String id) {
     if (myHelpSet == null) {
       Messages.showInfoMessage("Looks like you have enabled 'ide.help.fxbrowser' registry key but we cannot load JavaHelp bundle. " +
                                "Please put ideahelp.jar in the help directory.",
                                "Cannot find JavaHelp bundle");
       return;
     }
-
-    Class<?> myFXHelpBrowserClass= null;
     try {
-      myFXHelpBrowserClass = Class.forName("com.intellij.help.impl.FXHelpBrowser");
+      final Class<?> myFXHelpBrowserClass = Class.forName("com.intellij.help.impl.FXHelpBrowser");
+
+      if (myFXHelpBrowser == null) {
+        Object[] arguments = {myHelpSet};
+
+        Class[] argTypes = {HelpSet.class};
+        Constructor constructor = myFXHelpBrowserClass.getDeclaredConstructor(argTypes);
+        myFXHelpBrowser = constructor.newInstance(arguments);
+      }
+      Class[] showDocumentationMethodArgTypes = {String.class};
+      Method showDocumentationMethod = myFXHelpBrowserClass.getDeclaredMethod("showDocumentationById", showDocumentationMethodArgTypes);
+      showDocumentationMethod.invoke(myFXHelpBrowser, id);
+
     }
     catch (ClassNotFoundException e) {
       LOG.error(e);
     }
-
-    Class[] argTypes = {HelpSet.class};
-    Constructor constructor = null;
-    try {
-      constructor = myFXHelpBrowserClass.getDeclaredConstructor(argTypes);
+    catch (IllegalAccessException e) {
+      LOG.error(e);
     }
     catch (NoSuchMethodException e) {
       LOG.error(e);
     }
-
-    Object[] arguments = {myHelpSet};
-    try {
-      myFXHelpBrowser = constructor.newInstance(arguments);
+    catch (InvocationTargetException e) {
+      LOG.error(e);
     }
     catch (InstantiationException e) {
       LOG.error(e);
     }
-    catch (IllegalAccessException e) {
-      LOG.error(e);
-    }
-    catch (InvocationTargetException e) {
-      LOG.error(e);
-    }
 
-    Class[] showDocumentationMethodArgTypes = {String.class};
-
-    try {
-      Method showDocumentationMethod = myFXHelpBrowserClass.getDeclaredMethod("showDocumentation", showDocumentationMethodArgTypes);
-      showDocumentationMethod.invoke(myFXHelpBrowser, id);
-    }
-    catch (NoSuchMethodException e) {
-      LOG.error(e);
-    }
-    catch (InvocationTargetException e) {
-      LOG.error(e);
-    }
-    catch (IllegalAccessException e) {
-      LOG.error(e);
-    }
   }
 
   @Nullable
diff --git a/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java b/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java
index 8d80ff8..c6acddc 100644
--- a/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java
+++ b/platform/platform-impl/src/com/intellij/ide/diff/VirtualFileDiffElement.java
@@ -19,7 +19,8 @@
 import com.intellij.ide.util.PropertiesComponent;
 import com.intellij.openapi.actionSystem.DataProvider;
 import com.intellij.openapi.actionSystem.PlatformDataKeys;
-import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.application.Result;
+import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.diff.DiffRequest;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.fileChooser.FileChooser;
@@ -34,7 +35,6 @@
 import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.PlatformIcons;
-import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -279,19 +279,14 @@
       }
 
       if (!docsToSave.isEmpty()) {
-        UIUtil.invokeAndWaitIfNeeded(new Runnable() {
+        new WriteAction() {
           @Override
-          public void run() {
-            ApplicationManager.getApplication().runWriteAction(new Runnable() {
-              @Override
-              public void run() {
-                for (Document document : docsToSave) {
-                  manager.saveDocument(document);
-                }
-              }
-            });
+          protected void run(Result result) throws Throwable {
+            for (Document document : docsToSave) {
+              manager.saveDocument(document);
+            }
           }
-        });
+        }.execute();
       }
 
       virtualFile.refresh(true, true);
diff --git a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java
index 2296d6c3..171d2bf 100644
--- a/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java
+++ b/platform/platform-impl/src/com/intellij/ide/errorTreeView/NewErrorTreeViewPanel.java
@@ -60,8 +60,8 @@
   private volatile String myProgressText = "";
   private volatile float myFraction = 0.0f;
   private final boolean myCreateExitAction;
-  private ErrorViewStructure myErrorViewStructure;
-  private ErrorViewTreeBuilder myBuilder;
+  private final ErrorViewStructure myErrorViewStructure;
+  private final ErrorViewTreeBuilder myBuilder;
   private final Alarm myUpdateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
   private volatile boolean myIsDisposed = false;
   private final ErrorTreeViewConfiguration myConfiguration;
@@ -75,18 +75,18 @@
   private ActionToolbar myLeftToolbar;
   private ActionToolbar myRightToolbar;
   private final TreeExpander myTreeExpander = new MyTreeExpander();
-  private ExporterToTextFile myExporterToTextFile;
+  private final ExporterToTextFile myExporterToTextFile;
   protected Project myProject;
-  private String myHelpId;
+  private final String myHelpId;
   protected Tree myTree;
-  private JPanel myMessagePanel;
+  private final JPanel myMessagePanel;
   private ProcessController myProcessController;
 
   private JLabel myProgressLabel;
   private JPanel myProgressPanel;
 
-  private AutoScrollToSourceHandler myAutoScrollToSourceHandler;
-  private MyOccurenceNavigatorSupport myOccurenceNavigatorSupport;
+  private final AutoScrollToSourceHandler myAutoScrollToSourceHandler;
+  private final MyOccurrenceNavigatorSupport myOccurrenceNavigatorSupport;
 
   public NewErrorTreeViewPanel(Project project, String helpId) {
     this(project, helpId, true);
@@ -108,10 +108,12 @@
     setLayout(new BorderLayout());
 
     myAutoScrollToSourceHandler = new AutoScrollToSourceHandler() {
+      @Override
       protected boolean isAutoScrollMode() {
         return myConfiguration.isAutoscrollToSource();
       }
 
+      @Override
       protected void setAutoScrollMode(boolean state) {
         myConfiguration.setAutoscrollToSource(state);
       }
@@ -124,6 +126,7 @@
     root.setUserObject(myErrorViewStructure.createDescriptor(myErrorViewStructure.getRootElement(), null));
     final DefaultTreeModel treeModel = new DefaultTreeModel(root);
     myTree = new Tree(treeModel) {
+      @Override
       public void setRowHeight(int i) {
         super.setRowHeight(0);
         // this is needed in order to make UI calculate the height for each particular row
@@ -132,7 +135,7 @@
     myBuilder = new ErrorViewTreeBuilder(myTree, treeModel, myErrorViewStructure);
 
     myExporterToTextFile = new ErrorViewTextExporter(myErrorViewStructure);
-    myOccurenceNavigatorSupport = new MyOccurenceNavigatorSupport(myTree);
+    myOccurrenceNavigatorSupport = new MyOccurrenceNavigatorSupport(myTree);
 
     myAutoScrollToSourceHandler.install(myTree);
     TreeUtil.installActions(myTree);
@@ -152,6 +155,7 @@
     add(myMessagePanel, BorderLayout.CENTER);
 
     myTree.addKeyListener(new KeyAdapter() {
+      @Override
       public void keyPressed(KeyEvent e) {
         if (e.getKeyCode() == KeyEvent.VK_ENTER) {
           navigateToSource(false);
@@ -160,6 +164,7 @@
     });
 
     myTree.addMouseListener(new PopupHandler() {
+      @Override
       public void invokePopup(Component comp, int x, int y) {
         popupInvoked(comp, x, y);
       }
@@ -168,6 +173,7 @@
     EditSourceOnDoubleClickHandler.install(myTree);
   }
 
+  @Override
   public void dispose() {
     myIsDisposed = true;
     myErrorViewStructure.clear();
@@ -176,6 +182,7 @@
     Disposer.dispose(myBuilder);
   }
 
+  @Override
   public void performCopy(@NotNull DataContext dataContext) {
     final ErrorTreeNodeDescriptor descriptor = getSelectedNodeDescriptor();
     if (descriptor != null) {
@@ -184,14 +191,17 @@
     }
   }
 
+  @Override
   public boolean isCopyEnabled(@NotNull DataContext dataContext) {
     return getSelectedNodeDescriptor() != null;
   }
 
+  @Override
   public boolean isCopyVisible(@NotNull DataContext dataContext) {
     return true;
   }
 
+  @Override
   public Object getData(String dataId) {
     if (PlatformDataKeys.COPY_PROVIDER.is(dataId)) {
       return this;
@@ -220,6 +230,7 @@
     final ErrorTreeElement firstError = myErrorViewStructure.getFirstMessage(ErrorTreeElementKind.ERROR);
     if (firstError != null) {
       selectElement(firstError, new Runnable() {
+        @Override
         public void run() {
           if (shouldShowFirstErrorInEditor()) {
             navigateToSource(false);
@@ -259,6 +270,7 @@
     }
   }
 
+  @Override
   public void addMessage(int type, @NotNull String[] text, @Nullable VirtualFile file, int line, int column, @Nullable Object data) {
     addMessage(type, text, null, file, line, column, data);
   }
@@ -278,6 +290,7 @@
     myBuilder.updateTree();
   }
 
+  @Override
   public void addMessage(int type,
                          @NotNull String[] text,
                          @Nullable String groupName,
@@ -313,6 +326,7 @@
     return "(" + line + ", " + column + ")";
   }
 
+  @Override
   @NotNull
   public JComponent getComponent() {
     return this;
@@ -489,6 +503,7 @@
 
   private JPanel createToolbarPanel(@Nullable Runnable rerunAction) {
     AnAction closeMessageViewAction = new CloseTabToolbarAction() {
+      @Override
       public void actionPerformed(AnActionEvent e) {
         close();
       }
@@ -532,28 +547,34 @@
     group.add(myAutoScrollToSourceHandler.createToggleAction());
   }
 
+  @Override
   public OccurenceInfo goNextOccurence() {
-    return myOccurenceNavigatorSupport.goNextOccurence();
+    return myOccurrenceNavigatorSupport.goNextOccurence();
   }
 
+  @Override
   public OccurenceInfo goPreviousOccurence() {
-    return myOccurenceNavigatorSupport.goPreviousOccurence();
+    return myOccurrenceNavigatorSupport.goPreviousOccurence();
   }
 
+  @Override
   public boolean hasNextOccurence() {
-    return myOccurenceNavigatorSupport.hasNextOccurence();
+    return myOccurrenceNavigatorSupport.hasNextOccurence();
   }
 
+  @Override
   public boolean hasPreviousOccurence() {
-    return myOccurenceNavigatorSupport.hasPreviousOccurence();
+    return myOccurrenceNavigatorSupport.hasPreviousOccurence();
   }
 
+  @Override
   public String getNextOccurenceActionName() {
-    return myOccurenceNavigatorSupport.getNextOccurenceActionName();
+    return myOccurrenceNavigatorSupport.getNextOccurenceActionName();
   }
 
+  @Override
   public String getPreviousOccurenceActionName() {
-    return myOccurenceNavigatorSupport.getPreviousOccurenceActionName();
+    return myOccurrenceNavigatorSupport.getPreviousOccurenceActionName();
   }
 
   private class RerunAction extends AnAction {
@@ -566,11 +587,13 @@
       myCloseAction = closeAction;
     }
 
+    @Override
     public void actionPerformed(AnActionEvent e) {
       myCloseAction.actionPerformed(e);
       myRerunAction.run();
     }
 
+    @Override
     public void update(AnActionEvent event) {
       final Presentation presentation = event.getPresentation();
       presentation.setEnabled(canControlProcess() && isProcessStopped());
@@ -582,6 +605,7 @@
       super(IdeBundle.message("action.stop"), null, AllIcons.Actions.Suspend);
     }
 
+    @Override
     public void actionPerformed(AnActionEvent e) {
       if (canControlProcess()) {
         stopProcess();
@@ -590,6 +614,7 @@
       myRightToolbar.updateActionsImmediately();
     }
 
+    @Override
     public void update(AnActionEvent event) {
       Presentation presentation = event.getPresentation();
       presentation.setEnabled(canControlProcess() && !isProcessStopped());
@@ -606,10 +631,12 @@
       super(IdeBundle.message("action.hide.warnings"), null, AllIcons.General.HideWarnings);
     }
 
+    @Override
     public boolean isSelected(AnActionEvent event) {
       return isHideWarnings();
     }
 
+    @Override
     public void setSelected(AnActionEvent event, boolean flag) {
       if (isHideWarnings() != flag) {
         myConfiguration.setHideWarnings(flag);
@@ -623,28 +650,33 @@
   }
 
   private class MyTreeExpander implements TreeExpander {
+    @Override
     public void expandAll() {
       NewErrorTreeViewPanel.this.expandAll();
     }
 
+    @Override
     public boolean canExpand() {
       return true;
     }
 
+    @Override
     public void collapseAll() {
       NewErrorTreeViewPanel.this.collapseAll();
     }
 
+    @Override
     public boolean canCollapse() {
       return true;
     }
   }
 
-  private static class MyOccurenceNavigatorSupport extends OccurenceNavigatorSupport {
-    public MyOccurenceNavigatorSupport(final Tree tree) {
+  private static class MyOccurrenceNavigatorSupport extends OccurenceNavigatorSupport {
+    public MyOccurrenceNavigatorSupport(final Tree tree) {
       super(tree);
     }
 
+    @Override
     protected Navigatable createDescriptorForNode(DefaultMutableTreeNode node) {
       Object userObject = node.getUserObject();
       if (!(userObject instanceof ErrorTreeNodeDescriptor)) {
@@ -658,31 +690,38 @@
       return null;
     }
 
+    @Override
     public String getNextOccurenceActionName() {
       return IdeBundle.message("action.next.message");
     }
 
+    @Override
     public String getPreviousOccurenceActionName() {
       return IdeBundle.message("action.previous.message");
     }
   }
 
+  @Override
   public List<Object> getGroupChildrenData(final String groupName) {
     return myErrorViewStructure.getGroupChildrenData(groupName);
   }
 
+  @Override
   public void removeGroup(final String name) {
     myErrorViewStructure.removeGroup(name);
   }
 
+  @Override
   public void addFixedHotfixGroup(String text, List<SimpleErrorData> children) {
     myErrorViewStructure.addFixedHotfixGroup(text, children);
   }
 
+  @Override
   public void addHotfixGroup(HotfixData hotfixData, List<SimpleErrorData> children) {
     myErrorViewStructure.addHotfixGroup(hotfixData, children, this);
   }
 
+  @Override
   public void reload() {
     myBuilder.updateTree();
   }
diff --git a/platform/platform-impl/src/com/intellij/ide/highlighter/custom/impl/CustomFileTypeEditor.java b/platform/platform-impl/src/com/intellij/ide/highlighter/custom/impl/CustomFileTypeEditor.java
index 3db1a13..b20c113 100644
--- a/platform/platform-impl/src/com/intellij/ide/highlighter/custom/impl/CustomFileTypeEditor.java
+++ b/platform/platform-impl/src/com/intellij/ide/highlighter/custom/impl/CustomFileTypeEditor.java
@@ -128,10 +128,6 @@
     return panel;
   }
 
-  public void disposeEditor() {
-  }
-
-
   protected JComponent createCenterPanel() {
     JPanel panel = new JPanel(new BorderLayout());
 
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java
index 712e15e5..e1974cb 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerConfigurable.java
@@ -63,6 +63,11 @@
     myAvailable = available;
   }
 
+  @Override
+  public JComponent getPreferredFocusedComponent() {
+    return myPluginManagerMain.getPluginTable();
+  }
+
   public String getDisplayName() {
     return DISPLAY_NAME;
   }
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java
index 22fdb18..9eb33fb 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerMain.java
@@ -26,10 +26,7 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.progress.ProcessCanceledException;
-import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
-import com.intellij.openapi.progress.Task;
+import com.intellij.openapi.progress.*;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.updateSettings.impl.PluginDownloader;
@@ -300,7 +297,7 @@
                                         final Runnable cleanup) throws IOException {
     final boolean[] result = new boolean[1];
     try {
-      ProgressManager.getInstance().run(new Task.Backgroundable(null, IdeBundle.message("progress.download.plugins"), true) {
+      ProgressManager.getInstance().run(new Task.Backgroundable(null, IdeBundle.message("progress.download.plugins"), true, PluginManagerUISettings.getInstance()) {
         @Override
         public void run(@NotNull ProgressIndicator indicator) {
           try {
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerUISettings.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerUISettings.java
index b6d4e72..299a5c1d 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerUISettings.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginManagerUISettings.java
@@ -18,6 +18,7 @@
 import com.intellij.ide.ui.SplitterProportionsDataImpl;
 import com.intellij.openapi.components.*;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.progress.PerformInBackgroundOption;
 import com.intellij.openapi.ui.SplitterProportionsData;
 import com.intellij.openapi.util.DefaultJDOMExternalizer;
 import com.intellij.openapi.util.InvalidDataException;
@@ -38,7 +39,7 @@
     file = StoragePathMacros.APP_CONFIG + "/plugin_ui.xml")
   }
 )
-public class PluginManagerUISettings implements PersistentStateComponent<Element> {
+public class PluginManagerUISettings implements PersistentStateComponent<Element>, PerformInBackgroundOption {
   private static final Logger LOG = Logger.getInstance("#com.intellij.ide.plugins.PluginManagerUISettings");
 
   public int AVAILABLE_SORT_COLUMN_ORDER = SortOrder.ASCENDING.ordinal();
@@ -46,6 +47,7 @@
   public int AVAILABLE_SORT_MODE = 0;
   public boolean AVAILABLE_SORT_BY_STATUS = false;
   public boolean INSTALLED_SORT_BY_STATUS = false;
+  public boolean UPDATE_IN_BACKGROUND = false;
   public JDOMExternalizableStringList myOutdatedPlugins = new JDOMExternalizableStringList();
 
   private JDOMExternalizableStringList myInstalledPlugins = new JDOMExternalizableStringList();
@@ -100,4 +102,14 @@
   public SplitterProportionsData getAvailableSplitterProportionsData() {
     return myAvailableSplitterProportionsData;
   }
+
+  @Override
+  public boolean shouldStartInBackground() {
+    return UPDATE_IN_BACKGROUND;
+  }
+
+  @Override
+  public void processSentToBackground() {
+    UPDATE_IN_BACKGROUND = true;
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java b/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java
index 5d06987..086aaa8 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/PluginTable.java
@@ -15,16 +15,23 @@
  */
 package com.intellij.ide.plugins;
 
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.psi.PsiElement;
 import com.intellij.ui.TableUtil;
 import com.intellij.ui.table.JBTable;
 import com.intellij.util.ArrayUtil;
+import com.intellij.util.Function;
 import com.intellij.util.ui.ColumnInfo;
+import com.intellij.util.ui.TextTransferrable;
+import com.intellij.xml.util.XmlStringUtil;
+import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import javax.swing.table.TableCellRenderer;
 import javax.swing.table.TableColumn;
 import javax.swing.table.TableModel;
 import javax.swing.table.TableRowSorter;
+import java.awt.datatransfer.Transferable;
 import java.util.List;
 
 /**
@@ -54,6 +61,32 @@
     setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
     setShowGrid(false);
     setStriped(true);
+    setTransferHandler(new TransferHandler() {
+      @Nullable
+      @Override
+      protected Transferable createTransferable(JComponent c) {
+        final IdeaPluginDescriptor[] selectedValues = getSelectedObjects();
+        if (selectedValues == null) return null;
+        final String text = StringUtil.join(selectedValues, new Function<IdeaPluginDescriptor, String>() {
+          @Override
+          public String fun(IdeaPluginDescriptor descriptor) {
+            return descriptor.getName();
+          }
+        }, ", ");
+        final String htmlText = "<body>\n<ul>\n" + StringUtil.join(selectedValues, new Function<IdeaPluginDescriptor, String>() {
+          @Override
+          public String fun(IdeaPluginDescriptor descriptor) {
+            return descriptor.getName();
+          }
+        }, "</li>\n<li>") + "</ul>\n</body>\n";
+        return new TextTransferrable(XmlStringUtil.wrapInHtml(htmlText), text);
+      }
+
+      @Override
+      public int getSourceActions(JComponent c) {
+        return COPY;
+      }
+    });
   }
 
   public void setColumnWidth(final int columnIndex, final int width) {
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.form b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.form
index cf871ee..296f5ad 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.form
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.form
@@ -431,7 +431,7 @@
                 <properties/>
                 <border type="none"/>
                 <children>
-                  <component id="d2ccf" class="com.intellij.ui.table.JBTable">
+                  <component id="d2ccf" class="com.intellij.ui.table.JBTable" binding="myTable">
                     <constraints/>
                     <properties/>
                   </component>
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java
index 9f86722..3a7c85e 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,8 +18,10 @@
 import com.intellij.ide.ui.laf.darcula.DarculaLaf;
 import com.intellij.ui.ShowUIDefaultsAction;
 import com.intellij.ui.components.JBCheckBox;
+import com.intellij.ui.table.JBTable;
 
 import javax.swing.*;
+import javax.swing.table.DefaultTableModel;
 import java.awt.*;
 import java.awt.event.AWTEventListener;
 import java.awt.event.ActionEvent;
@@ -56,6 +58,7 @@
   private JButton myProgressButton;
   private JProgressBar myProgressBar2;
   private JButton myStartButton;
+  private JBTable myTable;
 
   public DarculaTest() {
     myProgressButton.addActionListener(new ActionListener() {
@@ -98,6 +101,8 @@
         }.start();
       }
     });
+
+    myTable.setModel(new DefaultTableModel(new Object[][]{{"Test", "Darcula"}, {"Test1", "Darcula1"}}, new Object[]{"Name", "Value"}));
   }
 
   public static void main(String[] args) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java
index 47e5d20..4ed678c 100644
--- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java
+++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionButton.java
@@ -22,6 +22,7 @@
 import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
 import com.intellij.openapi.actionSystem.ex.ActionUtil;
 import com.intellij.openapi.actionSystem.ex.CustomComponentAction;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.util.Getter;
 import com.intellij.openapi.util.IconLoader;
 import com.intellij.util.ui.EmptyIcon;
@@ -189,7 +190,7 @@
   }
 
   public void setToolTipText(String s) {
-    String tooltipText = AnAction.createTooltipText(s, myAction);
+    String tooltipText = KeymapUtil.createTooltipText(s, myAction);
     super.setToolTipText(tooltipText.length() > 0 ? tooltipText : null);
   }
 
@@ -209,11 +210,11 @@
     }
   }
 
-  
+
   public void setIconInsets(@Nullable Insets insets) {
     myInsets = insets != null ? insets : new Insets(0,0,0,0);
   }
-  
+
   public Dimension getMinimumSize() {
     return getPreferredSize();
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
index b493d1d..6159063 100644
--- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
@@ -212,7 +212,6 @@
   @Override
   public void removeNotify() {
     super.removeNotify();
-    this.removeAll();
     ourToolbars.remove(this);
     myActionManager.removeTimerListener(myWeakTimerListener);
     myActionManager.removeTransparentTimerListener(myWeakTimerListener);
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/TextFieldAction.java b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/TextFieldAction.java
index f65b082..3b07f3b 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/TextFieldAction.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileChooser/ex/TextFieldAction.java
@@ -19,7 +19,7 @@
 import com.intellij.ide.util.PropertiesComponent;
 import com.intellij.idea.ActionsBundle;
 import com.intellij.openapi.actionSystem.ActionManager;
-import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.ui.components.labels.LinkLabel;
 import com.intellij.ui.components.labels.LinkListener;
 
@@ -34,7 +34,7 @@
   }
 
   protected void onSetActive(final boolean active) {
-    final String tooltip = AnAction
+    final String tooltip = KeymapUtil
       .createTooltipText(ActionsBundle.message("action.FileChooser.TogglePathShowing.text"),
                          ActionManager.getInstance().getAction("FileChooser.TogglePathShowing"));
     setToolTipText(tooltip);
@@ -49,6 +49,6 @@
     setText(PropertiesComponent.getInstance().getBoolean(FileChooserDialogImpl.FILE_CHOOSER_SHOW_PATH_PROPERTY, true) ? IdeBundle.message("file.chooser.hide.path") : IdeBundle.message("file.chooser.show.path"));
   }
 
-  
-  
+
+
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java
index 105bc33..db07ac7 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/EditorsSplitters.java
@@ -352,12 +352,7 @@
         final FileEditorManagerImpl fileEditorManager = getManager();
         final HistoryEntry entry = new HistoryEntry(fileEditorManager.getProject(), file.getChild(HistoryEntry.TAG), true);
         final boolean isCurrent = Boolean.valueOf(file.getAttributeValue("current")).booleanValue();
-        final int finalI = i;
-        ApplicationManager.getApplication().runReadAction(new Runnable() {
-          public void run() {
-            fileEditorManager.openFileImpl4(window, entry.myFile, false, entry, isCurrent, finalI);
-          }
-        });
+        fileEditorManager.openFileImpl4(window, entry.myFile, false, entry, isCurrent, i);
         if (fileEditorManager.isFileOpen(entry.myFile)) {
           window.setFilePinned(entry.myFile, Boolean.valueOf(file.getAttributeValue(PINNED)).booleanValue());
           if (Boolean.valueOf(file.getAttributeValue("current-in-tab")).booleanValue()) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdateChecker.java
old mode 100755
new mode 100644
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdatesXmlLoader.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/UpdatesXmlLoader.java
old mode 100755
new mode 100644
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java b/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java
index df0f9be..a4198eb 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/ex/StatusBarEx.java
@@ -40,7 +40,7 @@
   BalloonHandler notifyProgressByBalloon(@NotNull MessageType type, @NotNull String htmlBody);
   BalloonHandler notifyProgressByBalloon(@NotNull MessageType type, @NotNull String htmlBody, @Nullable Icon icon, @Nullable HyperlinkListener listener);
 
-  void addProgress(ProgressIndicatorEx indicator, TaskInfo info);
+  void addProgress(@NotNull ProgressIndicatorEx indicator, @NotNull TaskInfo info);
   List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses();
 
   void updateWidgets();
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java
index 4c7defe..f9de5ac 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/TestWindowManager.java
@@ -133,7 +133,7 @@
     public void removeCustomIndicationComponent(@NotNull JComponent c) { }
 
     @Override
-    public void addProgress(ProgressIndicatorEx indicator, TaskInfo info) { }
+    public void addProgress(@NotNull ProgressIndicatorEx indicator, @NotNull TaskInfo info) { }
 
     @Override
     public List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses() {
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java
index e324d07..7c89fd6 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/ToolWindowHeader.java
@@ -167,7 +167,7 @@
         toolWindow.getContentUI().showContextMenu(comp, x, y, toolWindow.getPopupGroup(), toolWindow.getContentManager().getSelectedContent());
       }
     });
-    
+
     addMouseListener(new MouseAdapter() {
       public void mouseReleased(final MouseEvent e) {
         if (!e.isPopupTrigger()) {
@@ -300,16 +300,16 @@
       if (myActiveImage == null || /*myActiveImage.getHeight() != r.height ||*/ type != myImageType) {
         myActiveImage = drawToBuffer(true, r.height, myToolWindow.getType() == ToolWindowType.FLOATING);
       }
-      
+
       image = myActiveImage;
     } else {
       if (myImage == null || /*myImage.getHeight() != r.height ||*/ type != myImageType) {
         myImage = drawToBuffer(false, r.height, myToolWindow.getType() == ToolWindowType.FLOATING);
       }
-      
+
       image = myImage;
     }
-    
+
     myImageType = myToolWindow.getType();
 
     Rectangle clipBounds = clip.getBounds();
@@ -317,22 +317,22 @@
       UIUtil.drawImage(g, image, x, 0, null);
     }
   }
-  
+
   private static BufferedImage drawToBuffer(boolean active, int height, boolean floating) {
     final int width = 150;
-    
+
     BufferedImage image = UIUtil.createImage(width, height, BufferedImage.TYPE_INT_ARGB);
     Graphics2D g = image.createGraphics();
     UIUtil.drawHeader(g, 0, width, height, active, true, !floating, true);
     g.dispose();
 
-    return image; 
+    return image;
   }
 
   @Override
   public void setUI(PanelUI ui) {
     clearCaches();
-    
+
     super.setUI(ui);
   }
 
@@ -353,7 +353,7 @@
       graphics.setColor(new Color(255, 255, 255, 30));
       graphics.fill(r);
     }
-    
+
     graphics.dispose();
   }
 
@@ -430,7 +430,7 @@
 
       addPropertyChangeListener(listener);
     }
-    
+
     public void updateTooltip() {
       myButton.setToolTipText(getToolTipTextByAction(myCurrentAction));
     }
@@ -482,7 +482,7 @@
         myAlternativeAction != null && (e.getModifiers() & InputEvent.ALT_MASK) == InputEvent.ALT_MASK ? myAlternativeAction : myAction;
       final DataContext dataContext = DataManager.getInstance().getDataContext(this);
       final ActionManagerEx actionManager = ActionManagerEx.getInstanceEx();
-      InputEvent inputEvent = e.getSource() instanceof InputEvent ? (InputEvent) e.getSource() : null; 
+      InputEvent inputEvent = e.getSource() instanceof InputEvent ? (InputEvent) e.getSource() : null;
       final AnActionEvent event =
         new AnActionEvent(inputEvent, dataContext, ActionPlaces.UNKNOWN, action.getTemplatePresentation(),
                           ActionManager.getInstance(),
@@ -525,12 +525,12 @@
   }
 
   private static String getToolTipTextByAction(AnAction action) {
-    String text = AnAction.createTooltipText(action.getTemplatePresentation().getText(), action);
+    String text = KeymapUtil.createTooltipText(action.getTemplatePresentation().getText(), action);
 
     if (action instanceof HideAction) {
       text += String.format(" (Click with %s to Hide Side)", KeymapUtil.getShortcutText(KeyboardShortcut.fromString("pressed ALT")));
-    } 
-     
+    }
+
     return text;
   }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java
index ae9844c..9932590 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/IdeStatusBarImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -16,11 +16,8 @@
 package com.intellij.openapi.wm.impl.status;
 
 import com.intellij.icons.AllIcons;
-import com.intellij.ide.ui.UISettings;
-import com.intellij.ide.ui.UISettingsListener;
 import com.intellij.notification.impl.IdeNotificationArea;
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.TaskInfo;
 import com.intellij.openapi.ui.MessageType;
@@ -29,20 +26,16 @@
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.SystemInfo;
-import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.*;
 import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
 import com.intellij.openapi.wm.ex.StatusBarEx;
-import com.intellij.openapi.wm.impl.ToolWindowManagerImpl;
 import com.intellij.ui.ClickListener;
 import com.intellij.ui.awt.RelativePoint;
 import com.intellij.ui.popup.NotificationPopup;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Consumer;
 import com.intellij.util.containers.HashMap;
-import com.intellij.util.ui.BaseButtonBehavior;
-import com.intellij.util.ui.TimedDeadzone;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -52,8 +45,6 @@
 import java.awt.*;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
-import java.beans.PropertyChangeEvent;
-import java.beans.PropertyChangeListener;
 import java.util.*;
 import java.util.List;
 
@@ -81,6 +72,7 @@
   private final List<String> myCustomComponentIds = new ArrayList<String>();
 
   private final Set<IdeStatusBarImpl> myChildren = new HashSet<IdeStatusBarImpl>();
+  //private ToolWindowsWidget myToolWindowWidget;
 
   private static class WidgetBean {
     JComponent component;
@@ -172,8 +164,11 @@
     }
 
     if (master == null) {
-      addWidget(new ToolWindowsWidget(), Position.LEFT);
+      addWidget(new ToolWindowsWidget(this), Position.LEFT);
     }
+
+    enableEvents(AWTEvent.MOUSE_EVENT_MASK);
+    enableEvents(AWTEvent.MOUSE_MOTION_EVENT_MASK);
   }
 
 
@@ -259,6 +254,29 @@
     myCustomComponentIds.add(customId);
   }
 
+  //@Override
+  //protected void processMouseMotionEvent(MouseEvent e) {
+  //  final Point point = e.getPoint();
+  //  if (myToolWindowWidget != null) {
+  //    if(point.x < 42 && 0 <= point.y && point.y <= getHeight()) {
+  //      myToolWindowWidget.mouseEntered();
+  //    } else {
+  //      myToolWindowWidget.mouseExited();
+  //    }
+  //  }
+  //  super.processMouseMotionEvent(e);
+  //}
+
+  //@Override
+  //protected void processMouseEvent(MouseEvent e) {
+  //  if (e.getID() == MouseEvent.MOUSE_EXITED && myToolWindowWidget != null) {
+  //    if (!new Rectangle(0,0,22, getHeight()).contains(e.getPoint())) {
+  //      myToolWindowWidget.mouseExited();
+  //    }
+  //  }
+  //  super.processMouseEvent(e);
+  //}
+
   @Override
   public void removeCustomIndicationComponent(@NotNull final JComponent c) {
     final Set<String> keySet = myWidgetMap.keySet();
@@ -432,7 +450,7 @@
   }
 
   @Override
-  public void addProgress(ProgressIndicatorEx indicator, TaskInfo info) {
+  public void addProgress(@NotNull ProgressIndicatorEx indicator, @NotNull TaskInfo info) {
     myInfoAndProgressPanel.addProgress(indicator, info);
   }
 
@@ -548,24 +566,33 @@
     }
   }
 
-  @Override
-  protected void paintChildren(final Graphics g) {
-    if (getUI() instanceof MacStatusBarUI && !MacStatusBarUI.isActive(this)) {
-      final Graphics2D g2d = (Graphics2D)g.create();
-      //g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));
-      super.paintChildren(g2d);
-      g2d.dispose();
-    }
-    else {
-      super.paintChildren(g);
-    }
-  }
+  //@Override
+  //protected void paintChildren(final Graphics g) {
+  //  if (getUI() instanceof MacStatusBarUI && !MacStatusBarUI.isActive(this)) {
+  //    final Graphics2D g2d = (Graphics2D)g.create();
+  //    //g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, 0.4f));
+  //    super.paintChildren(g2d);
+  //    g2d.dispose();
+  //  }
+  //  else {
+  //    super.paintChildren(g);
+  //  }
+  //}
 
   public StatusBarUI getUI() {
     return (StatusBarUI)ui;
   }
 
   @Override
+  public void paint(Graphics g) {
+    super.paint(g);
+
+    //IDEA-112093
+    g.setColor(UIUtil.getPanelBackground());
+    g.drawLine(0, getHeight(), getWidth(), getHeight());
+  }
+
+  @Override
   public void removeWidget(@NotNull final String id) {
     final WidgetBean bean = myWidgetMap.get(id);
     if (bean != null) {
@@ -824,111 +851,4 @@
   public IdeFrame getFrame() {
     return myFrame;
   }
-
-  private static class ToolWindowsWidget extends JLabel implements CustomStatusBarWidget, StatusBarWidget, Disposable,
-                                                                   UISettingsListener, PropertyChangeListener {
-
-    private StatusBar myStatusBar;
-
-    private ToolWindowsWidget() {
-      new BaseButtonBehavior(this, TimedDeadzone.NULL) {
-        @Override
-        protected void execute(MouseEvent e) {
-          performAction();
-        }
-      }.setActionTrigger(MouseEvent.MOUSE_PRESSED);
-
-      UISettings.getInstance().addUISettingsListener(this, this);
-      KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this);
-    }
-
-
-    @Override
-    public void propertyChange(PropertyChangeEvent evt) {
-      updateIcon();
-    }
-
-    @Override
-    public void uiSettingsChanged(UISettings source) {
-      updateIcon();
-    }
-
-    private void performAction() {
-      if (isActive()) {
-        UISettings.getInstance().HIDE_TOOL_STRIPES = !UISettings.getInstance().HIDE_TOOL_STRIPES;
-        UISettings.getInstance().fireUISettingsChanged();
-      }
-    }
-
-    private void updateIcon() {
-      if (isActive()) {
-        boolean changes = false;
-
-        if (!isVisible()) {
-          setVisible(true);
-          changes = true;
-        }
-
-        Icon icon = UISettings.getInstance().HIDE_TOOL_STRIPES ? AllIcons.General.TbShown : AllIcons.General.TbHidden;
-        if (icon != getIcon()) {
-          setIcon(icon);
-          changes = true;
-        }
-
-        Set<Integer> vks = ToolWindowManagerImpl.getActivateToolWindowVKs();
-        String text = "Click to show or hide the tool window bars";
-        if (vks.size() == 1) {
-          Integer stroke = vks.iterator().next();
-          String keystrokeText = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(stroke.intValue(), 0));
-          text += ".\nDouble-press and hold " + keystrokeText + " to show tool window bars when hidden.";
-        }
-        if (!text.equals(getToolTipText())) {
-          setToolTipText(text);
-          changes = true;
-        }
-
-        if (changes) {
-          revalidate();
-          repaint();
-        }
-      }
-      else {
-        setVisible(false);
-        setToolTipText(null);
-      }
-    }
-
-    private boolean isActive() {
-      return myStatusBar != null && myStatusBar.getFrame() != null && myStatusBar.getFrame().getProject() != null && Registry.is("ide.windowSystem.showTooWindowButtonsSwitcher");
-    }
-
-    @Override
-    public JComponent getComponent() {
-      return this;
-    }
-
-    @NotNull
-    @Override
-    public String ID() {
-      return "ToolWindows Widget";
-    }
-
-    @Override
-    public WidgetPresentation getPresentation(@NotNull PlatformType type) {
-      return null;
-    }
-
-    @Override
-    public void install(@NotNull StatusBar statusBar) {
-      myStatusBar = statusBar;
-      updateIcon();
-    }
-
-    @Override
-    public void dispose() {
-      Disposer.dispose(this);
-      KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", this);
-      myStatusBar = null;
-    }
-  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java
index d5227a02..5231808 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InfoAndProgressPanel.java
@@ -51,8 +51,6 @@
 import java.awt.*;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
-import java.lang.ref.Reference;
-import java.lang.ref.WeakReference;
 import java.util.*;
 import java.util.List;
 
@@ -79,7 +77,7 @@
   private final AnimatedIcon myRefreshIcon;
 
   private String myCurrentRequestor;
-  
+
   public InfoAndProgressPanel() {
 
     setOpaque(false);
@@ -168,6 +166,13 @@
   @Override
   public void dispose() {
     setRefreshVisible(false);
+    InlineProgressIndicator[] indicators = getCurrentInlineIndicators().toArray(new InlineProgressIndicator[0]);
+    for (InlineProgressIndicator indicator : indicators) {
+      System.out.println("Disposing "+indicator);
+      Disposer.dispose(indicator);
+    }
+    myInline2Original.clear();
+    myOriginal2Inlines.clear();
   }
 
   @Override
@@ -175,6 +180,7 @@
     return this;
   }
 
+  @NotNull
   public List<Pair<TaskInfo, ProgressIndicator>> getBackgroundProcesses() {
     synchronized (myOriginals) {
       if (myOriginals.isEmpty()) return Collections.emptyList();
@@ -188,7 +194,7 @@
     }
   }
 
-  public void addProgress(final ProgressIndicatorEx original, TaskInfo info) {
+  public void addProgress(@NotNull ProgressIndicatorEx original, @NotNull TaskInfo info) {
     synchronized (myOriginals) {
       final boolean veryFirst = !hasProgressIndicators();
 
@@ -221,10 +227,10 @@
     }
   }
 
-  private void removeProgress(InlineProgressIndicator progress) {
+  private void removeProgress(@NotNull InlineProgressIndicator progress) {
     synchronized (myOriginals) {
       if (!myInline2Original.containsKey(progress)) return;
-      
+
       final boolean last = myOriginals.size() == 1;
       final boolean beforeLast = myOriginals.size() == 2;
 
@@ -255,7 +261,7 @@
     }
   }
 
-  private ProgressIndicatorEx removeFromMaps(final InlineProgressIndicator progress) {
+  private ProgressIndicatorEx removeFromMaps(@NotNull InlineProgressIndicator progress) {
     final ProgressIndicatorEx original = myInline2Original.get(progress);
 
     myInline2Original.remove(progress);
@@ -337,7 +343,7 @@
     repaint();
   }
 
-  private void buildInInlineIndicator(final InlineProgressIndicator inline) {
+  private void buildInInlineIndicator(@NotNull InlineProgressIndicator inline) {
     removeAll();
     setLayout(new InlineLayout());
     add(myRefreshAndInfoPanel);
@@ -477,7 +483,8 @@
     }
   }
 
-  private InlineProgressIndicator createInlineDelegate(final TaskInfo info, final ProgressIndicatorEx original, final boolean compact) {
+  @NotNull
+  private InlineProgressIndicator createInlineDelegate(@NotNull TaskInfo info, @NotNull ProgressIndicatorEx original, final boolean compact) {
     final Collection<InlineProgressIndicator> inlines = myOriginal2Inlines.get(original);
     if (inlines != null) {
       for (InlineProgressIndicator eachInline : inlines) {
@@ -547,12 +554,10 @@
 
   private class MyInlineProgressIndicator extends InlineProgressIndicator {
     private ProgressIndicatorEx myOriginal;
-    private final Reference<TaskInfo> myTask;
 
-    public MyInlineProgressIndicator(final boolean compact, @NotNull TaskInfo task, final ProgressIndicatorEx original) {
+    public MyInlineProgressIndicator(final boolean compact, @NotNull TaskInfo task, @NotNull ProgressIndicatorEx original) {
       super(compact, task);
       myOriginal = original;
-      myTask = new WeakReference<TaskInfo>(task);
       original.addStateDelegate(this);
     }
 
@@ -570,7 +575,7 @@
 
     @Override
     protected boolean isFinished() {
-      TaskInfo info = myTask.get();
+      TaskInfo info = getInfo();
       return info == null || isFinished(info);
     }
 
@@ -590,7 +595,6 @@
     public void dispose() {
       super.dispose();
       myOriginal = null;
-      myTask.clear();
     }
 
     @Override
@@ -637,6 +641,7 @@
     }, 2000);
   }
 
+  @NotNull
   private Set<InlineProgressIndicator> getCurrentInlineIndicators() {
     synchronized (myOriginals) {
       return myInline2Original.keySet();
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java
index ba025f6..ea846bf 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/InlineProgressIndicator.java
@@ -30,6 +30,7 @@
 import com.intellij.ui.components.panels.Wrapper;
 import com.intellij.util.ui.GraphicsUtil;
 import com.intellij.util.ui.UIUtil;
+import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
 import javax.swing.border.EmptyBorder;
@@ -59,7 +60,7 @@
   private long myLastTimeProgressWasAtZero;
   private boolean myLastTimeProgressWasZero;
 
-  public InlineProgressIndicator(boolean compact, TaskInfo processInfo) {
+  public InlineProgressIndicator(boolean compact, @NotNull TaskInfo processInfo) {
     myCompact = compact;
     myInfo = processInfo;
 
@@ -381,7 +382,7 @@
     myComponent = null;
 
     if (myProgress != null) {
-      UIUtil.disposeProgress(myProgress);  
+      UIUtil.disposeProgress(myProgress);
     }
     myProgress = null;
     myInfo = null;
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusBarUI.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusBarUI.java
index 019bcfd..3427513 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusBarUI.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/StatusBarUI.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -38,27 +38,12 @@
   }
 
   @Override
-  public void installUI(JComponent c) {
-    super.installUI(c);
-  }
-
-  @Override
-  public void uninstallUI(JComponent c) {
-    super.uninstallUI(c);
-  }
-
-  @Override
   public void paint(final Graphics g, final JComponent c) {
     final Rectangle bounds = c.getBounds();
     BACKGROUND_PAINTER.paintBorder(c, g, 0, 0, bounds.width, bounds.height);
   }
 
   @Override
-  public void update(Graphics g, JComponent c) {
-    super.update(g, c);
-  }
-
-  @Override
   public Dimension getMinimumSize(JComponent c) {
     return MIN_SIZE; // TODO
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java
new file mode 100644
index 0000000..1ebb011
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java
@@ -0,0 +1,266 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.wm.impl.status;
+
+import com.intellij.icons.AllIcons;
+import com.intellij.ide.IdeEventQueue;
+import com.intellij.ide.ui.UISettings;
+import com.intellij.ide.ui.UISettingsListener;
+import com.intellij.openapi.Disposable;
+import com.intellij.openapi.ui.popup.JBPopup;
+import com.intellij.openapi.ui.popup.JBPopupFactory;
+import com.intellij.openapi.util.Disposer;
+import com.intellij.openapi.util.registry.Registry;
+import com.intellij.openapi.wm.*;
+import com.intellij.openapi.wm.impl.IdeFrameImpl;
+import com.intellij.openapi.wm.impl.ToolWindowImpl;
+import com.intellij.ui.IdeBorderFactory;
+import com.intellij.ui.awt.RelativePoint;
+import com.intellij.ui.components.JBLabel;
+import com.intellij.ui.components.JBList;
+import com.intellij.util.Alarm;
+import com.intellij.util.ui.BaseButtonBehavior;
+import com.intellij.util.ui.TimedDeadzone;
+import com.intellij.util.ui.UIUtil;
+import org.jetbrains.annotations.NotNull;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.MouseEvent;
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+class ToolWindowsWidget extends JLabel implements CustomStatusBarWidget, StatusBarWidget, Disposable,
+                                                  UISettingsListener, PropertyChangeListener {
+
+  private final Alarm myAlarm;
+  private StatusBar myStatusBar;
+  private JBPopup popup;
+  private boolean wasExited = false;
+
+  ToolWindowsWidget(Disposable parent) {
+    new BaseButtonBehavior(this, TimedDeadzone.NULL) {
+      @Override
+      protected void execute(MouseEvent e) {
+        performAction();
+      }
+    }.setActionTrigger(MouseEvent.MOUSE_PRESSED);
+
+    IdeEventQueue.getInstance().addDispatcher(new IdeEventQueue.EventDispatcher() {
+      @Override
+      public boolean dispatch(AWTEvent e) {
+        if (e instanceof MouseEvent) {
+          if (e.getID() == MouseEvent.MOUSE_MOVED && isShowing()) {
+            Point p = ((MouseEvent)e).getLocationOnScreen();
+            Point screen = ToolWindowsWidget.this.getLocationOnScreen();
+            if (new Rectangle(screen.x - 4, screen.y - 2, getWidth() + 4, getHeight() + 4).contains(p)) {
+              mouseEntered();
+              wasExited = false;
+            } else {
+              if (!wasExited) {
+                wasExited = mouseExited(p);
+              }
+            }
+          }
+        }
+        return false;
+      }
+    }, parent);
+
+    UISettings.getInstance().addUISettingsListener(this, this);
+    KeyboardFocusManager.getCurrentKeyboardFocusManager().addPropertyChangeListener("focusOwner", this);
+    myAlarm = new Alarm(parent);
+  }
+
+  public boolean mouseExited(Point currentLocationOnScreen) {
+    myAlarm.cancelAllRequests();
+    if (popup != null && popup.isVisible()) {
+      final Point screen = popup.getLocationOnScreen();
+      final Rectangle popupScreenRect = new Rectangle(screen.x, screen.y, popup.getSize().width, popup.getSize().height);
+      if (! popupScreenRect.contains(currentLocationOnScreen)) {
+        myAlarm.cancelAllRequests();
+        myAlarm.addRequest(new Runnable() {
+          @Override
+          public void run() {
+            if (popup != null && popup.isVisible()) {
+              popup.cancel();
+            }
+          }
+        }, 150);
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public void mouseEntered() {
+    if (myAlarm.getActiveRequestCount() == 0) {
+      myAlarm.addRequest(new Runnable() {
+        @Override
+        public void run() {
+          DefaultListModel model = new DefaultListModel();
+          final IdeFrameImpl frame = UIUtil.getParentOfType(IdeFrameImpl.class, ToolWindowsWidget.this);
+          if (frame == null) return;
+          final ToolWindowManager toolWindowManager = ToolWindowManager.getInstance(frame.getProject());
+          for (String id : toolWindowManager.getToolWindowIds()) {
+            final ToolWindow tw = toolWindowManager.getToolWindow(id);
+            if (tw.isAvailable()) {
+              model.addElement(tw);
+            }
+          }
+
+          final JBList list = new JBList(model);
+          list.setCellRenderer(new ListCellRenderer() {
+            final JBLabel label = new JBLabel();
+
+            @Override
+            public Component getListCellRendererComponent(JList list, Object value, int index, boolean isSelected, boolean cellHasFocus) {
+              final ToolWindow toolWindow = (ToolWindow)value;
+              label.setText(toolWindow instanceof ToolWindowImpl ? ((ToolWindowImpl)toolWindow).getId() : toolWindow.getTitle());
+              label.setIcon(toolWindow.getIcon());
+              label.setBorder(IdeBorderFactory.createEmptyBorder(4, 10, 4, 10));
+              label.setForeground(UIUtil.getListForeground(isSelected));
+              label.setBackground(UIUtil.getListBackground(isSelected));
+              final JPanel panel = new JPanel(new BorderLayout());
+              panel.add(label, BorderLayout.CENTER);
+              panel.setBackground(UIUtil.getListBackground(isSelected));
+              return panel;
+            }
+          });
+
+          final Dimension size = list.getPreferredSize();
+          final JComponent c = ToolWindowsWidget.this;
+          final RelativePoint point = new RelativePoint(c, new Point(-4, -4 - size.height));
+
+
+          if (popup != null && popup.isVisible()) {
+            return;
+          }
+
+          list.setSelectedIndex(list.getItemsCount() - 1);
+          popup = JBPopupFactory.getInstance().createListPopupBuilder(list)
+            .setAutoselectOnMouseMove(true)
+            .setItemChoosenCallback(new Runnable() {
+              @Override
+              public void run() {
+                if (popup != null) popup.closeOk(null);
+                final Object value = list.getSelectedValue();
+                if (value instanceof ToolWindow) {
+                  ((ToolWindow)value).activate(null, true, true);
+                }
+              }
+            })
+            .createPopup();
+
+          popup.show(point);
+        }
+      }, 300);
+    }
+  }
+
+  @Override
+  public void propertyChange(PropertyChangeEvent evt) {
+    updateIcon();
+  }
+
+  @Override
+  public void uiSettingsChanged(UISettings source) {
+    updateIcon();
+  }
+
+  private void performAction() {
+    if (isActive()) {
+      UISettings.getInstance().HIDE_TOOL_STRIPES = !UISettings.getInstance().HIDE_TOOL_STRIPES;
+      UISettings.getInstance().fireUISettingsChanged();
+    }
+  }
+
+  private void updateIcon() {
+    setToolTipText(null);
+    if (isActive()) {
+      boolean changes = false;
+
+      if (!isVisible()) {
+        setVisible(true);
+        changes = true;
+      }
+
+      Icon icon = UISettings.getInstance().HIDE_TOOL_STRIPES ? AllIcons.General.TbShown : AllIcons.General.TbHidden;
+      if (icon != getIcon()) {
+        setIcon(icon);
+        changes = true;
+      }
+
+      //Set<Integer> vks = ToolWindowManagerImpl.getActivateToolWindowVKs();
+      //String text = "Click to show or hide the tool window bars";
+      //if (vks.size() == 1) {
+      //  Integer stroke = vks.iterator().next();
+      //  String keystrokeText = KeymapUtil.getKeystrokeText(KeyStroke.getKeyStroke(stroke.intValue(), 0));
+      //  text += ".\nDouble-press and hold " + keystrokeText + " to show tool window bars when hidden.";
+      //}
+      //if (!text.equals(getToolTipText())) {
+      //  setToolTipText(text);
+      //  changes = true;
+      //}
+
+      if (changes) {
+        revalidate();
+        repaint();
+      }
+    }
+    else {
+      setVisible(false);
+      setToolTipText(null);
+    }
+  }
+
+  private boolean isActive() {
+    return myStatusBar != null && myStatusBar.getFrame() != null && myStatusBar.getFrame().getProject() != null && Registry
+      .is("ide.windowSystem.showTooWindowButtonsSwitcher");
+  }
+
+  @Override
+  public JComponent getComponent() {
+    return this;
+  }
+
+  @NotNull
+  @Override
+  public String ID() {
+    return "ToolWindows Widget";
+  }
+
+  @Override
+  public WidgetPresentation getPresentation(@NotNull PlatformType type) {
+    return null;
+  }
+
+  @Override
+  public void install(@NotNull StatusBar statusBar) {
+    myStatusBar = statusBar;
+    updateIcon();
+  }
+
+  @Override
+  public void dispose() {
+    Disposer.dispose(this);
+    KeyboardFocusManager.getCurrentKeyboardFocusManager().removePropertyChangeListener("focusOwner", this);
+    myStatusBar = null;
+  }
+}
diff --git a/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java b/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java
index 71a5e7d..394e816 100644
--- a/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java
+++ b/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java
@@ -24,12 +24,18 @@
  * @author Konstantin Bulenkov
  */
 public class DefaultPlatformTopHitProvider implements SearchTopHitProvider {
-  private static final String[][] ACTION_MATRIX = {
-    {"op", "open ", "OpenFile", "$LRU"},
-    {"reo", "reopen ", "$LRU"},
-  };
+
   @Override
   public void consumeTopHits(String pattern, Consumer<Object> collector) {
+    //todo[kb] move to constant. Now it's better for hotswap
+    String[][] ACTION_MATRIX = {
+       {"op", "open ", "OpenFile"},
+       {"reo", "reopen ", "$LRU"},
+       {"new", "new ", "NewGroup"},
+       {"new c", "new class ", "NewClass"},
+       {"new i", "new interface ", "NewClass"},
+       {"new e", "new enum ", "NewClass"},
+     };
     final ActionManager actionManager = ActionManager.getInstance();
     for (String[] strings : ACTION_MATRIX) {
       if (StringUtil.isBetween(pattern, strings[0], strings[1])) {
diff --git a/platform/platform-resources-en/src/messages/LangBundle.properties b/platform/platform-resources-en/src/messages/LangBundle.properties
index 19213c6..cc4f4fd 100644
--- a/platform/platform-resources-en/src/messages/LangBundle.properties
+++ b/platform/platform-resources-en/src/messages/LangBundle.properties
@@ -51,5 +51,4 @@
 template.data.language.override.warning.text=There are template data languages specified for the subdirectories. Override them?
 template.data.language.override.warning.title=Override Subdirectory Template Data Languages
 quickfix.change.template.data.language.text=Change {0} template data language to...
-compacting.indices.title=Compacting Indices
 incorrect.name=Incorrect name
diff --git a/platform/platform-resources-en/src/messages/UIBundle.properties b/platform/platform-resources-en/src/messages/UIBundle.properties
index 14c7351..04a5c32 100644
--- a/platform/platform-resources-en/src/messages/UIBundle.properties
+++ b/platform/platform-resources-en/src/messages/UIBundle.properties
@@ -89,7 +89,7 @@
 
 file.chooser.default.title=Select Path
 file.chooser.save.dialog.default.title=Select File to Save
-file.chooser.save.dialog.confirmation={0} is already exists.\nDo you want to replace it?
+file.chooser.save.dialog.confirmation={0} already exists.\nDo you want to replace it?
 file.chooser.save.dialog.confirmation.title=Confirm Save as
 file.chooser.select.object.title=Select {0}
 delete.dialog.title=Delete
diff --git a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java
index 82b3ccf..53be07e 100644
--- a/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java
+++ b/platform/platform-tests/testSrc/com/intellij/ide/util/treeView/BaseTreeTestCase.java
@@ -282,11 +282,6 @@
   static AbstractTreeUpdater _createUpdater(AbstractTreeBuilder builder) {
     final AbstractTreeUpdater updater = new AbstractTreeUpdater(builder) {
       @Override
-      protected void invokeLater(Runnable runnable) {
-        runnable.run();
-      }
-
-      @Override
       protected boolean isEdt() {
         return SwingUtilities.isEventDispatchThread();
       }
@@ -422,7 +417,7 @@
   void select(final Object element, final boolean addToSelection) throws Exception {
     select(new Object[] {element}, addToSelection);
   }
-  
+
   void select(final Object[] elements, final boolean addToSelection) throws Exception {
     select(elements, addToSelection, false);
   }
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/ServerConfigurationBase.java b/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/ServerConfigurationBase.java
new file mode 100644
index 0000000..1e7e1d9
--- /dev/null
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/ServerConfigurationBase.java
@@ -0,0 +1,26 @@
+package com.intellij.remoteServer.configuration;
+
+import com.intellij.openapi.components.PersistentStateComponent;
+import com.intellij.util.xmlb.XmlSerializerUtil;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author nik
+ */
+public abstract class ServerConfigurationBase<Self extends ServerConfigurationBase<Self>> extends ServerConfiguration implements PersistentStateComponent<Self> {
+  @Override
+  public PersistentStateComponent<?> getSerializer() {
+    return this;
+  }
+
+  @Nullable
+  @Override
+  public Self getState() {
+    return (Self)this;
+  }
+
+  @Override
+  public void loadState(Self state) {
+    XmlSerializerUtil.copyBean(state, this);
+  }
+}
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/deployment/DeploymentSourceUtil.java b/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/deployment/DeploymentSourceUtil.java
index 1336f7c..72d978f 100644
--- a/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/deployment/DeploymentSourceUtil.java
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/configuration/deployment/DeploymentSourceUtil.java
@@ -18,10 +18,14 @@
 import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.module.ModulePointer;
 import com.intellij.openapi.project.Project;
+import com.intellij.packaging.artifacts.Artifact;
 import com.intellij.packaging.artifacts.ArtifactPointer;
 import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
 
+import java.util.Collection;
+import java.util.List;
+
 /**
  * @author nik
  */
@@ -34,6 +38,10 @@
   public abstract ArtifactDeploymentSource createArtifactDeploymentSource(@NotNull ArtifactPointer artifactPointer);
 
   @NotNull
+  public abstract List<DeploymentSource> createArtifactDeploymentSources(@NotNull Project project,
+                                                                         @NotNull Collection<? extends Artifact> artifacts);
+
+  @NotNull
   public abstract ModuleDeploymentSource createModuleDeploymentSource(@NotNull ModulePointer modulePointer);
 
   public abstract DeploymentSource loadDeploymentSource(@NotNull Element element, @NotNull Project project);
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ConnectionStatus.java b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ConnectionStatus.java
index 60265e8..be44446 100644
--- a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ConnectionStatus.java
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ConnectionStatus.java
@@ -6,7 +6,7 @@
  * @author nik
  */
 public enum ConnectionStatus {
-  DISCONNECTED, CONNECTED, CONNECTING, DISCONNECTING;
+  DISCONNECTED, CONNECTED, CONNECTING;
 
   public String getPresentableText() {
     return StringUtil.capitalize(name().toLowerCase());
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnection.java b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnection.java
index 8c148977..ddaf04b 100644
--- a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnection.java
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnection.java
@@ -3,6 +3,7 @@
 import com.intellij.openapi.ui.ComponentContainer;
 import com.intellij.remoteServer.configuration.RemoteServer;
 import com.intellij.remoteServer.configuration.deployment.DeploymentConfiguration;
+import com.intellij.remoteServer.runtime.deployment.DeploymentRuntime;
 import com.intellij.remoteServer.runtime.deployment.DeploymentTask;
 import com.intellij.util.ParameterizedRunnable;
 import org.jetbrains.annotations.NotNull;
@@ -27,10 +28,14 @@
   void connect(@NotNull Runnable onFinished);
 
 
+  void disconnect();
+
   void deploy(@NotNull DeploymentTask<D> task, @NotNull ParameterizedRunnable<String> onDeploymentStarted);
 
   void computeDeployments(@NotNull Runnable onFinished);
 
+  void undeploy(@NotNull Deployment deployment, @NotNull DeploymentRuntime runtime);
+
   @NotNull
   Collection<Deployment> getDeployments();
 
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnector.java b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnector.java
index e3b16f0..0f3fc11 100644
--- a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnector.java
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/ServerConnector.java
@@ -10,8 +10,6 @@
 public abstract class ServerConnector<D extends DeploymentConfiguration> {
   public abstract void connect(@NotNull ConnectionCallback<D> callback);
 
-  public abstract void disconnect();
-
   public interface ConnectionCallback<D extends DeploymentConfiguration> extends RemoteOperationCallback {
     void connected(@NotNull ServerRuntimeInstance<D> serverRuntimeInstance);
   }
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentRuntime.java b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentRuntime.java
index 6bae6c8..7a6cbd1 100644
--- a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentRuntime.java
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/DeploymentRuntime.java
@@ -6,13 +6,12 @@
 /**
  * @author nik
  */
-public class DeploymentRuntime {
+public abstract class DeploymentRuntime {
   public boolean isUndeploySupported() {
-    return false;
+    return true;
   }
 
-  public void undeploy(@NotNull UndeploymentTaskCallback callback) {
-  }
+  public abstract void undeploy(@NotNull UndeploymentTaskCallback callback);
 
   public interface UndeploymentTaskCallback extends RemoteOperationCallback {
     void succeeded();
diff --git a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/ServerRuntimeInstance.java b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/ServerRuntimeInstance.java
index 05c4bdc..499ec74 100644
--- a/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/ServerRuntimeInstance.java
+++ b/platform/remote-servers/api/src/com/intellij/remoteServer/runtime/deployment/ServerRuntimeInstance.java
@@ -2,12 +2,9 @@
 
 import com.intellij.remoteServer.configuration.deployment.DeploymentConfiguration;
 import com.intellij.remoteServer.configuration.deployment.DeploymentSource;
-import com.intellij.remoteServer.runtime.Deployment;
 import com.intellij.remoteServer.runtime.RemoteOperationCallback;
 import org.jetbrains.annotations.NotNull;
 
-import java.util.List;
-
 /**
  * @author nik
  */
@@ -15,18 +12,21 @@
 
   public abstract void deploy(@NotNull DeploymentTask<D> task, @NotNull DeploymentOperationCallback callback);
 
-  public abstract void computeDeployments(@NotNull ComputeDeploymentsCallback deployments);
+  public abstract void computeDeployments(@NotNull ComputeDeploymentsCallback callback);
 
   @NotNull
   public String getDeploymentName(@NotNull DeploymentSource source) {
     return source.getPresentableName();
   }
 
+  public abstract void disconnect();
+
   public interface DeploymentOperationCallback extends RemoteOperationCallback {
     void succeeded(@NotNull DeploymentRuntime deployment);
   }
 
   public interface ComputeDeploymentsCallback extends RemoteOperationCallback {
-    void succeeded(@NotNull List<Deployment> deployments);
+    void addDeployment(@NotNull String deploymentName);
+    void succeeded();
   }
 }
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerConfigurable.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerConfigurable.java
index 1a65ddd..0f460ac 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerConfigurable.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerConfigurable.java
@@ -61,7 +61,7 @@
       @Override
       public void actionPerformed(ActionEvent e) {
         try {
-          apply();
+          myConfigurable.apply();
         }
         catch (ConfigurationException exc) {
           Messages.showErrorDialog(myMainPanel, "Cannot test connection: " + exc.getMessage(), exc.getTitle());
@@ -100,7 +100,9 @@
           }
         });
         while (!indicator.isCanceled()) {
-          semaphore.waitFor(500);
+          if (semaphore.waitFor(500)) {
+            break;
+          }
         }
         Runnable showResult = showResultRef.get();
         if (showResult != null) {
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java
index c55fa75..b35899e 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/RemoteServerListConfigurable.java
@@ -20,6 +20,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import javax.swing.*;
 import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
@@ -30,12 +31,23 @@
  */
 public class RemoteServerListConfigurable extends MasterDetailsComponent implements OptionalConfigurable, SearchableConfigurable {
   private final RemoteServersManager myServersManager;
+  @Nullable private final ServerType<?> myServerType;
+  private RemoteServer<?> myLastSelectedServer;
 
-  public RemoteServerListConfigurable(RemoteServersManager manager) {
+  public RemoteServerListConfigurable(@NotNull RemoteServersManager manager) {
+    this(manager, null);
+  }
+
+  private RemoteServerListConfigurable(@NotNull RemoteServersManager manager, @Nullable ServerType<?> type) {
     myServersManager = manager;
+    myServerType = type;
     initTree();
   }
 
+  public static RemoteServerListConfigurable createConfigurable(@NotNull ServerType<?> type) {
+    return new RemoteServerListConfigurable(RemoteServersManager.getInstance(), type);
+  }
+
   @Nls
   @Override
   public String getDisplayName() {
@@ -45,12 +57,23 @@
   @Override
   public void reset() {
     myRoot.removeAllChildren();
-    for (RemoteServer<?> server : myServersManager.getServers()) {
+    List<RemoteServer<?>> servers = getServers();
+    for (RemoteServer<?> server : servers) {
       addServerNode(server, false);
     }
     super.reset();
   }
 
+  private List<RemoteServer<?>> getServers() {
+    if (myServerType == null) {
+      return myServersManager.getServers();
+    }
+    else {
+      //code won't compile without this ugly cast (at least in jdk 1.6)
+      return (List<RemoteServer<?>>)((List)myServersManager.getServers(myServerType));
+    }
+  }
+
   private MyNode addServerNode(RemoteServer<?> server, boolean isNew) {
     MyNode node = new MyNode(new RemoteServerConfigurable(server, TREE_UPDATER, isNew));
     addNode(node, myRoot);
@@ -77,7 +100,7 @@
     }
 
     List<RemoteServer<?>> toDelete = new ArrayList<RemoteServer<?>>();
-    for (RemoteServer<?> server : myServersManager.getServers()) {
+    for (RemoteServer<?> server : getServers()) {
       if (!servers.contains(server)) {
         toDelete.add(server);
       }
@@ -90,7 +113,7 @@
   @Override
   public void apply() throws ConfigurationException {
     super.apply();
-    Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(myServersManager.getServers());
+    Set<RemoteServer<?>> servers = new HashSet<RemoteServer<?>>(getServers());
     for (NamedConfigurable<RemoteServer<?>> configurable : getConfiguredServers()) {
       RemoteServer<?> server = configurable.getEditableObject();
       server.setName(configurable.getDisplayName());
@@ -104,7 +127,12 @@
   @Override
   protected ArrayList<AnAction> createActions(boolean fromPopup) {
     ArrayList<AnAction> actions = new ArrayList<AnAction>();
-    actions.add(new AddRemoteServerGroup());
+    if (myServerType == null) {
+      actions.add(new AddRemoteServerGroup());
+    }
+    else {
+      actions.add(new AddRemoteServerAction(myServerType, IconUtil.getAddIcon()));
+    }
     actions.add(new MyDeleteAction());
     return actions;
   }
@@ -119,6 +147,18 @@
     return true;
   }
 
+  @Override
+  public void disposeUIResources() {
+    Object selectedObject = getSelectedObject();
+    myLastSelectedServer = selectedObject instanceof RemoteServer<?> ? (RemoteServer)selectedObject : null;
+    super.disposeUIResources();
+  }
+
+  @Nullable
+  public RemoteServer<?> getLastSelectedServer() {
+    return myLastSelectedServer;
+  }
+
   private List<NamedConfigurable<RemoteServer<?>>> getConfiguredServers() {
     List<NamedConfigurable<RemoteServer<?>>> configurables = new ArrayList<NamedConfigurable<RemoteServer<?>>>();
     for (int i = 0; i < myRoot.getChildCount(); i++) {
@@ -140,7 +180,7 @@
       ServerType[] serverTypes = ServerType.EP_NAME.getExtensions();
       AnAction[] actions = new AnAction[serverTypes.length];
       for (int i = 0; i < serverTypes.length; i++) {
-        actions[i] = new AddRemoteServerAction(serverTypes[i]);
+        actions[i] = new AddRemoteServerAction(serverTypes[i], serverTypes[i].getIcon());
       }
       return actions;
     }
@@ -159,8 +199,8 @@
   private class AddRemoteServerAction extends DumbAwareAction {
     private final ServerType<?> myServerType;
 
-    private AddRemoteServerAction(ServerType<?> serverType) {
-      super(serverType.getPresentableName(), null, serverType.getIcon());
+    private AddRemoteServerAction(ServerType<?> serverType, final Icon icon) {
+      super(serverType.getPresentableName(), null, icon);
       myServerType = serverType;
     }
 
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerRunConfiguration.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerRunConfiguration.java
index 6e03b30..235a274 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerRunConfiguration.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerRunConfiguration.java
@@ -79,7 +79,7 @@
   @NotNull
   @Override
   public SettingsEditor<DeployToServerRunConfiguration> getConfigurationEditor() {
-    return new DeployToServerSettingsEditor(myServerType, myDeploymentConfigurator, getProject());
+    return new DeployToServerSettingsEditor(myServerType, myDeploymentConfigurator);
   }
 
   @Nullable
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java
index f6ef4dda..a4190f6 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeployToServerSettingsEditor.java
@@ -17,7 +17,7 @@
 
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SettingsEditor;
-import com.intellij.openapi.project.Project;
+import com.intellij.openapi.options.ShowSettingsUtil;
 import com.intellij.openapi.ui.ComboBox;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Disposer;
@@ -28,10 +28,8 @@
 import com.intellij.remoteServer.configuration.deployment.DeploymentConfiguration;
 import com.intellij.remoteServer.configuration.deployment.DeploymentConfigurator;
 import com.intellij.remoteServer.configuration.deployment.DeploymentSource;
-import com.intellij.ui.ColoredListCellRendererWrapper;
-import com.intellij.ui.ListCellRendererWrapper;
-import com.intellij.ui.SimpleTextAttributes;
-import com.intellij.ui.SortedComboBoxModel;
+import com.intellij.remoteServer.impl.configuration.RemoteServerListConfigurable;
+import com.intellij.ui.*;
 import com.intellij.util.ui.FormBuilder;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -46,29 +44,39 @@
  * @author nik
  */
 public class DeployToServerSettingsEditor<S extends ServerConfiguration, D extends DeploymentConfiguration> extends SettingsEditor<DeployToServerRunConfiguration<S, D>> {
+  private final ServerType<S> myServerType;
   private final DeploymentConfigurator<D> myDeploymentConfigurator;
-  private ComboBox myServerComboBox;
-  private ComboBox mySourceComboBox;
+  private final ComboboxWithBrowseButton myServerComboBox;
+  private final ComboBox mySourceComboBox;
   private final SortedComboBoxModel<String> myServerListModel;
   private final SortedComboBoxModel<DeploymentSource> mySourceListModel;
+  private final JPanel myDeploymentSettingsComponent;
   private SettingsEditor<D> myDeploymentSettingsEditor;
   private DeploymentSource myLastSelection;
-  private JPanel myDeploymentSettingsComponent;
 
-  public DeployToServerSettingsEditor(final ServerType<S> type, DeploymentConfigurator<D> deploymentConfigurator, Project project) {
+  public DeployToServerSettingsEditor(final ServerType<S> type, DeploymentConfigurator<D> deploymentConfigurator) {
+    myServerType = type;
     myDeploymentConfigurator = deploymentConfigurator;
-    myServerListModel = new SortedComboBoxModel<String>(String.CASE_INSENSITIVE_ORDER);
-    for (RemoteServer<? extends ServerConfiguration> server : RemoteServersManager.getInstance().getServers(type)) {
-      myServerListModel.add(server.getName());
-    }
 
-    myServerComboBox = new ComboBox(myServerListModel);
-    myServerComboBox.setRenderer(new ColoredListCellRendererWrapper<String>() {
+    myServerListModel = new SortedComboBoxModel<String>(String.CASE_INSENSITIVE_ORDER);
+    myServerComboBox = new ComboboxWithBrowseButton(new ComboBox(myServerListModel));
+    fillApplicationServersList(null);
+    myServerComboBox.addActionListener(new ActionListener() {
+      @Override
+      public void actionPerformed(ActionEvent e) {
+        RemoteServerListConfigurable configurable = RemoteServerListConfigurable.createConfigurable(type);
+        if (ShowSettingsUtil.getInstance().editConfigurable(myServerComboBox, configurable)) {
+          fillApplicationServersList(configurable.getLastSelectedServer());
+        }
+      }
+    });
+    myServerComboBox.getComboBox().setRenderer(new ColoredListCellRendererWrapper<String>() {
       @Override
       protected void doCustomize(JList list, String value, int index, boolean selected, boolean hasFocus) {
         if (value == null) return;
-        SimpleTextAttributes attributes = RemoteServersManager.getInstance().findByName(value, type) == null
-                                          ? SimpleTextAttributes.ERROR_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;
+        RemoteServer<S> server = RemoteServersManager.getInstance().findByName(value, type);
+        SimpleTextAttributes attributes = server == null ? SimpleTextAttributes.ERROR_ATTRIBUTES : SimpleTextAttributes.REGULAR_ATTRIBUTES;
+        setIcon(server != null ? server.getType().getIcon() : null);
         append(value, attributes);
       }
     });
@@ -99,6 +107,15 @@
     });
   }
 
+  private void fillApplicationServersList(@Nullable RemoteServer<?> newSelection) {
+    String oldSelection = myServerListModel.getSelectedItem();
+    myServerListModel.clear();
+    for (RemoteServer<?> server : RemoteServersManager.getInstance().getServers(myServerType)) {
+      myServerListModel.add(server.getName());
+    }
+    myServerComboBox.getComboBox().setSelectedItem(newSelection != null ? newSelection.getName() : oldSelection);
+  }
+
   private void updateDeploymentSettings(@Nullable D configuration) {
     DeploymentSource selected = mySourceListModel.getSelectedItem();
     if (Comparing.equal(selected, myLastSelection)) {
@@ -126,7 +143,7 @@
     if (serverName != null && !myServerListModel.getItems().contains(serverName)) {
       myServerListModel.add(serverName);
     }
-    myServerComboBox.setSelectedItem(serverName);
+    myServerComboBox.getComboBox().setSelectedItem(serverName);
     mySourceComboBox.setSelectedItem(configuration.getDeploymentSource());
     updateDeploymentSettings(configuration.getDeploymentConfiguration());
   }
@@ -161,9 +178,4 @@
       .addComponent(myDeploymentSettingsComponent)
       .getPanel();
   }
-
-  @Override
-  protected void disposeEditor() {
-
-  }
 }
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeploymentSourceUtilImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeploymentSourceUtilImpl.java
index f1df34a..6cc425e 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeploymentSourceUtilImpl.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/configuration/deployment/DeploymentSourceUtilImpl.java
@@ -18,6 +18,7 @@
 import com.intellij.openapi.module.ModulePointer;
 import com.intellij.openapi.module.ModulePointerManager;
 import com.intellij.openapi.project.Project;
+import com.intellij.packaging.artifacts.Artifact;
 import com.intellij.packaging.artifacts.ArtifactPointer;
 import com.intellij.packaging.artifacts.ArtifactPointerManager;
 import com.intellij.remoteServer.configuration.deployment.ArtifactDeploymentSource;
@@ -27,6 +28,10 @@
 import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
 
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.List;
+
 /**
  * @author nik
  */
@@ -37,6 +42,18 @@
     return new ArtifactDeploymentSourceImpl(artifactPointer);
   }
 
+  @NotNull
+  @Override
+  public List<DeploymentSource> createArtifactDeploymentSources(@NotNull Project project,
+                                                                @NotNull Collection<? extends Artifact> artifacts) {
+    List<DeploymentSource> sources = new ArrayList<DeploymentSource>();
+    ArtifactPointerManager pointerManager = ArtifactPointerManager.getInstance(project);
+    for (Artifact artifact : artifacts) {
+      sources.add(createArtifactDeploymentSource(pointerManager.createPointer(artifact)));
+    }
+    return sources;
+  }
+
   @Override
   @NotNull
   public ModuleDeploymentSource createModuleDeploymentSource(@NotNull ModulePointer modulePointer) {
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java
index d371233..ea83602 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionImpl.java
@@ -28,17 +28,19 @@
   private final RemoteServer<?> myServer;
   private final ServerConnector<D> myConnector;
   private final ServerConnectionEventDispatcher myEventDispatcher;
+  private final ServerConnectionManagerImpl myConnectionManager;
   private volatile ConnectionStatus myStatus = ConnectionStatus.DISCONNECTED;
   private volatile String myStatusText;
   private volatile ServerRuntimeInstance<D> myRuntimeInstance;
   private final Map<String, Deployment> myRemoteDeployments = new HashMap<String, Deployment>();
-  private final Map<DeploymentSource, Deployment> myLocalDeployments = Collections.synchronizedMap(new HashMap<DeploymentSource, Deployment>());
+  private final Map<String, Deployment> myLocalDeployments = Collections.synchronizedMap(new HashMap<String, Deployment>());
   private final Map<String, LoggingHandlerImpl> myLoggingHandlers = new ConcurrentHashMap<String, LoggingHandlerImpl>();
 
-  public ServerConnectionImpl(RemoteServer<?> server, ServerConnector<D> connector, ServerConnectionEventDispatcher eventDispatcher) {
+  public ServerConnectionImpl(RemoteServer<?> server, ServerConnector connector, ServerConnectionManagerImpl connectionManager) {
     myServer = server;
     myConnector = connector;
-    myEventDispatcher = eventDispatcher;
+    myConnectionManager = connectionManager;
+    myEventDispatcher = myConnectionManager.getEventDispatcher();
   }
 
   @NotNull
@@ -61,7 +63,7 @@
 
   @Override
   public void connect(@NotNull final Runnable onFinished) {
-    disconnect();
+    doDisconnect();
     connectIfNeeded(new ServerConnector.ConnectionCallback<D>() {
       @Override
       public void connected(@NotNull ServerRuntimeInstance<D> serverRuntimeInstance) {
@@ -75,10 +77,18 @@
     });
   }
 
-  private void disconnect() {
+  @Override
+  public void disconnect() {
+    myConnectionManager.removeConnection(myServer);
+    doDisconnect();
+  }
+
+  private void doDisconnect() {
     if (myStatus == ConnectionStatus.CONNECTED) {
-      myRuntimeInstance = null;
-      myConnector.disconnect();
+      if (myRuntimeInstance != null) {
+        myRuntimeInstance.disconnect();
+        myRuntimeInstance = null;
+      }
       setStatus(ConnectionStatus.DISCONNECTED);
     }
   }
@@ -90,10 +100,10 @@
       public void connected(@NotNull ServerRuntimeInstance<D> instance) {
         DeploymentSource source = task.getSource();
         String deploymentName = instance.getDeploymentName(source);
-        myLocalDeployments.put(source, new DeploymentImpl(deploymentName, DeploymentStatus.DEPLOYING, null, null));
+        myLocalDeployments.put(deploymentName, new DeploymentImpl(deploymentName, DeploymentStatus.DEPLOYING, null, null));
         myLoggingHandlers.put(deploymentName, (LoggingHandlerImpl)task.getLoggingHandler());
         onDeploymentStarted.run(deploymentName);
-        instance.deploy(task, new DeploymentOperationCallbackImpl(task.getSource(), deploymentName));
+        instance.deploy(task, new DeploymentOperationCallbackImpl(deploymentName));
       }
     });
   }
@@ -111,11 +121,18 @@
       @Override
       public void connected(@NotNull ServerRuntimeInstance<D> instance) {
         instance.computeDeployments(new ServerRuntimeInstance.ComputeDeploymentsCallback() {
+          private final List<Deployment> myDeployments = new ArrayList<Deployment>();
+
           @Override
-          public void succeeded(@NotNull List<Deployment> deployments) {
+          public void addDeployment(@NotNull String deploymentName) {
+            myDeployments.add(new DeploymentImpl(deploymentName, DeploymentStatus.DEPLOYED, null, null));
+          }
+
+          @Override
+          public void succeeded() {
             synchronized (myRemoteDeployments) {
               myRemoteDeployments.clear();
-              for (Deployment deployment : deployments) {
+              for (Deployment deployment : myDeployments) {
                 myRemoteDeployments.put(deployment.getName(), deployment);
               }
             }
@@ -137,6 +154,26 @@
     });
   }
 
+  @Override
+  public void undeploy(@NotNull Deployment deployment, @NotNull final DeploymentRuntime runtime) {
+    final String deploymentName = deployment.getName();
+    myLocalDeployments.put(deploymentName, new DeploymentImpl(deploymentName, DeploymentStatus.UNDEPLOYING, null, null));
+    myEventDispatcher.queueDeploymentsChanged(this);
+    runtime.undeploy(new DeploymentRuntime.UndeploymentTaskCallback() {
+      @Override
+      public void succeeded() {
+        myLocalDeployments.remove(deploymentName);
+        myEventDispatcher.queueDeploymentsChanged(ServerConnectionImpl.this);
+      }
+
+      @Override
+      public void errorOccurred(@NotNull String errorMessage) {
+        myLocalDeployments.put(deploymentName, new DeploymentImpl(deploymentName, DeploymentStatus.DEPLOYED, errorMessage, runtime));
+        myEventDispatcher.queueDeploymentsChanged(ServerConnectionImpl.this);
+      }
+    });
+  }
+
   @NotNull
   @Override
   public Collection<Deployment> getDeployments() {
@@ -190,23 +227,21 @@
   }
 
   private class DeploymentOperationCallbackImpl implements ServerRuntimeInstance.DeploymentOperationCallback {
-    private final DeploymentSource mySource;
     private final String myDeploymentName;
 
-    public DeploymentOperationCallbackImpl(DeploymentSource source, String deploymentName) {
-      mySource = source;
+    public DeploymentOperationCallbackImpl(String deploymentName) {
       myDeploymentName = deploymentName;
     }
 
     @Override
     public void succeeded(@NotNull DeploymentRuntime deployment) {
-      myLocalDeployments.put(mySource, new DeploymentImpl(myDeploymentName, DeploymentStatus.DEPLOYED, null, deployment));
+      myLocalDeployments.put(myDeploymentName, new DeploymentImpl(myDeploymentName, DeploymentStatus.DEPLOYED, null, deployment));
       myEventDispatcher.queueDeploymentsChanged(ServerConnectionImpl.this);
     }
 
     @Override
     public void errorOccurred(@NotNull String errorMessage) {
-      myLocalDeployments.put(mySource, new DeploymentImpl(myDeploymentName, DeploymentStatus.NOT_DEPLOYED, errorMessage, null));
+      myLocalDeployments.put(myDeploymentName, new DeploymentImpl(myDeploymentName, DeploymentStatus.NOT_DEPLOYED, errorMessage, null));
       myEventDispatcher.queueDeploymentsChanged(ServerConnectionImpl.this);
     }
   }
diff --git a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionManagerImpl.java b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionManagerImpl.java
index af9d141..d480270c 100644
--- a/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionManagerImpl.java
+++ b/platform/remote-servers/impl/src/com/intellij/remoteServer/impl/runtime/ServerConnectionManagerImpl.java
@@ -17,7 +17,7 @@
  * @author nik
  */
 public class ServerConnectionManagerImpl extends ServerConnectionManager {
-  private Map<RemoteServer<?>, ServerConnection> myConnections = new HashMap<RemoteServer<?>, ServerConnection>();
+  private final Map<RemoteServer<?>, ServerConnection> myConnections = new HashMap<RemoteServer<?>, ServerConnection>();
   private final ServerConnectionEventDispatcher myEventDispatcher = new ServerConnectionEventDispatcher();
 
   @NotNull
@@ -27,7 +27,7 @@
     ServerConnection connection = myConnections.get(server);
     if (connection == null) {
       ServerTaskExecutorImpl executor = new ServerTaskExecutorImpl();
-      connection = new ServerConnectionImpl(server, server.getType().createConnector(server.getConfiguration(), executor), myEventDispatcher);
+      connection = new ServerConnectionImpl(server, server.getType().createConnector(server.getConfiguration(), executor), this);
       myConnections.put(server, connection);
       myEventDispatcher.fireConnectionCreated(connection);
     }
@@ -40,6 +40,15 @@
     return myConnections.get(server);
   }
 
+  public void removeConnection(RemoteServer<?> server) {
+    ApplicationManager.getApplication().assertIsDispatchThread();
+    myConnections.remove(server);
+  }
+
+  public ServerConnectionEventDispatcher getEventDispatcher() {
+    return myEventDispatcher;
+  }
+
   @NotNull
   @Override
   public Collection<ServerConnection> getConnections() {
diff --git a/platform/util/src/com/intellij/Patches.java b/platform/util/src/com/intellij/Patches.java
index 055a673..44307c3 100644
--- a/platform/util/src/com/intellij/Patches.java
+++ b/platform/util/src/com/intellij/Patches.java
@@ -28,6 +28,7 @@
 
   /**
    * Debugger hangs on any attempt to attach/listen Connector when attach hanged once.
+   * @deprecated to remove in IDEA 13 (IDEA support JRE only >= 1.6)
    */
   public static final boolean SUN_JDI_CONNECTOR_HANGUP_BUG = !SystemInfo.isJavaVersionAtLeast("1.5");
 
diff --git a/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListProcessor.java b/platform/util/src/com/intellij/openapi/util/text/DelimitedListProcessor.java
similarity index 97%
rename from xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListProcessor.java
rename to platform/util/src/com/intellij/openapi/util/text/DelimitedListProcessor.java
index ba05968..07142b4 100644
--- a/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListProcessor.java
+++ b/platform/util/src/com/intellij/openapi/util/text/DelimitedListProcessor.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package com.intellij.util.xml.converters;
+package com.intellij.openapi.util.text;
 
 import org.jetbrains.annotations.NotNull;
 
diff --git a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java
index 82bd5a4..afafbaf 100644
--- a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java
+++ b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java
@@ -248,7 +248,6 @@
     return html.replaceAll("<(.|\n)*?>", "");
   }
 
-  @Nullable
   public static String toLowerCase(@Nullable final String str) {
     //noinspection ConstantConditions
     return str == null ? null : str.toLowerCase();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/InspectionGadgetsFix.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/InspectionGadgetsFix.java
index 4ad523c..1aa6827 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/InspectionGadgetsFix.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/InspectionGadgetsFix.java
@@ -127,7 +127,7 @@
     final Project project = statement.getProject();
     final CodeStyleManager styleManager = CodeStyleManager.getInstance(project);
     final JavaCodeStyleManager javaStyleManager = JavaCodeStyleManager.getInstance(project);
-    if (FileTypeUtils.isInJsp(statement)) {
+    if (FileTypeUtils.isInServerPageFile(statement)) {
       final PsiDocumentManager documentManager = PsiDocumentManager.getInstance(project);
       final PsiFile jspFile = PsiUtilCore.getTemplateLanguageFile(statement);
       if (jspFile == null) {
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EmptyStatementBodyInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EmptyStatementBodyInspection.java
index 722c2d1..5e3b4c4 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EmptyStatementBodyInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EmptyStatementBodyInspection.java
@@ -106,7 +106,7 @@
     }
 
     private void checkLoopStatement(PsiLoopStatement statement) {
-      if (FileTypeUtils.isInJsp(statement)) {
+      if (FileTypeUtils.isInServerPageFile(statement)) {
         return;
       }
       final PsiStatement body = statement.getBody();
@@ -119,7 +119,7 @@
     @Override
     public void visitIfStatement(@NotNull PsiIfStatement statement) {
       super.visitIfStatement(statement);
-      if (FileTypeUtils.isInJsp(statement)) {
+      if (FileTypeUtils.isInServerPageFile(statement)) {
         return;
       }
       final PsiStatement thenBranch = statement.getThenBranch();
@@ -140,7 +140,7 @@
     @Override
     public void visitSwitchStatement(PsiSwitchStatement statement) {
       super.visitSwitchStatement(statement);
-      if (FileTypeUtils.isInJsp(statement)) {
+      if (FileTypeUtils.isInServerPageFile(statement)) {
         return;
       }
       final PsiCodeBlock body = statement.getBody();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryContinueInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryContinueInspection.java
index 05b4bb6..36a0dc90 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryContinueInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryContinueInspection.java
@@ -70,7 +70,7 @@
 
     @Override
     public void visitContinueStatement(@NotNull PsiContinueStatement statement) {
-      if (FileTypeUtils.isInJsp(statement.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(statement.getContainingFile())) {
         return;
       }
       final PsiStatement continuedStatement = statement.findContinuedStatement();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryReturnInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryReturnInspection.java
index 42d07b5..5c8f1df 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryReturnInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/controlflow/UnnecessaryReturnInspection.java
@@ -80,7 +80,7 @@
     @Override
     public void visitReturnStatement(@NotNull PsiReturnStatement statement) {
       super.visitReturnStatement(statement);
-      if (FileTypeUtils.isInJsp(statement.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(statement.getContainingFile())) {
         return;
       }
       if (statement.getReturnValue() != null) {
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/dataflow/TooBroadScopeInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/dataflow/TooBroadScopeInspectionBase.java
index ca336ff..07b7786 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/dataflow/TooBroadScopeInspectionBase.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/dataflow/TooBroadScopeInspectionBase.java
@@ -216,7 +216,7 @@
           return;
         }
       }
-      if (insertionPoint != null && FileTypeUtils.isInJsp(insertionPoint)) {
+      if (insertionPoint != null && FileTypeUtils.isInServerPageFile(insertionPoint)) {
         PsiElement elementBefore = insertionPoint.getPrevSibling();
         elementBefore = PsiTreeUtil.skipSiblingsBackward(elementBefore, PsiWhiteSpace.class);
         if (elementBefore instanceof PsiDeclarationStatement) {
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyCatchBlockInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyCatchBlockInspection.java
index f5db89a1..207e5e7 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyCatchBlockInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyCatchBlockInspection.java
@@ -119,7 +119,7 @@
     @Override
     public void visitTryStatement(@NotNull PsiTryStatement statement) {
       super.visitTryStatement(statement);
-      if (FileTypeUtils.isInJsp(statement.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(statement.getContainingFile())) {
         return;
       }
       if (m_ignoreTestCases && TestUtils.isInTestCode(statement)) {
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyFinallyBlockInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyFinallyBlockInspection.java
index d2e428e..41ed575 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyFinallyBlockInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyFinallyBlockInspection.java
@@ -150,7 +150,7 @@
     public void visitTryStatement(
       @NotNull PsiTryStatement statement) {
       super.visitTryStatement(statement);
-      if (FileTypeUtils.isInJsp(statement.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(statement.getContainingFile())) {
         return;
       }
       final PsiCodeBlock finallyBlock = statement.getFinallyBlock();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyTryBlockInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyTryBlockInspection.java
index 346d07f..57003f5 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyTryBlockInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/errorhandling/EmptyTryBlockInspection.java
@@ -54,7 +54,7 @@
     @Override
     public void visitTryStatement(@NotNull PsiTryStatement statement) {
       super.visitTryStatement(statement);
-      if (FileTypeUtils.isInJsp(statement.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(statement.getContainingFile())) {
         return;
       }
       final PsiCodeBlock finallyBlock = statement.getTryBlock();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/JavaLangImportInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/JavaLangImportInspection.java
index 691ccef..36c31ac 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/JavaLangImportInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/JavaLangImportInspection.java
@@ -60,7 +60,7 @@
       if (!(aClass.getParent() instanceof PsiJavaFile)) {
         return;
       }
-      if (FileTypeUtils.isInJsp(aClass.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(aClass.getContainingFile())) {
         return;
       }
       final PsiJavaFile file = (PsiJavaFile)aClass.getContainingFile();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/OnDemandImportInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/OnDemandImportInspection.java
index 0115add..d9d9dd9 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/OnDemandImportInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/OnDemandImportInspection.java
@@ -51,7 +51,7 @@
         return;
       }
       final PsiJavaFile file = (PsiJavaFile)parent;
-      if (FileTypeUtils.isInJsp(aClass.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(aClass.getContainingFile())) {
         return;
       }
       if (!file.getClasses()[0].equals(aClass)) {
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SamePackageImportInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SamePackageImportInspection.java
index 5764a30..579a20b 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SamePackageImportInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SamePackageImportInspection.java
@@ -59,7 +59,7 @@
       if (!(parent instanceof PsiJavaFile)) {
         return;
       }
-      if (FileTypeUtils.isInJsp(importList)) {
+      if (FileTypeUtils.isInServerPageFile(importList)) {
         return;
       }
       final PsiJavaFile javaFile = (PsiJavaFile)parent;
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SingleClassImportInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SingleClassImportInspection.java
index f358ed0..91692ab 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SingleClassImportInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/SingleClassImportInspection.java
@@ -54,7 +54,7 @@
       if (!(aClass.getParent() instanceof PsiJavaFile)) {
         return;
       }
-      if (FileTypeUtils.isInJsp(aClass.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(aClass.getContainingFile())) {
         return;
       }
       final PsiJavaFile file = (PsiJavaFile)aClass.getParent();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/UnusedImportInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/UnusedImportInspection.java
index 3df4e44..49c58d1 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/UnusedImportInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/imports/UnusedImportInspection.java
@@ -58,7 +58,7 @@
 
     @Override
     public void visitJavaFile(PsiJavaFile file) {
-      if (FileTypeUtils.isInJsp(file)) {
+      if (FileTypeUtils.isInServerPageFile(file)) {
         return;
       }
       final PsiClass[] classes = file.getClasses();
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java
index f62c0bb..da42176 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/j2me/PrivateMemberAccessBetweenOuterAndInnerClassInspection.java
@@ -170,7 +170,7 @@
 
     @Override
     public void visitNewExpression(PsiNewExpression expression) {
-      if (FileTypeUtils.isInJsp(expression)) {
+      if (FileTypeUtils.isInServerPageFile(expression)) {
         return;
       }
       super.visitNewExpression(expression);
@@ -214,7 +214,7 @@
     @Override
     public void visitReferenceExpression(
       @NotNull PsiReferenceExpression expression) {
-      if (FileTypeUtils.isInJsp(expression)) {
+      if (FileTypeUtils.isInServerPageFile(expression)) {
         // disable for jsp files IDEADEV-12957
         return;
       }
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javabeans/ClassWithoutConstructorInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javabeans/ClassWithoutConstructorInspection.java
index 96567a0..c7c734b 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javabeans/ClassWithoutConstructorInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/javabeans/ClassWithoutConstructorInspection.java
@@ -104,7 +104,7 @@
     public void visitClass(@NotNull PsiClass aClass) {
       // no call to super, so it doesn't drill down
       if (aClass.isInterface() || aClass.isEnum() ||
-          aClass.isAnnotationType() || FileTypeUtils.isInJsp(aClass)) {
+          aClass.isAnnotationType() || FileTypeUtils.isInServerPageFile(aClass)) {
         return;
       }
       if (aClass instanceof PsiTypeParameter ||
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java
index a969b2f..98ec40b 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2010-2011 Bas Leijdekkers
+ * Copyright 2010-2013 Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -27,23 +27,19 @@
 
 import java.util.Set;
 
-public class ExpectedExceptionNeverThrownInspection
-  extends BaseInspection {
+public class ExpectedExceptionNeverThrownInspection extends BaseInspection {
   @Nls
   @NotNull
   @Override
   public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "expected.exception.never.thrown.display.name");
+    return InspectionGadgetsBundle.message("expected.exception.never.thrown.display.name");
   }
 
   @NotNull
   @Override
   protected String buildErrorString(Object... infos) {
     final PsiMethod method = (PsiMethod)infos[0];
-    return InspectionGadgetsBundle.message(
-      "expected.exception.never.thrown.problem.descriptor",
-      method.getName());
+    return InspectionGadgetsBundle.message("expected.exception.never.thrown.problem.descriptor", method.getName());
   }
 
   @Override
@@ -51,19 +47,16 @@
     return new ExpectedExceptionNeverThrownVisitor();
   }
 
-  private static class ExpectedExceptionNeverThrownVisitor
-    extends BaseInspectionVisitor {
+  private static class ExpectedExceptionNeverThrownVisitor extends BaseInspectionVisitor {
 
     @Override
     public void visitMethod(PsiMethod method) {
       super.visitMethod(method);
-      final PsiAnnotation annotation =
-        AnnotationUtil.findAnnotation(method, "org.junit.Test");
+      final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, "org.junit.Test");
       if (annotation == null) {
         return;
       }
-      final PsiAnnotationParameterList parameterList =
-        annotation.getParameterList();
+      final PsiAnnotationParameterList parameterList = annotation.getParameterList();
       final PsiNameValuePair[] attributes = parameterList.getAttributes();
       PsiAnnotationMemberValue value = null;
       for (PsiNameValuePair attribute : attributes) {
@@ -79,22 +72,19 @@
       if (body == null) {
         return;
       }
-      final PsiClassObjectAccessExpression classObjectAccessExpression =
-        (PsiClassObjectAccessExpression)value;
-      final PsiTypeElement operand =
-        classObjectAccessExpression.getOperand();
+      final PsiClassObjectAccessExpression classObjectAccessExpression = (PsiClassObjectAccessExpression)value;
+      final PsiTypeElement operand = classObjectAccessExpression.getOperand();
       final PsiType type = operand.getType();
       if (!(type instanceof PsiClassType)) {
         return;
       }
       final PsiClassType classType = (PsiClassType)type;
       final PsiClass aClass = classType.resolve();
-      if (InheritanceUtil.isInheritor(aClass,
-                                      CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION)) {
+      if (InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_LANG_RUNTIME_EXCEPTION) ||
+        InheritanceUtil.isInheritor(aClass, CommonClassNames.JAVA_LANG_ERROR)) {
         return;
       }
-      final Set<PsiClassType> exceptionsThrown =
-        ExceptionUtils.calculateExceptionsThrown(body);
+      final Set<PsiClassType> exceptionsThrown = ExceptionUtils.calculateExceptionsThrown(body);
       if (exceptionsThrown.contains(classType)) {
         return;
       }
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/FileTypeUtils.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/FileTypeUtils.java
index 7f07a6b..7888121 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/FileTypeUtils.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/psiutils/FileTypeUtils.java
@@ -20,7 +20,7 @@
 import com.intellij.psi.util.PsiUtilCore;
 
 public class FileTypeUtils {
-  public static boolean isInJsp(PsiElement file) {
+  public static boolean isInServerPageFile(PsiElement file) {
     return PsiUtilCore.getTemplateLanguageFile(file) instanceof ServerPageFile;
   }
 }
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/security/DesignForExtensionInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/security/DesignForExtensionInspection.java
index 04052a3..7df6ad2 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/security/DesignForExtensionInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/security/DesignForExtensionInspection.java
@@ -47,7 +47,7 @@
 
     @Override
     public void visitMethod(PsiMethod method) {
-      if (FileTypeUtils.isInJsp(method)) {
+      if (FileTypeUtils.isInServerPageFile(method)) {
         // IDEADEV-25538
         return;
       }
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java
index 08adf0c6..a134ce56 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/style/EqualsCalledOnEnumConstantInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2008 Bas Leijdekkers
+ * Copyright 2008-2013 Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,7 +19,7 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.*;
 import com.intellij.psi.tree.IElementType;
-import com.intellij.util.IncorrectOperationException;
+import com.intellij.psi.util.TypeConversionUtil;
 import com.siyeh.InspectionGadgetsBundle;
 import com.siyeh.ig.BaseInspection;
 import com.siyeh.ig.BaseInspectionVisitor;
@@ -35,15 +35,13 @@
   @Nls
   @NotNull
   public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "equals.called.on.enum.constant.display.name");
+    return InspectionGadgetsBundle.message("equals.called.on.enum.constant.display.name");
   }
 
   @Override
   @NotNull
   protected String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "equals.called.on.enum.constant.problem.descriptor");
+    return InspectionGadgetsBundle.message("equals.called.on.enum.constant.problem.descriptor");
   }
 
   @Override
@@ -56,19 +54,16 @@
     return new EqualsCalledOnEnumValueFix();
   }
 
-  private static class EqualsCalledOnEnumValueFix
-    extends InspectionGadgetsFix {
+  private static class EqualsCalledOnEnumValueFix extends InspectionGadgetsFix {
 
     @Override
     @NotNull
     public String getName() {
-      return InspectionGadgetsBundle.message(
-        "equals.called.on.enum.constant.quickfix");
+      return InspectionGadgetsBundle.message("equals.called.on.enum.constant.quickfix");
     }
 
     @Override
-    protected void doFix(Project project, ProblemDescriptor descriptor)
-      throws IncorrectOperationException {
+    protected void doFix(Project project, ProblemDescriptor descriptor) {
       final PsiElement element = descriptor.getPsiElement();
       final PsiElement parent = element.getParent();
       if (parent == null) {
@@ -78,18 +73,14 @@
       if (!(grandParent instanceof PsiMethodCallExpression)) {
         return;
       }
-      final PsiMethodCallExpression methodCallExpression =
-        (PsiMethodCallExpression)grandParent;
-      final PsiExpressionList argumentList =
-        methodCallExpression.getArgumentList();
+      final PsiMethodCallExpression methodCallExpression = (PsiMethodCallExpression)grandParent;
+      final PsiExpressionList argumentList = methodCallExpression.getArgumentList();
       final PsiExpression[] arguments = argumentList.getExpressions();
       if (arguments.length > 1) {
         return;
       }
-      final PsiReferenceExpression methodExpression =
-        methodCallExpression.getMethodExpression();
-      final PsiExpression qualifier =
-        methodExpression.getQualifierExpression();
+      final PsiReferenceExpression methodExpression = methodCallExpression.getMethodExpression();
+      final PsiExpression qualifier = methodExpression.getQualifierExpression();
       if (qualifier == null) {
         return;
       }
@@ -99,8 +90,7 @@
       final PsiPrefixExpression prefixExpression;
       if (greatGrandParent instanceof PsiPrefixExpression) {
         prefixExpression = (PsiPrefixExpression)greatGrandParent;
-        final IElementType tokenType =
-          prefixExpression.getOperationTokenType();
+        final IElementType tokenType = prefixExpression.getOperationTokenType();
         not = JavaTokenType.EXCL == tokenType;
       }
       else {
@@ -121,8 +111,7 @@
         replaceExpression(prefixExpression, newExpression.toString());
       }
       else {
-        replaceExpression(methodCallExpression,
-                          newExpression.toString());
+        replaceExpression(methodCallExpression, newExpression.toString());
       }
     }
   }
@@ -132,22 +121,25 @@
     return new EqualsCalledOnEnumValueVisitor();
   }
 
-  private static class EqualsCalledOnEnumValueVisitor
-    extends BaseInspectionVisitor {
+  private static class EqualsCalledOnEnumValueVisitor extends BaseInspectionVisitor {
 
     @Override
-    public void visitMethodCallExpression(
-      @NotNull PsiMethodCallExpression expression) {
+    public void visitMethodCallExpression(@NotNull PsiMethodCallExpression expression) {
       super.visitMethodCallExpression(expression);
       if (!MethodCallUtils.isEqualsCall(expression)) {
         return;
       }
-      final PsiReferenceExpression methodExpression =
-        expression.getMethodExpression();
-      final PsiExpression qualifier =
-        methodExpression.getQualifierExpression();
-      if (!TypeUtils.expressionHasTypeOrSubtype(qualifier,
-                                                CommonClassNames.JAVA_LANG_ENUM)) {
+      final PsiReferenceExpression methodExpression = expression.getMethodExpression();
+      final PsiExpression qualifier = methodExpression.getQualifierExpression();
+      if (qualifier == null || !TypeUtils.expressionHasTypeOrSubtype(qualifier, CommonClassNames.JAVA_LANG_ENUM)) {
+        return;
+      }
+      final PsiExpressionList argumentList = expression.getArgumentList();
+      final PsiExpression[] arguments = argumentList.getExpressions();
+      final PsiType comparedTypeErasure = TypeConversionUtil.erasure(qualifier.getType());
+      final PsiType comparisonTypeErasure = TypeConversionUtil.erasure(arguments[0].getType());
+      if (comparedTypeErasure == null || comparisonTypeErasure == null ||
+          !TypeConversionUtil.areTypesConvertible(comparedTypeErasure, comparisonTypeErasure)) {
         return;
       }
       registerMethodCallError(expression, expression);
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/EmptySynchronizedStatementInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/EmptySynchronizedStatementInspection.java
index 5707639..43060f7 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/EmptySynchronizedStatementInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/threading/EmptySynchronizedStatementInspection.java
@@ -52,7 +52,7 @@
     public void visitSynchronizedStatement(
       @NotNull PsiSynchronizedStatement statement) {
       super.visitSynchronizedStatement(statement);
-      if (FileTypeUtils.isInJsp(statement.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(statement.getContainingFile())) {
         return;
       }
       final PsiCodeBlock body = statement.getBody();
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java
index c55b406..9b5861c 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java
@@ -70,7 +70,7 @@
     @Override
     public void visitClass(@NotNull PsiClass aClass) {
       // no call to super, so that it doesn't drill down to inner classes
-      if (FileTypeUtils.isInJsp(aClass)) {
+      if (FileTypeUtils.isInServerPageFile(aClass)) {
         return;
       }
       if (ClassUtils.isInnerClass(aClass)) {
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassNameDiffersFromFileNameInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassNameDiffersFromFileNameInspection.java
index e8c9f43..cd7c3c0 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassNameDiffersFromFileNameInspection.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassNameDiffersFromFileNameInspection.java
@@ -71,7 +71,7 @@
     @Override
     public void visitClass(@NotNull PsiClass aClass) {
       // no call to super, so that it doesn't drill down to inner classes
-      if (FileTypeUtils.isInJsp(aClass)) {
+      if (FileTypeUtils.isInServerPageFile(aClass)) {
         return;
       }
       final PsiElement parent = aClass.getParent();
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/EmptyClassInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/EmptyClassInspection.java
index fce8f899..85b42f1e 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/EmptyClassInspection.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/EmptyClassInspection.java
@@ -126,7 +126,7 @@
     @Override
     public void visitClass(@NotNull PsiClass aClass) {
       //don't call super, to prevent drilldown
-      if (FileTypeUtils.isInJsp(aClass.getContainingFile())) {
+      if (FileTypeUtils.isInServerPageFile(aClass.getContainingFile())) {
         return;
       }
       if (aClass.isInterface() || aClass.isEnum() || aClass.isAnnotationType()) {
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/imports/StaticImportInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/imports/StaticImportInspection.java
index def9d4f..167e800 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/imports/StaticImportInspection.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/imports/StaticImportInspection.java
@@ -277,7 +277,7 @@
         return;
       }
       final PsiJavaFile file = (PsiJavaFile)parent;
-      if (FileTypeUtils.isInJsp(file)) {
+      if (FileTypeUtils.isInServerPageFile(file)) {
         return;
       }
       if (!file.getClasses()[0].equals(aClass)) {
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/equals_called_on_enum_constant/EqualsCalled.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/equals_called_on_enum_constant/EqualsCalled.java
index 72cd8bf..195c38b 100644
--- a/plugins/InspectionGadgets/test/com/siyeh/igtest/style/equals_called_on_enum_constant/EqualsCalled.java
+++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/style/equals_called_on_enum_constant/EqualsCalled.java
@@ -13,3 +13,12 @@
         A.equals(1);
     }
 }
+class Main {
+  enum Suit {
+    SPADES, HEARTS, DIAMONDS, CLUBS
+  }
+
+  private boolean equalsType(Suit suit, String type) {
+    return suit.equals(type);
+  }
+}
diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspectionTest.java
new file mode 100644
index 0000000..e057666
--- /dev/null
+++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/junit/ExpectedExceptionNeverThrownInspectionTest.java
@@ -0,0 +1,47 @@
+/**
+ * (c) 2013 Desert Island BV
+ * created: 14 08 2013
+ */
+package com.siyeh.ig.junit;
+
+import com.intellij.codeInspection.LocalInspectionTool;
+import com.siyeh.ig.LightInspectionTestCase;
+
+/**
+ * @author Bas Leijdekkers
+ */
+public class ExpectedExceptionNeverThrownInspectionTest extends LightInspectionTestCase {
+  @Override
+  protected LocalInspectionTool getInspection() {
+    return new ExpectedExceptionNeverThrownInspection();
+  }
+
+  @Override
+  protected String[] getEnvironmentClasses() {
+    return new String[] {"package org.junit; " +
+                         "public @interface Test {\n" +
+                         "    java.lang.Class<? extends java.lang.Throwable> expected() default org.junit.Test.None.class;" +
+                         "}"};
+  }
+
+  public void testSimple() {
+    doTest("class X {" +
+           "    @org.junit.Test(expected=/*Expected 'java.io.IOException' never thrown in body of 'test()'*/java.io.IOException/**/.class)" +
+           "    public void test() {}" +
+           "}");
+  }
+
+  public void testError() {
+    doTest("class X {" +
+           "    @org.junit.Test(expected = Error.class)" +
+           "    public void test() {}" +
+           "}");
+  }
+
+  public void testRuntimeException() {
+    doTest("class X {" +
+           "    @org.junit.Test(expected = IllegalArgumentException.class)" +
+           "    public void test() {}" +
+           "}");
+  }
+}
diff --git a/plugins/IntelliLang/IntelliLang-tests/test/org/intellij/plugins/intelliLang/ReferenceInjectionTest.java b/plugins/IntelliLang/IntelliLang-tests/test/org/intellij/plugins/intelliLang/ReferenceInjectionTest.java
index 75fead4..1422228 100644
--- a/plugins/IntelliLang/IntelliLang-tests/test/org/intellij/plugins/intelliLang/ReferenceInjectionTest.java
+++ b/plugins/IntelliLang/IntelliLang-tests/test/org/intellij/plugins/intelliLang/ReferenceInjectionTest.java
@@ -6,7 +6,7 @@
 import com.intellij.psi.PsiReference;
 import com.intellij.psi.impl.PsiModificationTrackerImpl;
 import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
+import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
 import org.intellij.plugins.intelliLang.inject.InjectLanguageAction;
 import org.intellij.plugins.intelliLang.inject.UnInjectLanguageAction;
 import org.intellij.plugins.intelliLang.references.FileReferenceInjector;
@@ -18,7 +18,7 @@
  * @author Dmitry Avdeev
  *         Date: 02.08.13
  */
-public class ReferenceInjectionTest extends LightPlatformCodeInsightFixtureTestCase {
+public class ReferenceInjectionTest extends LightCodeInsightFixtureTestCase {
 
   public void testInjectReference() throws Exception {
 
@@ -87,11 +87,20 @@
     assertNull(getInjectedReferences());
   }
 
+  public void testInjectByAnnotation() throws Exception {
+    myFixture.configureByText("Foo.java", "class Foo {\n" +
+                                          "    @org.intellij.lang.annotations.Language(\"file-reference\")\n" +
+                                          "    String bar() {\n" +
+                                          "       return \"<error descr=\"Cannot resolve file 'unknown.file'\">unknown.file</error>\";\n" +
+                                          "    }  \n" +
+                                          "}");
+    myFixture.testHighlighting();
+  }
+
   private PsiReference[] getInjectedReferences() {
     PsiElement element = myFixture.getFile().findElementAt(myFixture.getCaretOffset());
     element = PsiTreeUtil.getParentOfType(element, PsiLanguageInjectionHost.class);
     assertNotNull(element);
-    element.getReferences();
     return InjectedReferencesContributor.getInjectedReferences(element);
   }
 
@@ -106,9 +115,4 @@
     myFixture.disableInspections(new InjectedReferencesInspection());
     super.tearDown();
   }
-
-  @Override
-  protected boolean isWriteActionRequired() {
-    return false;
-  }
 }
diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java
index b2f1360..32378d0 100644
--- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java
+++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/ConcatenationInjector.java
@@ -28,6 +28,7 @@
 import com.intellij.psi.*;
 import com.intellij.psi.impl.java.stubs.index.JavaAnnotationIndex;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
+import com.intellij.psi.injection.ReferenceInjector;
 import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.psi.search.LocalSearchScope;
 import com.intellij.psi.search.searches.ReferencesSearch;
@@ -374,8 +375,15 @@
     }
 
     private void processInjectionWithContext(BaseInjection injection, boolean settingsAvailable) {
-      final Language language = InjectedLanguage.findLanguageById(injection.getInjectedLanguageId());
-      if (language == null) return;
+      Language language = InjectedLanguage.findLanguageById(injection.getInjectedLanguageId());
+      if (language == null) {
+        ReferenceInjector injector = ReferenceInjector.findById(injection.getInjectedLanguageId());
+        if (injector != null) {
+          language = injector.toLanguage();
+        }
+        else return;
+      }
+
       final boolean separateFiles = !injection.isSingleFile() && StringUtil.isNotEmpty(injection.getValuePattern());
 
       final Ref<Boolean> unparsableRef = Ref.create(myUnparsable);
diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java
index 7bf11d2..a453933 100644
--- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java
+++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/JavaLanguageInjectionSupport.java
@@ -19,6 +19,7 @@
 import com.intellij.codeInsight.AnnotationUtil;
 import com.intellij.codeInsight.daemon.impl.quickfix.OrderEntryFix;
 import com.intellij.lang.Language;
+import com.intellij.lang.injection.MultiHostRegistrar;
 import com.intellij.openapi.actionSystem.AnAction;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.application.Result;
@@ -40,10 +41,7 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.ui.SimpleColoredText;
 import com.intellij.ui.SimpleTextAttributes;
-import com.intellij.util.ArrayUtil;
-import com.intellij.util.Consumer;
-import com.intellij.util.NullableFunction;
-import com.intellij.util.PlatformIcons;
+import com.intellij.util.*;
 import com.intellij.util.containers.ContainerUtil;
 import gnu.trove.THashSet;
 import org.intellij.plugins.intelliLang.AdvancedSettingsUI;
@@ -103,7 +101,7 @@
 
   public boolean addInjectionInPlace(final Language language, final PsiLanguageInjectionHost psiElement) {
     if (!isMine(psiElement)) return false;
-    return doInjectInJava(psiElement.getProject(), psiElement, language.getID());
+    return doInjectInJava(psiElement.getProject(), psiElement, psiElement, language.getID());
   }
 
   public boolean removeInjectionInPlace(final PsiLanguageInjectionHost psiElement) {
@@ -141,7 +139,8 @@
     if (injectionsMap.isEmpty() || !annotations.isEmpty()) return false;
 
     final BaseInjection originalInjection = injectionsMap.keySet().iterator().next();
-    final MethodParameterInjection methodParameterInjection = createFrom(psiElement.getProject(), originalInjection, injectionsMap.get(originalInjection).first, false);
+    final MethodParameterInjection methodParameterInjection = createFrom(psiElement.getProject(), originalInjection,
+                                                                         injectionsMap.get(originalInjection).first, false);
     final MethodParameterInjection copy = methodParameterInjection.copy();
     final BaseInjection newInjection = showInjectionUI(project, methodParameterInjection);
     if (newInjection != null) {
@@ -182,43 +181,66 @@
     else return new BaseInjection(JAVA_SUPPORT_ID);
   }
 
-  private static boolean doInjectInJava(final Project project, final PsiElement host, final String languageId) {
-    final PsiElement target = ContextComputationProcessor.getTopLevelInjectionTarget(host);
+  private static boolean doInjectInJava(final Project project,
+                                        final PsiElement psiElement,
+                                        PsiLanguageInjectionHost host,
+                                        final String languageId) {
+    final PsiElement target = ContextComputationProcessor.getTopLevelInjectionTarget(psiElement);
     final PsiElement parent = target.getParent();
     if (parent instanceof PsiReturnStatement ||
         parent instanceof PsiMethod ||
         parent instanceof PsiNameValuePair) {
-      return doInjectInJavaMethod(project, findPsiMethod(parent), -1, languageId);
+      return doInjectInJavaMethod(project, findPsiMethod(parent), -1, host, languageId);
     }
     else if (parent instanceof PsiExpressionList && parent.getParent() instanceof PsiCallExpression) {
-      return doInjectInJavaMethod(project, findPsiMethod(parent), findParameterIndex(target, (PsiExpressionList)parent), languageId);
+      return doInjectInJavaMethod(project, findPsiMethod(parent), findParameterIndex(target, (PsiExpressionList)parent), host, languageId);
     }
     else if (parent instanceof PsiAssignmentExpression) {
       final PsiExpression psiExpression = ((PsiAssignmentExpression)parent).getLExpression();
       if (psiExpression instanceof PsiReferenceExpression) {
         final PsiElement element = ((PsiReferenceExpression)psiExpression).resolve();
         if (element != null) {
-          return doInjectInJava(project, element, languageId);
+          return doInjectInJava(project, element, host, languageId);
         }
       }
     }
     else if (parent instanceof PsiVariable) {
-      if (doAddLanguageAnnotation(project, (PsiModifierListOwner)parent, languageId)) return true;
+      if (doAddLanguageAnnotation(project, (PsiModifierListOwner)parent, host, languageId)) return true;
     }
     else if (target instanceof PsiVariable) {
-      if (doAddLanguageAnnotation(project, (PsiModifierListOwner)target, languageId)) return true;
+      if (doAddLanguageAnnotation(project, (PsiModifierListOwner)target, host, languageId)) return true;
     }
     return false;
   }
 
-  public static boolean doAddLanguageAnnotation(final Project project, final PsiModifierListOwner modifierListOwner, final String languageId) {
-    if (!Configuration.getProjectInstance(project).getAdvancedConfiguration().isSourceModificationAllowed()) return false;
+  public static boolean doAddLanguageAnnotation(final Project project,
+                                                final PsiModifierListOwner modifierListOwner,
+                                                @NotNull PsiLanguageInjectionHost host,
+                                                final String languageId) {
     if (modifierListOwner.getModifierList() == null || !PsiUtil.isLanguageLevel5OrHigher(modifierListOwner)) return false;
-    if (!OrderEntryFix.isAnnotationsJarInPath(ModuleUtilCore.findModuleForPsiElement(modifierListOwner))) {
+    final Configuration.AdvancedConfiguration configuration = Configuration.getProjectInstance(project).getAdvancedConfiguration();
+    if (!configuration.isSourceModificationAllowed()) {
       // todo add languageId comment
+      host.putUserData(InjectLanguageAction.FIX_KEY, new Processor<PsiLanguageInjectionHost>() {
+        @Override
+        public boolean process(PsiLanguageInjectionHost host) {
+          boolean allowed = configuration.isSourceModificationAllowed();
+          configuration.setSourceModificationAllowed(true);
+          try {
+            return doInjectInJava(project, host, host, languageId);
+          }
+          finally {
+            configuration.setSourceModificationAllowed(allowed);
+          }
+        }
+      });
+
       return false;
     }
-    new WriteCommandAction(project, modifierListOwner.getContainingFile()) {
+    if (!OrderEntryFix.ensureAnnotationsJarInPath(ModuleUtilCore.findModuleForPsiElement(modifierListOwner))) {
+      return false;
+    }
+    new WriteCommandAction(modifierListOwner.getProject(), modifierListOwner.getContainingFile()) {
       protected void run(final Result result) throws Throwable {
         JVMElementFactory factory = JVMElementFactories.getFactory(modifierListOwner.getLanguage(), modifierListOwner.getProject());
         if (factory == null) {
@@ -243,19 +265,21 @@
   public static boolean doInjectInJavaMethod(@NotNull final Project project,
                                              @Nullable final PsiMethod psiMethod,
                                              final int parameterIndex,
-                                             @NotNull final String languageId) {
+                                             @NotNull PsiLanguageInjectionHost host, @NotNull final String languageId) {
     if (psiMethod == null) return false;
     if (parameterIndex < -1) return false;
     if (parameterIndex >= psiMethod.getParameterList().getParametersCount()) return false;
     final PsiModifierList methodModifiers = psiMethod.getModifierList();
     if (methodModifiers.hasModifierProperty(PsiModifier.PRIVATE) || methodModifiers.hasModifierProperty(PsiModifier.PACKAGE_LOCAL)) {
-      return doAddLanguageAnnotation(project, parameterIndex >= 0? psiMethod.getParameterList().getParameters()[parameterIndex] : psiMethod, languageId);
+      return doAddLanguageAnnotation(project, parameterIndex >= 0? psiMethod.getParameterList().getParameters()[parameterIndex] : psiMethod,
+                                     host, languageId);
     }
     final PsiClass containingClass = psiMethod.getContainingClass();
     assert containingClass != null;
     final PsiModifierList classModifiers = containingClass.getModifierList();
     if (classModifiers != null && (classModifiers.hasModifierProperty(PsiModifier.PRIVATE) || classModifiers.hasModifierProperty(PsiModifier.PACKAGE_LOCAL))) {
-      return doAddLanguageAnnotation(project, parameterIndex >= 0? psiMethod.getParameterList().getParameters()[parameterIndex] : psiMethod, languageId);
+      return doAddLanguageAnnotation(project, parameterIndex >= 0? psiMethod.getParameterList().getParameters()[parameterIndex] : psiMethod,
+                                     host, languageId);
     }
 
     final String className = containingClass.getQualifiedName();
@@ -427,7 +451,8 @@
           if (!visitedSignatures.add(methodInfo.getMethodSignature())) continue;
           if (isInjectable(method.getReturnType(), method.getProject())) {
             final int parameterIndex = -1;
-            int index = ArrayUtil.find(injection.getInjectionPlaces(), new InjectionPlace(compiler.compileElementPattern(getPatternStringForJavaPlace(method, parameterIndex)), true));
+            int index = ArrayUtilRt.find(injection.getInjectionPlaces(), new InjectionPlace(
+              compiler.compileElementPattern(getPatternStringForJavaPlace(method, parameterIndex)), true));
             final InjectionPlace place = index > -1 ? injection.getInjectionPlaces()[index] : null;
             methodInfo.setReturnFlag(place != null && place.isEnabled() || includeAllPlaces);
             add = true;
@@ -436,7 +461,9 @@
           for (int i = 0; i < parameters.length; i++) {
             final PsiParameter p = parameters[i];
             if (isInjectable(p.getType(), p.getProject())) {
-              int index = ArrayUtil.find(injection.getInjectionPlaces(), new InjectionPlace(compiler.compileElementPattern(getPatternStringForJavaPlace(method, i)), true));
+              int index = ArrayUtilRt.find(injection.getInjectionPlaces(),
+                                           new InjectionPlace(compiler.compileElementPattern(getPatternStringForJavaPlace(method, i)),
+                                                              true));
               final InjectionPlace place = index > -1 ? injection.getInjectionPlaces()[index] : null;
               methodInfo.getParamFlags()[i] = place != null && place.isEnabled() || includeAllPlaces;
               add = true;
@@ -519,6 +546,11 @@
   }
 
   @Override
+  public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
+
+  }
+
+  @Override
   public String getHelpId() {
     return "reference.settings.injection.language.injection.settings.java.parameter";
   }
diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java
index 1cd9628..c6cc44a 100644
--- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java
+++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/LanguageReference.java
@@ -17,18 +17,19 @@
 
 import com.intellij.codeInsight.lookup.LookupElement;
 import com.intellij.codeInsight.lookup.LookupElementBuilder;
-import com.intellij.lang.Language;
-import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiLiteralExpression;
+import com.intellij.psi.injection.Injectable;
 import com.intellij.util.Function;
 import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.ui.EmptyIcon;
+import org.intellij.plugins.intelliLang.inject.InjectLanguageAction;
 import org.intellij.plugins.intelliLang.inject.InjectedLanguage;
 import org.intellij.plugins.intelliLang.util.StringLiteralReference;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.List;
+
 /**
  * Provides completion for available Language-IDs in
  * <pre>@Language("[ctrl-space]")</pre>
@@ -50,22 +51,13 @@
 
   @NotNull
   public Object[] getVariants() {
-    final String[] ids = InjectedLanguage.getAvailableLanguageIDs();
-    return ContainerUtil.map2Array(ids, LookupElement.class, new Function<String, LookupElement>() {
-      public LookupElement fun(String s) {
-        final Language l = InjectedLanguage.findLanguageById(s);
-        assert l != null;
-
-        final FileType ft = l.getAssociatedFileType();
-        if (ft != null) {
-          return LookupElementBuilder.create(s).withIcon(ft.getIcon()).withTypeText(ft.getDescription());
-//                } else if (l == StdLanguages.EL) {
-//                    // IDEA-10012
-//                    return new LanguageLookupValue(s, StdFileTypes.JSP.getIcon(), "Expression Language");
-        }
-        return LookupElementBuilder.create(s).withIcon(EmptyIcon.ICON_16);
+    List<Injectable> list = InjectLanguageAction.getAllInjectables();
+    return ContainerUtil.map2Array(list, LookupElement.class, new Function<Injectable, LookupElement>() {
+      @Override
+      public LookupElement fun(Injectable injectable) {
+        return LookupElementBuilder.create(injectable.getId()).withIcon(injectable.getIcon()).withTailText(
+          "(" + injectable.getDisplayName() + ")", true);
       }
     });
   }
-
 }
diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/validation/UnknownLanguageID.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/validation/UnknownLanguageID.java
index 0fb9b31..8e33447 100644
--- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/validation/UnknownLanguageID.java
+++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/inject/java/validation/UnknownLanguageID.java
@@ -19,8 +19,8 @@
 import com.intellij.codeInspection.LocalInspectionTool;
 import com.intellij.codeInspection.ProblemHighlightType;
 import com.intellij.codeInspection.ProblemsHolder;
-import com.intellij.lang.Language;
 import com.intellij.psi.*;
+import com.intellij.psi.injection.ReferenceInjector;
 import com.intellij.psi.util.PsiTreeUtil;
 import org.intellij.plugins.intelliLang.Configuration;
 import org.intellij.plugins.intelliLang.inject.InjectedLanguage;
@@ -68,8 +68,7 @@
                 final Object id = JavaPsiFacade.getInstance(expression.getProject()).
                   getConstantEvaluationHelper().computeConstantExpression(expression);
                 if (id instanceof String) {
-                  final Language language = InjectedLanguage.findLanguageById((String)id);
-                  if (language == null) {
+                  if (InjectedLanguage.findLanguageById((String)id) == null && ReferenceInjector.findById((String)id) == null) {
                     holder.registerProblem(expression, "Unknown language '" + id + "'", ProblemHighlightType.LIKE_UNKNOWN_SYMBOL);
                   }
                 }
diff --git a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/AnnotationUtilEx.java b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/AnnotationUtilEx.java
index 2397b47..0b4360c 100644
--- a/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/AnnotationUtilEx.java
+++ b/plugins/IntelliLang/java-support/org/intellij/plugins/intelliLang/util/AnnotationUtilEx.java
@@ -44,7 +44,7 @@
    * @see AnnotationUtilEx#getAnnotatedElementFor(com.intellij.psi.PsiElement, LookupType)
    */
   public enum LookupType {
-    PREFER_CONTEXT, PREFER_DECLARATION, CONTEXT_ONLY, DECLRARATION_ONLY
+    PREFER_CONTEXT, PREFER_DECLARATION, CONTEXT_ONLY, DECLARATION_ONLY
   }
 
   /**
@@ -55,13 +55,13 @@
   @Nullable
   public static PsiModifierListOwner getAnnotatedElementFor(@Nullable PsiElement element, LookupType type) {
     while (element != null) {
-      if (type == LookupType.PREFER_DECLARATION || type == LookupType.DECLRARATION_ONLY) {
+      if (type == LookupType.PREFER_DECLARATION || type == LookupType.DECLARATION_ONLY) {
         if (element instanceof PsiReferenceExpression) {
           final PsiElement e = ((PsiReferenceExpression)element).resolve();
           if (e instanceof PsiModifierListOwner) {
             return (PsiModifierListOwner)e;
           }
-          if (type == LookupType.DECLRARATION_ONLY) {
+          if (type == LookupType.DECLARATION_ONLY) {
             return null;
           }
         }
@@ -105,7 +105,7 @@
 
       // If no annotation has been found through the usage context, check if the element
       // (i.e. the element the reference refers to) is annotated itself
-      if (type != LookupType.DECLRARATION_ONLY) {
+      if (type != LookupType.DECLARATION_ONLY) {
         if (element instanceof PsiReferenceExpression) {
           final PsiElement e = ((PsiReferenceExpression)element).resolve();
           if (e instanceof PsiModifierListOwner) {
@@ -186,7 +186,7 @@
    * <p/>
    * The <code>annotationName</code> parameter is a pair of the target annotation class' fully qualified name as a
    * String and as a Set. This is done for performance reasons because the Set is required by the
-   * {@link com.intellij.codeInsight.AnnotationUtil} utility class and allows to avoid unecessary object constructions.
+   * {@link com.intellij.codeInsight.AnnotationUtil} utility class and allows to avoid unnecessary object constructions.
    */
   @NotNull
   public static PsiAnnotation[] getAnnotationFrom(PsiModifierListOwner owner,
@@ -206,7 +206,7 @@
    * <p/>
    * The <code>annotationName</code> parameter is a pair of the target annotation class' fully qualified name as a
    * String and as a Set. This is done for performance reasons because the Set is required by the
-   * {@link com.intellij.codeInsight.AnnotationUtil} utility class and allows to avoid unecessary object constructions.
+   * {@link com.intellij.codeInsight.AnnotationUtil} utility class and allows to avoid unnecessary object constructions.
    */
 
   public static PsiAnnotation[] getAnnotationsFromImpl(PsiModifierListOwner owner,
diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java
index bcfd9c5..80e5577 100644
--- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java
+++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/AbstractLanguageInjectionSupport.java
@@ -17,6 +17,7 @@
 package org.intellij.plugins.intelliLang.inject;
 
 import com.intellij.lang.Language;
+import com.intellij.lang.injection.MultiHostRegistrar;
 import com.intellij.openapi.actionSystem.AnAction;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.fileTypes.FileTypeManager;
@@ -62,6 +63,9 @@
     return InjectorUtils.findCommentInjection(host, "comment", commentRef);
   }
 
+  public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
+  }
+
   public boolean addInjectionInPlace(final Language language, final PsiLanguageInjectionHost psiElement) {
     return false;
   }
diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java
index 6ff3d98..0d6a2be 100644
--- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java
+++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/inject/InjectLanguageAction.java
@@ -17,27 +17,31 @@
 
 import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
 import com.intellij.codeInsight.hint.HintManager;
+import com.intellij.codeInsight.hint.QuestionAction;
 import com.intellij.codeInsight.intention.IntentionAction;
 import com.intellij.ide.util.PropertiesComponent;
 import com.intellij.injected.editor.EditorWindow;
 import com.intellij.lang.Language;
 import com.intellij.lang.injection.InjectedLanguageManager;
+import com.intellij.openapi.actionSystem.ActionManager;
+import com.intellij.openapi.actionSystem.IdeActions;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.options.Configurable;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.JBPopup;
 import com.intellij.openapi.ui.popup.PopupChooserBuilder;
 import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiFile;
-import com.intellij.psi.PsiLanguageInjectionHost;
-import com.intellij.psi.PsiManager;
+import com.intellij.psi.*;
 import com.intellij.psi.impl.PsiModificationTrackerImpl;
+import com.intellij.psi.injection.Injectable;
+import com.intellij.psi.injection.ReferenceInjector;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.ui.ColoredListCellRendererWrapper;
 import com.intellij.ui.SimpleTextAttributes;
@@ -48,9 +52,7 @@
 import com.intellij.util.Processor;
 import com.intellij.util.containers.ContainerUtil;
 import org.intellij.plugins.intelliLang.Configuration;
-import com.intellij.psi.injection.Injectable;
 import org.intellij.plugins.intelliLang.references.InjectedReferencesContributor;
-import com.intellij.psi.injection.ReferenceInjector;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -64,6 +66,7 @@
 public class InjectLanguageAction implements IntentionAction {
   @NonNls private static final String INJECT_LANGUAGE_FAMILY = "Inject Language/Reference";
   public static final String LAST_INJECTED_LANGUAGE = "LAST_INJECTED_LANGUAGE";
+  public static final Key<Processor<PsiLanguageInjectionHost>> FIX_KEY = Key.create("inject fix key");
 
   public static List<Injectable> getAllInjectables() {
     Language[] languages = InjectedLanguage.getAvailableLanguages();
@@ -120,12 +123,13 @@
     });
   }
 
-  public static void invokeImpl(Project project, Editor editor, PsiFile file, Injectable injectable) {
+  public static void invokeImpl(Project project, Editor editor, final PsiFile file, Injectable injectable) {
     final PsiLanguageInjectionHost host = findInjectionHost(editor, file);
     if (host == null) return;
     if (defaultFunctionalityWorked(host, injectable.getId())) return;
 
     try {
+      host.putUserData(FIX_KEY, null);
       Language language = injectable.toLanguage();
       for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
         if (support.isApplicableTo(host) && support.addInjectionInPlace(language, host)) {
@@ -133,7 +137,26 @@
         }
       }
       if (TemporaryPlacesRegistry.getInstance(project).getLanguageInjectionSupport().addInjectionInPlace(language, host)) {
-        HintManager.getInstance().showInformationHint(editor, StringUtil.escapeXml(language.getDisplayName()) + " was temporarily injected");
+        final Processor<PsiLanguageInjectionHost> data = host.getUserData(FIX_KEY);
+        String text = StringUtil.escapeXml(language.getDisplayName()) + " was temporarily injected.";
+        if (data != null) {
+          if (!ApplicationManager.getApplication().isUnitTestMode()) {
+            final SmartPsiElementPointer<PsiLanguageInjectionHost> pointer =
+              SmartPointerManager.getInstance(project).createSmartPsiElementPointer(host);
+            final TextRange range = host.getTextRange();
+            HintManager.getInstance().showQuestionHint(editor, text + "<br>Do you want to insert annotation? " + KeymapUtil
+              .getFirstKeyboardShortcutText(ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS)),
+                                                       range.getStartOffset(), range.getEndOffset(), new QuestionAction() {
+              @Override
+              public boolean execute() {
+                return data.process(pointer.getElement());
+              }
+            });
+          }
+        }
+        else {
+          HintManager.getInstance().showInformationHint(editor, text);
+        }
       }
     }
     finally {
diff --git a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/references/InjectedReferencesContributor.java b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/references/InjectedReferencesContributor.java
index 69d7819..0ee07af 100644
--- a/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/references/InjectedReferencesContributor.java
+++ b/plugins/IntelliLang/src/org/intellij/plugins/intelliLang/references/InjectedReferencesContributor.java
@@ -16,12 +16,15 @@
 package org.intellij.plugins.intelliLang.references;
 
 import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.patterns.PlatformPatterns;
 import com.intellij.psi.*;
+import com.intellij.psi.impl.source.tree.injected.InjectedLanguageUtil;
+import com.intellij.psi.impl.source.tree.injected.InjectedReferenceVisitor;
 import com.intellij.psi.injection.ReferenceInjector;
-import com.intellij.util.ArrayUtil;
 import com.intellij.util.ProcessingContext;
+import com.intellij.util.SmartList;
 import org.intellij.plugins.intelliLang.Configuration;
 import org.intellij.plugins.intelliLang.inject.InjectedLanguage;
 import org.intellij.plugins.intelliLang.inject.InjectorUtils;
@@ -31,6 +34,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
 
@@ -48,6 +52,7 @@
 
   @Nullable
   public static PsiReference[] getInjectedReferences(PsiElement element) {
+    element.getReferences();
     return element.getUserData(INJECTED_REFERENCES);
   }
 
@@ -56,40 +61,53 @@
     registrar.registerReferenceProvider(PlatformPatterns.psiElement(), new PsiReferenceProvider() {
       @NotNull
       @Override
-      public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
+      public PsiReference[] getReferencesByElement(@NotNull final PsiElement element, @NotNull final ProcessingContext context) {
         ReferenceInjector[] extensions = ReferenceInjector.EXTENSION_POINT_NAME.getExtensions();
-        PsiReference[] references = new PsiReference[0];
+        final List<PsiReference> references = new SmartList<PsiReference>();
         Configuration configuration = Configuration.getProjectInstance(element.getProject());
-        boolean injected = false;
+        final Ref<Boolean> injected = new Ref<Boolean>(Boolean.FALSE);
         for (ReferenceInjector injector : extensions) {
           Collection<BaseInjection> injections = configuration.getInjectionsByLanguageId(injector.getId());
           for (BaseInjection injection : injections) {
             if (injection.acceptForReference(element)) {
-              injected = true;
+              injected.set(Boolean.TRUE);
               LanguageInjectionSupport support = InjectorUtils.findInjectionSupport(injection.getSupportId());
               element.putUserData(LanguageInjectionSupport.INJECTOR_SUPPORT, support);
               List<TextRange> area = injection.getInjectedArea(element);
               for (TextRange range : area) {
-                references = ArrayUtil.mergeArrays(references, injector.getReferences(element, context, range));
+                references.addAll(Arrays.asList(injector.getReferences(element, context, range)));
               }
             }
           }
         }
         if (element instanceof PsiLanguageInjectionHost) {
-          TemporaryPlacesRegistry registry = TemporaryPlacesRegistry.getInstance(element.getProject());
+          final TemporaryPlacesRegistry registry = TemporaryPlacesRegistry.getInstance(element.getProject());
           InjectedLanguage language = registry.getLanguageFor((PsiLanguageInjectionHost)element, element.getContainingFile());
           if (language != null) {
             ReferenceInjector injector = ReferenceInjector.findById(language.getID());
             if (injector != null) {
-              injected = true;
+              injected.set(Boolean.TRUE);
               element.putUserData(LanguageInjectionSupport.INJECTOR_SUPPORT, registry.getLanguageInjectionSupport());
               TextRange range = ElementManipulators.getValueTextRange(element);
-              references = ArrayUtil.mergeArrays(references, injector.getReferences(element, context, range));
+              references.addAll(Arrays.asList(injector.getReferences(element, context, range)));
             }
           }
+          else {
+            InjectedLanguageUtil.enumerate(element, element.getContainingFile(), false, new InjectedReferenceVisitor() {
+              @Override
+              public void visitInjectedReference(@NotNull ReferenceInjector injector, @NotNull List<PsiLanguageInjectionHost.Shred> places) {
+                  injected.set(Boolean.TRUE);
+                  element.putUserData(LanguageInjectionSupport.INJECTOR_SUPPORT, registry.getLanguageInjectionSupport());
+                  for (PsiLanguageInjectionHost.Shred place : places) {
+                    references.addAll(Arrays.asList(injector.getReferences(element, context, place.getRangeInsideHost())));
+                  }
+              }
+            });
+          }
         }
-        element.putUserData(INJECTED_REFERENCES, injected ? references : null);
-        return references;
+        PsiReference[] array = references.toArray(new PsiReference[references.size()]);
+        element.putUserData(INJECTED_REFERENCES, injected.get() ? array : null);
+        return array;
       }
     });
   }
diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/RemoveBracesIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/RemoveBracesIntention.java
index 658665d..b977e1c 100644
--- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/RemoveBracesIntention.java
+++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/braces/RemoveBracesIntention.java
@@ -15,9 +15,9 @@
  */
 package com.siyeh.ipp.braces;
 
-import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
 import com.intellij.psi.*;
 import com.intellij.util.IncorrectOperationException;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import com.siyeh.ipp.base.PsiElementPredicate;
 import org.jetbrains.annotations.NotNull;
 
@@ -40,7 +40,7 @@
         final PsiFile file = statement.getContainingFile();
         //this intention doesn't work in JSP files, as it can't tell about tags
         // inside the braces
-        return !JspPsiUtil.isInJspFile(file);
+        return !FileTypeUtils.isInServerPageFile(file);
       }
     };
   }
diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/conditional/ReplaceConditionalWithIfPredicate.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/conditional/ReplaceConditionalWithIfPredicate.java
index e3b8c7a..5fe305e 100644
--- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/conditional/ReplaceConditionalWithIfPredicate.java
+++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/conditional/ReplaceConditionalWithIfPredicate.java
@@ -17,6 +17,7 @@
 
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.siyeh.ig.psiutils.FileTypeUtils;
 import com.siyeh.ipp.base.PsiElementPredicate;
 
 class ReplaceConditionalWithIfPredicate implements PsiElementPredicate {
@@ -30,7 +31,7 @@
     if (parent instanceof PsiExpressionStatement) {
       return false;
     }
-    if (JspPsiUtil.isInJspFile(element)) {
+    if (FileTypeUtils.isInServerPageFile(element)) {
       return false;
     }
     final PsiMember member = PsiTreeUtil.getParentOfType(element, PsiMember.class);
diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/enumswitch/CreateEnumSwitchBranchesIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/enumswitch/CreateEnumSwitchBranchesIntention.java
index c82d842..59d1f36 100644
--- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/enumswitch/CreateEnumSwitchBranchesIntention.java
+++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/enumswitch/CreateEnumSwitchBranchesIntention.java
@@ -22,7 +22,9 @@
 import org.jetbrains.annotations.NotNull;
 
 import java.util.ArrayList;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 public class CreateEnumSwitchBranchesIntention extends Intention {
 
@@ -34,6 +36,7 @@
   public void processIntention(@NotNull PsiElement element) {
     if (element instanceof PsiWhiteSpace) {
       element = element.getPrevSibling();
+      assert element != null;
     }
     final PsiSwitchStatement switchStatement = (PsiSwitchStatement)element;
     final PsiCodeBlock body = switchStatement.getBody();
@@ -50,62 +53,105 @@
       return;
     }
     final PsiField[] fields = enumClass.getFields();
-    final List<String> missingEnumElements = new ArrayList<String>(fields.length);
+    final List<PsiEnumConstant> missingEnumElements = new ArrayList<PsiEnumConstant>(fields.length);
     for (final PsiField field : fields) {
-      if (field instanceof PsiEnumConstant) {
-        missingEnumElements.add(field.getName());
+      if (!(field instanceof PsiEnumConstant)) {
+        continue;
+      }
+      final PsiEnumConstant enumConstant = (PsiEnumConstant)field;
+      missingEnumElements.add(enumConstant);
+    }
+    if (body == null) {
+      // replace entire switch statement if no code block is present
+      @NonNls final StringBuilder newStatementText = new StringBuilder();
+      newStatementText.append("switch(").append(switchExpression.getText()).append("){");
+      for (PsiEnumConstant missingEnumElement : missingEnumElements) {
+        newStatementText.append("case ").append(missingEnumElement.getName()).append(": break;");
+      }
+      newStatementText.append('}');
+      replaceStatement(newStatementText.toString(), switchStatement);
+      return;
+    }
+    final Map<PsiEnumConstant, PsiEnumConstant> nextEnumConstants = new HashMap<PsiEnumConstant, PsiEnumConstant>(fields.length);
+    PsiEnumConstant previous = null;
+    for (PsiEnumConstant enumConstant : missingEnumElements) {
+      if (previous != null) {
+        nextEnumConstants.put(previous, enumConstant);
+      }
+      previous = enumConstant;
+    }
+    final PsiStatement[] statements = body.getStatements();
+    for (final PsiStatement statement : statements) {
+      missingEnumElements.remove(findEnumConstant(statement));
+    }
+    PsiEnumConstant nextEnumConstant = getNextEnumConstant(nextEnumConstants, missingEnumElements);
+    PsiElement bodyElement = body.getFirstBodyElement();
+    while (bodyElement != null) {
+      while (nextEnumConstant != null && findEnumConstant(bodyElement) == nextEnumConstant) {
+        addSwitchLabelStatementBefore(missingEnumElements.get(0), bodyElement);
+        missingEnumElements.remove(0);
+        if (missingEnumElements.isEmpty()) {
+          break;
+        }
+        nextEnumConstant = getNextEnumConstant(nextEnumConstants, missingEnumElements);
+      }
+      if (isDefaultSwitchLabelStatement(bodyElement)) {
+        for (PsiEnumConstant missingEnumElement : missingEnumElements) {
+          addSwitchLabelStatementBefore(missingEnumElement, bodyElement);
+        }
+        missingEnumElements.clear();
+        break;
+      }
+      bodyElement = bodyElement.getNextSibling();
+    }
+    if (!missingEnumElements.isEmpty()) {
+      final PsiElement lastChild = body.getLastChild();
+      for (PsiEnumConstant missingEnumElement : missingEnumElements) {
+        addSwitchLabelStatementBefore(missingEnumElement, lastChild);
       }
     }
-    if (body != null) {
-      final PsiStatement[] statements = body.getStatements();
-      for (final PsiStatement statement : statements) {
-        if (!(statement instanceof PsiSwitchLabelStatement)) {
-          continue;
-        }
-        final PsiSwitchLabelStatement labelStatement = (PsiSwitchLabelStatement)statement;
-        final PsiExpression value = labelStatement.getCaseValue();
-        if (!(value instanceof PsiReferenceExpression)) {
-          continue;
-        }
-        final PsiReferenceExpression reference = (PsiReferenceExpression)value;
-        final PsiElement resolved = reference.resolve();
-        if (!(resolved instanceof PsiEnumConstant)) {
-          continue;
-        }
-        final PsiEnumConstant enumConstant = (PsiEnumConstant)resolved;
-        missingEnumElements.remove(enumConstant.getName());
-      }
-    }
-    @NonNls final StringBuilder newStatementText = new StringBuilder();
-    newStatementText.append("switch(").append(switchExpression.getText()).append("){");
-    if (body != null) {
-      int position = 0;
-      final PsiElement[] children = body.getChildren();
-      for (position = 1; position < children.length - 1; position++) {
-        final PsiElement child = children[position];
-        if (child instanceof PsiSwitchLabelStatement) {
-          final PsiSwitchLabelStatement switchLabelStatement = (PsiSwitchLabelStatement)child;
-          if (switchLabelStatement.isDefaultCase()) {
-            break;
-          }
-        }
-        newStatementText.append(child.getText());
-      }
-      appendMissingEnumCases(missingEnumElements, newStatementText);
-      for (; position< children.length - 1; position++) {
-        newStatementText.append(children[position].getText());
-      }
-    }
-    else {
-      appendMissingEnumCases(missingEnumElements, newStatementText);
-    }
-    newStatementText.append('}');
-    replaceStatement(newStatementText.toString(), switchStatement);
   }
 
-  private static void appendMissingEnumCases(List<String> missingEnumElements, @NonNls StringBuilder newStatementText) {
-    for (String missingEnumElement : missingEnumElements) {
-      newStatementText.append("case ").append(missingEnumElement).append(": break;");
+  private static void addSwitchLabelStatementBefore(PsiEnumConstant missingEnumElement, PsiElement anchor) {
+    final PsiElement parent = anchor.getParent();
+    final PsiElementFactory factory = JavaPsiFacade.getElementFactory(anchor.getProject());
+    final PsiStatement caseStatement = factory.createStatementFromText("case " + missingEnumElement.getName() + ":", anchor);
+    parent.addBefore(caseStatement, anchor);
+    final PsiStatement breakStatement = factory.createStatementFromText("break;", anchor);
+    parent.addBefore(breakStatement, anchor);
+  }
+
+  private static PsiEnumConstant findEnumConstant(PsiElement element) {
+    if (!(element instanceof PsiSwitchLabelStatement)) {
+      return null;
     }
+    final PsiSwitchLabelStatement switchLabelStatement = (PsiSwitchLabelStatement)element;
+    final PsiExpression value = switchLabelStatement.getCaseValue();
+    if (!(value instanceof PsiReferenceExpression)) {
+      return null;
+    }
+    final PsiReferenceExpression referenceExpression = (PsiReferenceExpression)value;
+    final PsiElement target = referenceExpression.resolve();
+    if (!(target instanceof PsiEnumConstant)) {
+      return null;
+    }
+    return (PsiEnumConstant)target;
+  }
+
+  private static PsiEnumConstant getNextEnumConstant(Map<PsiEnumConstant, PsiEnumConstant> nextEnumConstants,
+                                                     List<PsiEnumConstant> missingEnumElements) {
+    PsiEnumConstant nextEnumConstant = nextEnumConstants.get(missingEnumElements.get(0));
+    while (missingEnumElements.contains(nextEnumConstant)) {
+      nextEnumConstant = nextEnumConstants.get(nextEnumConstant);
+    }
+    return nextEnumConstant;
+  }
+
+  private static boolean isDefaultSwitchLabelStatement(PsiElement element) {
+    if (!(element instanceof PsiSwitchLabelStatement)) {
+      return false;
+    }
+    final PsiSwitchLabelStatement switchLabelStatement = (PsiSwitchLabelStatement)element;
+    return switchLabelStatement.isDefaultCase();
   }
 }
\ No newline at end of file
diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/BeforeDefault_after.java b/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/BeforeDefault_after.java
index 7a69b04..be20930 100644
--- a/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/BeforeDefault_after.java
+++ b/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/BeforeDefault_after.java
@@ -4,15 +4,15 @@
   enum Status { ACTIVE, INACTIVE, ERROR }
 
   private void foo (Status status) {
-      switch (status) {
-          case ACTIVE:
-              break;
-          case INACTIVE:
-              break;
-          case ERROR:
-              break;
-          default:
-              throw new IllegalArgumentException("Unknown Status " + status);
-      }
+    switch (status) {
+      case ACTIVE:
+        break;
+      case INACTIVE:
+        break;
+        case ERROR:
+            break;
+        default:
+        throw new IllegalArgumentException("Unknown Status " + status);
+    }
   }
 }
\ No newline at end of file
diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/Multiple.java b/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/Multiple.java
new file mode 100644
index 0000000..a96ac71
--- /dev/null
+++ b/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/Multiple.java
@@ -0,0 +1,10 @@
+class Main {
+    enum Status { ACTIVE, INACTIVE, ERROR }
+
+    private void foo (Status status) {
+        switch<caret> (status) {
+            case ERROR:
+                break;
+        }
+    }
+}
\ No newline at end of file
diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/Multiple_after.java b/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/Multiple_after.java
new file mode 100644
index 0000000..3bdf9e5
--- /dev/null
+++ b/plugins/IntentionPowerPak/test/com/siyeh/ipp/enumswitch/Multiple_after.java
@@ -0,0 +1,14 @@
+class Main {
+    enum Status { ACTIVE, INACTIVE, ERROR }
+
+    private void foo (Status status) {
+        switch (status) {
+            case ACTIVE:
+                break;
+            case INACTIVE:
+                break;
+            case ERROR:
+                break;
+        }
+    }
+}
\ No newline at end of file
diff --git a/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/enumswitch/EnumSwitchBranchesIntentionTest.java b/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/enumswitch/EnumSwitchBranchesIntentionTest.java
index b8ae35f..0cee31b 100644
--- a/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/enumswitch/EnumSwitchBranchesIntentionTest.java
+++ b/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/enumswitch/EnumSwitchBranchesIntentionTest.java
@@ -18,10 +18,14 @@
 import com.siyeh.IntentionPowerPackBundle;
 import com.siyeh.ipp.IPPTestCase;
 
+/**
+ * @see CreateEnumSwitchBranchesIntention
+ */
 public class EnumSwitchBranchesIntentionTest extends IPPTestCase {
 
   public void testWithoutBraces() { doTest(); }
   public void testBeforeDefault() { doTest(); }
+  public void testMultiple() { doTest(); }
   public void testNoActionAfterBraces() { assertIntentionNotAvailable(); }
 
   @Override
diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/ui/experts/SelectLocationStep.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/ui/experts/SelectLocationStep.java
index e53fb4e..3cb19b6 100644
--- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/ui/experts/SelectLocationStep.java
+++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/ui/experts/SelectLocationStep.java
@@ -29,6 +29,7 @@
 import com.intellij.openapi.fileChooser.ex.FileTextFieldImpl;
 import com.intellij.openapi.fileChooser.ex.LocalFsFinder;
 import com.intellij.openapi.fileChooser.impl.FileChooserFactoryImpl;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.vfs.VfsUtil;
@@ -295,8 +296,8 @@
     }
 
     protected void onSetActive(final boolean active) {
-      final String tooltip = AnAction.createTooltipText(ActionsBundle.message("action.FileChooser.TogglePathShowing.text"),
-                                                        ActionManager.getInstance().getAction("FileChooser.TogglePathShowing"));
+      final String tooltip = KeymapUtil.createTooltipText(ActionsBundle.message("action.FileChooser.TogglePathShowing.text"),
+                                                          ActionManager.getInstance().getAction("FileChooser.TogglePathShowing"));
       setToolTipText(tooltip);
     }
 
diff --git a/plugins/devkit/src/run/PluginRunConfigurationEditor.java b/plugins/devkit/src/run/PluginRunConfigurationEditor.java
index 8b4ae5b..a516533 100644
--- a/plugins/devkit/src/run/PluginRunConfigurationEditor.java
+++ b/plugins/devkit/src/run/PluginRunConfigurationEditor.java
@@ -185,7 +185,4 @@
   public RawCommandLineEditor getProgramParameters() {
     return myProgramParameters.getComponent();
   }
-
-  public void disposeEditor() {
-  }
 }
diff --git a/plugins/github/src/META-INF/github-tracker.xml b/plugins/github/src/META-INF/github-tracker.xml
index e33dd36..9264670 100644
--- a/plugins/github/src/META-INF/github-tracker.xml
+++ b/plugins/github/src/META-INF/github-tracker.xml
@@ -1,6 +1,6 @@
 <idea-plugin version="2">
   <extensions defaultExtensionNs="com.intellij">
-    <checkoutCompletedListener implementation="org.jetbrains.plugins.github.GithubCheckoutListener"
+    <checkoutCompletedListener implementation="org.jetbrains.plugins.github.extensions.GithubCheckoutListener"
                                order="after PlatformProjectCheckoutListener"/>
     <tasks.repositoryType implementation="org.jetbrains.plugins.github.tasks.GithubRepositoryType"/>
   </extensions>
diff --git a/plugins/github/src/META-INF/plugin.xml b/plugins/github/src/META-INF/plugin.xml
index cc74486..86240aa 100644
--- a/plugins/github/src/META-INF/plugin.xml
+++ b/plugins/github/src/META-INF/plugin.xml
@@ -10,19 +10,19 @@
 
   <extensions defaultExtensionNs="com.intellij">
     <errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
-    <checkoutProvider implementation="org.jetbrains.plugins.github.GithubCheckoutProvider"/>
-    <applicationService serviceInterface="org.jetbrains.plugins.github.GithubSettings"
-                        serviceImplementation="org.jetbrains.plugins.github.GithubSettings"/>
-    <vcsAnnotationGutterActionProvider implementation="org.jetbrains.plugins.github.GithubAnnotationGutterActionProvider" />
-    <checkoutCompletedListener implementation="org.jetbrains.plugins.github.GithubCheckoutListener" order="after PlatformProjectCheckoutListener"/>
+    <checkoutProvider implementation="org.jetbrains.plugins.github.extensions.GithubCheckoutProvider"/>
+    <applicationService serviceInterface="org.jetbrains.plugins.github.util.GithubSettings"
+                        serviceImplementation="org.jetbrains.plugins.github.util.GithubSettings"/>
+    <vcsAnnotationGutterActionProvider implementation="org.jetbrains.plugins.github.extensions.GithubAnnotationGutterActionProvider" />
+    <checkoutCompletedListener implementation="org.jetbrains.plugins.github.extensions.GithubCheckoutListener" order="after PlatformProjectCheckoutListener"/>
     <vcsConfigurableProvider implementation="org.jetbrains.plugins.github.ui.GithubSettingsConfigurable"/>
 
-    <applicationService serviceInterface="org.jetbrains.plugins.github.GithubSslSupport"
-                        serviceImplementation="org.jetbrains.plugins.github.GithubSslSupport"/>
+    <applicationService serviceInterface="org.jetbrains.plugins.github.util.GithubSslSupport"
+                        serviceImplementation="org.jetbrains.plugins.github.util.GithubSslSupport"/>
   </extensions>
 
   <extensions defaultExtensionNs="Git4Idea">
-    <GitHttpAuthDataProvider implementation="org.jetbrains.plugins.github.GithubHttpAuthDataProvider" />
+    <GitHttpAuthDataProvider implementation="org.jetbrains.plugins.github.extensions.GithubHttpAuthDataProvider" />
   </extensions>
 
   <actions>
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubCreateGistAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubCreateGistAction.java
index 0ca65ea..5983302 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubCreateGistAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubCreateGistAction.java
@@ -25,7 +25,6 @@
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileTypes.FileTypeManager;
 import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
@@ -34,12 +33,17 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vcs.changes.ChangeListManager;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.ThrowableConvertor;
 import icons.GithubIcons;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 import org.jetbrains.plugins.github.api.GithubGist;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
 import org.jetbrains.plugins.github.ui.GithubCreateGistDialog;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import java.io.IOException;
 import java.util.*;
@@ -106,17 +110,27 @@
       return;
     }
 
-    final GithubAuthData auth = dialog.isAnonymous() ? GithubAuthData.createAnonymous() : getValidAuthData(project);
-    if (auth == null) {
-      return;
+    GithubAuthData auth = GithubAuthData.createAnonymous();
+    if (!dialog.isAnonymous()) {
+      try {
+        auth = getValidAuthData(project);
+      }
+      catch (GithubAuthenticationCanceledException e) {
+        return;
+      }
+      catch (IOException e) {
+        GithubNotifications.showError(project, "Can't create gist", e);
+        return;
+      }
     }
 
     final Ref<String> url = new Ref<String>();
+    final GithubAuthData finalAuth = auth;
     new Task.Backgroundable(project, "Creating Gist...") {
       @Override
       public void run(@NotNull ProgressIndicator indicator) {
         List<FileContent> contents = collectContents(project, editor, file, files);
-        String gistUrl = createGist(project, auth, contents, dialog.isPrivate(), dialog.getDescription(), dialog.getFileName());
+        String gistUrl = createGist(project, finalAuth, contents, dialog.isPrivate(), dialog.getDescription(), dialog.getFileName());
         url.set(gistUrl);
       }
 
@@ -135,15 +149,15 @@
     }.queue();
   }
 
-  @Nullable
-  private static GithubAuthData getValidAuthData(@NotNull final Project project) {
-    final Ref<GithubAuthData> authDataRef = new Ref<GithubAuthData>();
-    ProgressManager.getInstance().run(new Task.Modal(project, "Access to GitHub", true) {
-      public void run(@NotNull ProgressIndicator indicator) {
-        authDataRef.set(GithubUtil.getValidAuthDataFromConfig(project, indicator));
-      }
-    });
-    return authDataRef.get();
+  @NotNull
+  private static GithubAuthData getValidAuthData(@NotNull final Project project) throws IOException {
+    return GithubUtil.computeValueInModal(project, "Access to GitHub",
+                                          new ThrowableConvertor<ProgressIndicator, GithubAuthData, IOException>() {
+                                            @Override
+                                            public GithubAuthData convert(ProgressIndicator indicator) throws IOException {
+                                              return GithubUtil.getValidAuthDataFromConfig(project, indicator);
+                                            }
+                                          });
   }
 
   @NotNull
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestAction.java
index 70465e5..ec135c2 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestAction.java
@@ -15,40 +15,63 @@
  */
 package org.jetbrains.plugins.github;
 
+import com.intellij.icons.AllIcons;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.PlatformDataKeys;
 import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.ui.DialogWrapper;
+import com.intellij.openapi.ui.Splitter;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vcs.VcsException;
+import com.intellij.openapi.vcs.changes.Change;
+import com.intellij.openapi.vcs.changes.ui.ChangesBrowser;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.ui.TabbedPaneImpl;
+import com.intellij.util.Consumer;
 import com.intellij.util.Function;
 
 import com.intellij.util.ThrowableConsumer;
+import com.intellij.util.ThrowableConvertor;
 import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.containers.HashSet;
+import com.intellij.util.ui.UIUtil;
 import git4idea.DialogManager;
+import git4idea.GitCommit;
 import git4idea.GitLocalBranch;
+import git4idea.GitRemoteBranch;
+import git4idea.changes.GitChangeUtils;
 import git4idea.commands.Git;
 import git4idea.commands.GitCommandResult;
+import git4idea.history.GitHistoryUtils;
 import git4idea.repo.GitRemote;
 import git4idea.repo.GitRepository;
+import git4idea.ui.GitCommitListPanel;
+import icons.Git4ideaIcons;
 import icons.GithubIcons;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.*;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
 import org.jetbrains.plugins.github.ui.GithubCreatePullRequestDialog;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
+import javax.swing.*;
+import java.awt.*;
 import java.io.IOException;
-import java.util.ArrayList;
+import java.util.*;
 import java.util.List;
 
-import static org.jetbrains.plugins.github.GithubUtil.setVisibleEnabled;
+import static org.jetbrains.plugins.github.util.GithubUtil.setVisibleEnabled;
 
 /**
  * @author Aleksey Pivovarov
@@ -132,10 +155,24 @@
     if (info == null) {
       return;
     }
+    final Set<RemoteBranch> branches = getAvailableBranchesFromGit(repository);
+    branches.addAll(info.getBranches());
 
     GithubRepo parent = info.getRepo().getParent();
     String suggestedBranch = parent == null ? null : parent.getUserName() + ":" + parent.getDefaultBranch();
-    final GithubCreatePullRequestDialog dialog = new GithubCreatePullRequestDialog(project, info.getBranches(), suggestedBranch);
+    Collection<String> suggestions = ContainerUtil.map(branches, new Function<RemoteBranch, String>() {
+      @Override
+      public String fun(RemoteBranch remoteBranch) {
+        return remoteBranch.getReference();
+      }
+    });
+    Consumer<String> showDiff = new Consumer<String>() {
+      @Override
+      public void consume(String s) {
+        showDiffByRef(project, s, branches, repository, currentBranch.getName());
+      }
+    };
+    final GithubCreatePullRequestDialog dialog = new GithubCreatePullRequestDialog(project, suggestions, suggestedBranch, showDiff);
     DialogManager.show(dialog);
     if (!dialog.isOK()) {
       return;
@@ -152,9 +189,20 @@
           return;
         }
 
+        String from = info.getRepo().getUserName() + ":" + currentBranch.getName();
+        String onto = dialog.getTargetBranch();
+        GithubAuthData auth = info.getAuthData();
+
+        GithubFullPath targetRepo = findTargetRepository(project, auth, onto, info.getRepo(), upstreamUserAndRepo, branches);
+        if (targetRepo == null) {
+          GithubNotifications.showError(project, CANNOT_CREATE_PULL_REQUEST, "Can't find repository for specified branch: " + onto);
+          return;
+        }
+
         LOG.info("Creating pull request");
         indicator.setText("Creating pull request...");
-        GithubPullRequest request = createPullRequest(project, info, dialog, currentBranch.getName(), upstreamUserAndRepo);
+        GithubPullRequest request =
+          createPullRequest(project, auth, targetRepo, dialog.getRequestTitle(), dialog.getDescription(), from, onto);
         if (request == null) {
           return;
         }
@@ -169,75 +217,50 @@
   private static GithubInfo loadGithubInfoWithModal(@NotNull final Project project,
                                                     @NotNull final GithubFullPath userAndRepo,
                                                     @Nullable final GithubFullPath upstreamUserAndRepo) {
-    final Ref<GithubInfo> githubInfoRef = new Ref<GithubInfo>();
-    final Ref<IOException> exceptionRef = new Ref<IOException>();
-    ProgressManager.getInstance().run(new Task.Modal(project, "Access to GitHub", true) {
-      public void run(@NotNull ProgressIndicator indicator) {
-        try {
-          final Ref<GithubRepoDetailed> reposRef = new Ref<GithubRepoDetailed>();
-          final GithubAuthData auth =
-            GithubUtil.runAndGetValidAuth(project, indicator, new ThrowableConsumer<GithubAuthData, IOException>() {
-              @Override
-              public void consume(GithubAuthData authData) throws IOException {
-                reposRef.set(GithubApiUtil.getDetailedRepoInfo(authData, userAndRepo.getUser(), userAndRepo.getRepository()));
-              }
-            });
-          List<String> branches = loadAvailableBranches(project, auth, reposRef.get(), upstreamUserAndRepo);
-          githubInfoRef.set(new GithubInfo(auth, reposRef.get(), branches));
-        }
-        catch (IOException e) {
-          exceptionRef.set(e);
-        }
-      }
-    });
-    if (!exceptionRef.isNull()) {
-      if (exceptionRef.get() instanceof GithubAuthenticationCanceledException) {
-        return null;
-      }
-      GithubNotifications.showErrorDialog(project, CANNOT_CREATE_PULL_REQUEST, exceptionRef.get());
-      return null;
-    }
-    return githubInfoRef.get();
-  }
-
-  @Nullable
-  private static GithubPullRequest createPullRequest(@NotNull Project project,
-                                                     @NotNull GithubInfo info,
-                                                     @NotNull final GithubCreatePullRequestDialog dialog,
-                                                     @NotNull final String headBranch,
-                                                     @Nullable final GithubFullPath upstreamPath) {
-    GithubAuthData auth = info.getAuthData();
-    GithubRepoDetailed repo = info.getRepo();
-
-    String from = repo.getUserName() + ":" + headBranch;
-    String onto = dialog.getTargetBranch();
-
-    GithubFullPath target = getTargetRepository(project, auth, onto, repo, upstreamPath);
-    if (target == null) {
-      GithubNotifications.showError(project, CANNOT_CREATE_PULL_REQUEST, "Can't find repository for specified branch: " + onto);
-      return null;
-    }
-
     try {
-      return GithubApiUtil
-        .createPullRequest(auth, target.getUser(), target.getRepository(), dialog.getRequestTitle(), dialog.getDescription(), from, onto);
+      return GithubUtil
+        .computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, GithubInfo, IOException>() {
+          @Override
+          public GithubInfo convert(ProgressIndicator indicator) throws IOException {
+            final Ref<GithubRepoDetailed> reposRef = new Ref<GithubRepoDetailed>();
+            final GithubAuthData auth =
+              GithubUtil.runAndGetValidAuth(project, indicator, new ThrowableConsumer<GithubAuthData, IOException>() {
+                @Override
+                public void consume(GithubAuthData authData) throws IOException {
+                  reposRef.set(GithubApiUtil.getDetailedRepoInfo(authData, userAndRepo.getUser(), userAndRepo.getRepository()));
+                }
+              });
+            List<RemoteBranch> branches = loadAvailableBranchesFromGithub(project, auth, reposRef.get(), upstreamUserAndRepo);
+            return new GithubInfo(auth, reposRef.get(), branches);
+          }
+        });
+    }
+    catch (GithubAuthenticationCanceledException e) {
+      return null;
     }
     catch (IOException e) {
-      GithubNotifications.showError(project, CANNOT_CREATE_PULL_REQUEST, e);
+      GithubNotifications.showErrorDialog(project, CANNOT_CREATE_PULL_REQUEST, e);
       return null;
     }
   }
 
   @Nullable
-  private static GithubFullPath getTargetRepository(@NotNull Project project,
-                                                    @NotNull GithubAuthData auth,
-                                                    @NotNull String onto,
-                                                    @NotNull GithubRepoDetailed repo,
-                                                    @Nullable GithubFullPath upstreamPath) {
+  private static GithubFullPath findTargetRepository(@NotNull Project project,
+                                                     @NotNull GithubAuthData auth,
+                                                     @NotNull String onto,
+                                                     @NotNull GithubRepoDetailed repo,
+                                                     @Nullable GithubFullPath upstreamPath,
+                                                     @NotNull Collection<RemoteBranch> branches) {
     String targetUser = onto.substring(0, onto.indexOf(':'));
     @Nullable GithubRepo parent = repo.getParent();
     @Nullable GithubRepo source = repo.getSource();
 
+    for (RemoteBranch branch : branches) {
+      if (StringUtil.equalsIgnoreCase(targetUser, branch.getUser()) && branch.getRepo() != null) {
+        return new GithubFullPath(branch.getUser(), branch.getRepo());
+      }
+    }
+
     if (isRepoOwner(targetUser, repo)) {
       return repo.getFullPath();
     }
@@ -278,11 +301,47 @@
     return StringUtil.equalsIgnoreCase(user, repo.getUserName());
   }
 
-  private static List<String> loadAvailableBranches(@NotNull final Project project,
-                                                    @NotNull final GithubAuthData auth,
-                                                    @NotNull final GithubRepoDetailed repo,
-                                                    @Nullable final GithubFullPath upstreamPath) {
-    List<String> result = new ArrayList<String>();
+  @Nullable
+  private static GithubPullRequest createPullRequest(@NotNull Project project,
+                                                     @NotNull GithubAuthData auth,
+                                                     @NotNull GithubFullPath targetRepo,
+                                                     @NotNull String title,
+                                                     @NotNull String description,
+                                                     @NotNull String from,
+                                                     @NotNull String onto) {
+    try {
+      return GithubApiUtil.createPullRequest(auth, targetRepo.getUser(), targetRepo.getRepository(), title, description, from, onto);
+    }
+    catch (IOException e) {
+      GithubNotifications.showError(project, CANNOT_CREATE_PULL_REQUEST, e);
+      return null;
+    }
+  }
+
+  @NotNull
+  private static Set<RemoteBranch> getAvailableBranchesFromGit(@NotNull GitRepository gitRepository) {
+    Set<RemoteBranch> result = new HashSet<RemoteBranch>();
+    for (GitRemoteBranch remoteBranch : gitRepository.getBranches().getRemoteBranches()) {
+      for (String url : remoteBranch.getRemote().getUrls()) {
+        if (GithubUrlUtil.isGithubUrl(url)) {
+          GithubFullPath path = GithubUrlUtil.getUserAndRepositoryFromRemoteUrl(url);
+          if (path != null) {
+            result.add(new RemoteBranch(path.getUser(), remoteBranch.getNameForRemoteOperations(), path.getRepository(),
+                                        remoteBranch.getNameForLocalOperations()));
+            break;
+          }
+        }
+      }
+    }
+    return result;
+  }
+
+  @NotNull
+  private static List<RemoteBranch> loadAvailableBranchesFromGithub(@NotNull final Project project,
+                                                                    @NotNull final GithubAuthData auth,
+                                                                    @NotNull final GithubRepoDetailed repo,
+                                                                    @Nullable final GithubFullPath upstreamPath) {
+    List<RemoteBranch> result = new ArrayList<RemoteBranch>();
     try {
       final GithubRepo parent = repo.getParent();
       final GithubRepo source = repo.getSource();
@@ -308,13 +367,13 @@
   }
 
   @NotNull
-  private static List<String> getBranches(@NotNull GithubAuthData auth, @NotNull final String user, @NotNull String repo)
+  private static List<RemoteBranch> getBranches(@NotNull GithubAuthData auth, @NotNull final String user, @NotNull final String repo)
     throws IOException {
     List<GithubBranch> branches = GithubApiUtil.getRepoBranches(auth, user, repo);
-    return ContainerUtil.map(branches, new Function<GithubBranch, String>() {
+    return ContainerUtil.map(branches, new Function<GithubBranch, RemoteBranch>() {
       @Override
-      public String fun(GithubBranch branch) {
-        return user + ":" + branch.getName();
+      public RemoteBranch fun(GithubBranch branch) {
+        return new RemoteBranch(user, branch.getName(), repo);
       }
     });
   }
@@ -333,12 +392,244 @@
     return StringUtil.equalsIgnoreCase(repo1.getUser(), repo2.getUserName());
   }
 
+  private static void showDiffByRef(@NotNull Project project,
+                                    @Nullable String ref,
+                                    @NotNull Set<RemoteBranch> branches,
+                                    @NotNull GitRepository gitRepository,
+                                    @NotNull String currentBranch) {
+    RemoteBranch branch = findRemoteBranch(branches, ref);
+    if (branch == null || branch.getLocalBranch() == null) {
+      GithubNotifications.showErrorDialog(project, "Can't show diff", "Can't find local branch");
+      return;
+    }
+    String targetBranch = branch.getLocalBranch();
+
+    DiffInfo info = getDiffInfo(project, gitRepository, currentBranch, targetBranch);
+    if (info == null) {
+      GithubNotifications.showErrorDialog(project, "Can't show diff", "Can't get diff info");
+      return;
+    }
+
+    GithubCreatePullRequestDiffDialog dialog = new GithubCreatePullRequestDiffDialog(project, info);
+    dialog.show();
+  }
+
+  @Nullable
+  private static RemoteBranch findRemoteBranch(@NotNull Set<RemoteBranch> branches, @Nullable String ref) {
+    if (ref == null) {
+      return null;
+    }
+    List<String> list = StringUtil.split(ref, ":");
+    if (list.size() != 2) {
+      return null;
+    }
+    for (RemoteBranch branch : branches) {
+      if (StringUtil.equalsIgnoreCase(list.get(0), branch.getUser()) && StringUtil.equals(list.get(1), branch.getBranch())) {
+        return branch;
+      }
+    }
+
+    return null;
+  }
+
+  @Nullable
+  private static DiffInfo getDiffInfo(@NotNull final Project project,
+                                      @NotNull final GitRepository repository,
+                                      @NotNull final String currentBranch,
+                                      @NotNull final String targetBranch) {
+    try {
+      return GithubUtil.computeValueInModal(project, "Access to Git", new ThrowableConvertor<ProgressIndicator, DiffInfo, VcsException>() {
+        @Override
+        public DiffInfo convert(ProgressIndicator indicator) throws VcsException {
+          List<GitCommit> commits = GitHistoryUtils.history(project, repository.getRoot(), targetBranch + "..");
+          Collection<Change> diff =
+            GitChangeUtils.getDiff(repository.getProject(), repository.getRoot(), targetBranch, currentBranch, null);
+          return new DiffInfo(targetBranch, currentBranch, commits, diff);
+        }
+      });
+    }
+    catch (VcsException e) {
+      LOG.info(e);
+      return null;
+    }
+  }
+
+  private static class GithubCreatePullRequestDiffDialog extends DialogWrapper {
+    @NotNull private final Project myProject;
+    @NotNull private final DiffInfo myInfo;
+    private JPanel myLogPanel;
+
+    public GithubCreatePullRequestDiffDialog(@NotNull Project project, @NotNull DiffInfo info) {
+      super(project, false);
+      myProject = project;
+      myInfo = info;
+      setTitle(String.format("Comparing %s with %s", info.getFrom(), info.getTo()));
+      setModal(false);
+      init();
+    }
+
+    @Override
+    protected JComponent createCenterPanel() {
+      myLogPanel = new GithubCreatePullRequestLogPanel(myProject, myInfo);
+      JPanel diffPanel = new GithubCreatePullRequestDiffPanel(myProject, myInfo);
+
+      TabbedPaneImpl tabbedPane = new TabbedPaneImpl(SwingConstants.TOP);
+      tabbedPane.addTab("Log", Git4ideaIcons.Branch, myLogPanel);
+      tabbedPane.addTab("Diff", AllIcons.Actions.Diff, diffPanel);
+      tabbedPane.setKeyboardNavigation(TabbedPaneImpl.DEFAULT_PREV_NEXT_SHORTCUTS);
+      return tabbedPane;
+    }
+
+    @NotNull
+    @Override
+    protected Action[] createActions() {
+      return new Action[0];
+    }
+
+    @Override
+    protected String getDimensionServiceKey() {
+      return "Github.CreatePullRequestDiffDialog";
+    }
+  }
+
+  private static class GithubCreatePullRequestDiffPanel extends JPanel {
+
+    private final Project myProject;
+    private final DiffInfo myInfo;
+
+    public GithubCreatePullRequestDiffPanel(@NotNull Project project, @NotNull DiffInfo info) {
+      super(new BorderLayout(UIUtil.DEFAULT_VGAP, UIUtil.DEFAULT_HGAP));
+      myProject = project;
+      myInfo = info;
+
+      add(createCenterPanel());
+    }
+
+    private JComponent createCenterPanel() {
+      List<Change> diff = new ArrayList<Change>(myInfo.getDiff());
+      final ChangesBrowser changesBrowser =
+        new ChangesBrowser(myProject, null, diff, null, false, true, null, ChangesBrowser.MyUseCase.COMMITTED_CHANGES, null);
+      changesBrowser.setChangesToDisplay(diff);
+      return changesBrowser;
+    }
+  }
+
+  private static class GithubCreatePullRequestLogPanel extends JPanel {
+    private final Project myProject;
+    private final DiffInfo myInfo;
+
+    private GitCommitListPanel myCommitPanel;
+
+    GithubCreatePullRequestLogPanel(@NotNull Project project, @NotNull DiffInfo info) {
+      super(new BorderLayout(UIUtil.DEFAULT_HGAP, UIUtil.DEFAULT_VGAP));
+      myProject = project;
+      myInfo = info;
+
+      add(createCenterPanel());
+    }
+
+    private JComponent createCenterPanel() {
+      final ChangesBrowser changesBrowser = new ChangesBrowser(myProject, null, Collections.<Change>emptyList(), null, false, true, null,
+                                                               ChangesBrowser.MyUseCase.COMMITTED_CHANGES, null);
+
+      myCommitPanel =
+        new GitCommitListPanel(myInfo.getCommits(), String.format("Branch %s is fully merged to %s", myInfo.getFrom(), myInfo.getTo()));
+      addSelectionListener(myCommitPanel, changesBrowser);
+
+      myCommitPanel.registerDiffAction(changesBrowser.getDiffAction());
+
+      Splitter rootPanel = new Splitter(false, 0.7f);
+      rootPanel.setSecondComponent(changesBrowser);
+      rootPanel.setFirstComponent(myCommitPanel);
+
+      return rootPanel;
+    }
+
+    private static void addSelectionListener(@NotNull GitCommitListPanel sourcePanel, @NotNull final ChangesBrowser changesBrowser) {
+      sourcePanel.addListSelectionListener(new Consumer<GitCommit>() {
+        @Override
+        public void consume(GitCommit commit) {
+          changesBrowser.setChangesToDisplay(commit.getChanges());
+        }
+      });
+    }
+
+  }
+
+  private static class RemoteBranch {
+    @NotNull final String myUser;
+    @NotNull final String myBranch;
+
+    @Nullable final String myRepo;
+    @Nullable final String myLocalBranch;
+
+    private RemoteBranch(@NotNull String user, @NotNull String branch) {
+      this(user, branch, null, null);
+    }
+
+    private RemoteBranch(@NotNull String user, @NotNull String branch, @NotNull String repo) {
+      this(user, branch, repo, null);
+    }
+
+    public RemoteBranch(@NotNull String user, @NotNull String branch, @Nullable String repo, @Nullable String localBranch) {
+      myUser = user;
+      myBranch = branch;
+      myRepo = repo;
+      myLocalBranch = localBranch;
+    }
+
+    @NotNull
+    public String getReference() {
+      return myUser + ":" + myBranch;
+    }
+
+    @NotNull
+    public String getUser() {
+      return myUser;
+    }
+
+    @NotNull
+    public String getBranch() {
+      return myBranch;
+    }
+
+    @Nullable
+    public String getRepo() {
+      return myRepo;
+    }
+
+    @Nullable
+    public String getLocalBranch() {
+      return myLocalBranch;
+    }
+
+    @Override
+    public boolean equals(Object o) {
+      if (this == o) return true;
+      if (o == null || getClass() != o.getClass()) return false;
+
+      RemoteBranch that = (RemoteBranch)o;
+
+      if (!StringUtil.equalsIgnoreCase(myUser, that.myUser)) return false;
+      if (!StringUtil.equalsIgnoreCase(myBranch, that.myBranch)) return false;
+
+      return true;
+    }
+
+    @Override
+    public int hashCode() {
+      int result = myUser.hashCode();
+      result = 31 * result + myBranch.hashCode();
+      return result;
+    }
+  }
+
   private static class GithubInfo {
     @NotNull private final GithubRepoDetailed myRepo;
     @NotNull private final GithubAuthData myAuthData;
-    @NotNull private final List<String> myBranches;
+    @NotNull private final List<RemoteBranch> myBranches;
 
-    private GithubInfo(@NotNull GithubAuthData authData, @NotNull GithubRepoDetailed repo, @NotNull List<String> branches) {
+    private GithubInfo(@NotNull GithubAuthData authData, @NotNull GithubRepoDetailed repo, @NotNull List<RemoteBranch> branches) {
       myAuthData = authData;
       myRepo = repo;
       myBranches = branches;
@@ -355,8 +646,42 @@
     }
 
     @NotNull
-    public List<String> getBranches() {
+    public List<RemoteBranch> getBranches() {
       return myBranches;
     }
   }
+
+  private static class DiffInfo {
+    @NotNull private final List<GitCommit> commits;
+    @NotNull private final Collection<Change> diff;
+    @NotNull private final String from;
+    @NotNull private final String to;
+
+    private DiffInfo(@NotNull String from, @NotNull String to, @NotNull List<GitCommit> commits, @NotNull Collection<Change> diff) {
+      this.commits = commits;
+      this.diff = diff;
+      this.from = from;
+      this.to = to;
+    }
+
+    @NotNull
+    public List<GitCommit> getCommits() {
+      return commits;
+    }
+
+    @NotNull
+    public Collection<Change> getDiff() {
+      return diff;
+    }
+
+    @NotNull
+    public String getFrom() {
+      return from;
+    }
+
+    @NotNull
+    public String getTo() {
+      return to;
+    }
+  }
 }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserAction.java
index f1b7d30..4399bae 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubOpenInBrowserAction.java
@@ -33,8 +33,11 @@
 import icons.GithubIcons;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
-import static org.jetbrains.plugins.github.GithubUtil.setVisibleEnabled;
+import static org.jetbrains.plugins.github.util.GithubUtil.setVisibleEnabled;
 
 /**
  * Created by IntelliJ IDEA.
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubRebaseAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubRebaseAction.java
index a9edef5..1db546b 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubRebaseAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubRebaseAction.java
@@ -44,11 +44,13 @@
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 import org.jetbrains.plugins.github.api.GithubFullPath;
 import org.jetbrains.plugins.github.api.GithubRepoDetailed;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
+import org.jetbrains.plugins.github.util.*;
 
 import java.io.IOException;
 import java.util.Collections;
 
-import static org.jetbrains.plugins.github.GithubUtil.setVisibleEnabled;
+import static org.jetbrains.plugins.github.util.GithubUtil.setVisibleEnabled;
 
 /**
  * Created by IntelliJ IDEA.
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.java
index 3893969..5aa1934 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubShareAction.java
@@ -20,7 +20,6 @@
 import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
@@ -33,6 +32,7 @@
 import com.intellij.openapi.vcs.ui.CommitMessage;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.ThrowableConsumer;
+import com.intellij.util.ThrowableConvertor;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.HashSet;
 import com.intellij.vcsUtil.VcsFileUtil;
@@ -51,13 +51,18 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.*;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
 import org.jetbrains.plugins.github.ui.GithubShareDialog;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import javax.swing.*;
 import java.io.IOException;
 import java.util.*;
 
-import static org.jetbrains.plugins.github.GithubUtil.setVisibleEnabled;
+import static org.jetbrains.plugins.github.util.GithubUtil.setVisibleEnabled;
 
 /**
  * @author oleg
@@ -192,42 +197,38 @@
 
   @Nullable
   private static GithubInfo loadGithubInfoWithModal(@NotNull final Project project) {
-    final Ref<GithubInfo> githubInfoRef = new Ref<GithubInfo>();
-    final Ref<IOException> exceptionRef = new Ref<IOException>();
-    ProgressManager.getInstance().run(new Task.Modal(project, "Access to GitHub", true) {
-      public void run(@NotNull ProgressIndicator indicator) {
-        try {
-          // get existing github repos (network) and validate auth data
-          final Ref<List<GithubRepo>> availableReposRef = new Ref<List<GithubRepo>>();
-          final GithubAuthData auth =
-            GithubUtil.runAndGetValidAuth(project, indicator, new ThrowableConsumer<GithubAuthData, IOException>() {
-              @Override
-              public void consume(GithubAuthData authData) throws IOException {
-                availableReposRef.set(GithubApiUtil.getAvailableRepos(authData));
-              }
-            });
-          final HashSet<String> names = new HashSet<String>();
-          for (GithubRepo info : availableReposRef.get()) {
-            names.add(info.getName());
-          }
+    try {
+      return GithubUtil
+        .computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, GithubInfo, IOException>() {
+          @Override
+          public GithubInfo convert(ProgressIndicator indicator) throws IOException {
+            // get existing github repos (network) and validate auth data
+            final Ref<List<GithubRepo>> availableReposRef = new Ref<List<GithubRepo>>();
+            final GithubAuthData auth =
+              GithubUtil.runAndGetValidAuth(project, indicator, new ThrowableConsumer<GithubAuthData, IOException>() {
+                @Override
+                public void consume(GithubAuthData authData) throws IOException {
+                  availableReposRef.set(GithubApiUtil.getUserRepos(authData));
+                }
+              });
+            final HashSet<String> names = new HashSet<String>();
+            for (GithubRepo info : availableReposRef.get()) {
+              names.add(info.getName());
+            }
 
-          // check access to private repos (network)
-          final GithubUserDetailed userInfo = GithubApiUtil.getCurrentUserDetailed(auth);
-          githubInfoRef.set(new GithubInfo(auth, userInfo, names));
-        }
-        catch (IOException e) {
-          exceptionRef.set(e);
-        }
-      }
-    });
-    if (!exceptionRef.isNull()) {
-      if (exceptionRef.get() instanceof GithubAuthenticationCanceledException) {
-        return null;
-      }
-      GithubNotifications.showErrorDialog(project, "Failed to connect to GitHub", exceptionRef.get());
+            // check access to private repos (network)
+            final GithubUserDetailed userInfo = GithubApiUtil.getCurrentUserDetailed(auth);
+            return new GithubInfo(auth, userInfo, names);
+          }
+        });
+    }
+    catch (GithubAuthenticationCanceledException e) {
       return null;
     }
-    return githubInfoRef.get();
+    catch (IOException e) {
+      GithubNotifications.showErrorDialog(project, "Failed to connect to GitHub", e);
+      return null;
+    }
   }
 
   @Nullable
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserAction.java
index 4e8970e..1dc7aad 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserAction.java
@@ -22,6 +22,9 @@
 import git4idea.repo.GitRepository;
 import icons.GithubIcons;
 import org.jetbrains.plugins.github.api.GithubFullPath;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 /**
  * @author Kirill Likhodedov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromAnnotateAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromAnnotateAction.java
index 9f0b394..0b02a0b 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromAnnotateAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromAnnotateAction.java
@@ -30,6 +30,7 @@
 import git4idea.repo.GitRepository;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 /**
  * @author Kirill Likhodedov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromLogAction.java b/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromLogAction.java
index dfb4727..139716e 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromLogAction.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubShowCommitInBrowserFromLogAction.java
@@ -25,6 +25,7 @@
 import git4idea.repo.GitRepository;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 /**
  * @author Kirill Likhodedov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
index 50da928..ba7a8cd 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
@@ -26,12 +26,15 @@
 import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.*;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException;
+import org.jetbrains.plugins.github.exceptions.GithubJsonException;
+import org.jetbrains.plugins.github.exceptions.GithubStatusCodeException;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubSslSupport;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.io.Reader;
+import java.io.*;
 import java.net.URLEncoder;
 import java.util.*;
 
@@ -234,7 +237,7 @@
       return new JsonParser().parse(reader);
     }
     catch (JsonSyntaxException jse) {
-      throw new JsonException(String.format("Couldn't parse GitHub response:%n%s", githubResponse), jse);
+      throw new GithubJsonException("Couldn't parse GitHub response", jse);
     }
     finally {
       reader.close();
@@ -274,12 +277,12 @@
    */
 
   static <Raw extends DataConstructor, Result> Result createDataFromRaw(@NotNull Raw rawObject, @NotNull Class<Result> resultClass)
-    throws JsonException {
+    throws GithubJsonException {
     try {
       return rawObject.create(resultClass);
     }
     catch (Exception e) {
-      throw new JsonException("Json parse error", e);
+      throw new GithubJsonException("Json parse error", e);
     }
   }
 
@@ -316,7 +319,7 @@
       }
 
       if (!response.getJsonElement().isJsonArray()) {
-        throw new JsonException("Wrong json type: expected JsonArray");
+        throw new GithubJsonException("Wrong json type: expected JsonArray", new Exception(response.getJsonElement().toString()));
       }
 
       myNextPage = response.getNextPage();
@@ -345,7 +348,7 @@
   @NotNull
   private static <T> T fromJson(@Nullable JsonElement json, @NotNull Class<T> classT) throws IOException {
     if (json == null) {
-      throw new JsonException("Unexpected empty response");
+      throw new GithubJsonException("Unexpected empty response");
     }
 
     T res;
@@ -355,13 +358,13 @@
       res = (T)gson.fromJson(json, classT);
     }
     catch (ClassCastException e) {
-      throw new JsonException("Parse exception while converting JSON to object " + classT.toString(), e);
+      throw new GithubJsonException("Parse exception while converting JSON to object " + classT.toString(), e);
     }
     catch (JsonParseException e) {
-      throw new JsonException("Parse exception while converting JSON to object " + classT.toString(), e);
+      throw new GithubJsonException("Parse exception while converting JSON to object " + classT.toString(), e);
     }
     if (res == null) {
-      throw new JsonException("Empty Json response");
+      throw new GithubJsonException("Empty Json response");
     }
     return res;
   }
@@ -432,19 +435,8 @@
   }
 
   @NotNull
-  public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth) throws IOException {
-    return doGetAvailableRepos(auth, null);
-  }
-
-  @NotNull
-  public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth, @NotNull String user) throws IOException {
-    return doGetAvailableRepos(auth, user);
-  }
-
-  @NotNull
-  private static List<GithubRepo> doGetAvailableRepos(@NotNull GithubAuthData auth, @Nullable String user) throws IOException {
-    String path = user == null ? "/user/repos" : "/users/" + user + "/repos?" + PER_PAGE;
-
+  public static List<GithubRepo> getUserRepos(@NotNull GithubAuthData auth) throws IOException {
+    String path = "/user/repos?" + PER_PAGE;
 
     PagedRequest<GithubRepo> request = new PagedRequest<GithubRepo>(path, GithubRepo.class, GithubRepoRaw[].class);
 
@@ -452,6 +444,37 @@
   }
 
   @NotNull
+  public static List<GithubRepo> getUserRepos(@NotNull GithubAuthData auth, @NotNull String user) throws IOException {
+    String path = "/users/" + user + "/repos?" + PER_PAGE;
+
+    PagedRequest<GithubRepo> request = new PagedRequest<GithubRepo>(path, GithubRepo.class, GithubRepoRaw[].class);
+
+    return request.getAll(auth);
+  }
+
+  @NotNull
+  public static List<GithubRepo> getAvailableRepos(@NotNull GithubAuthData auth) throws IOException {
+    List<GithubRepo> repos = new ArrayList<GithubRepo>();
+
+    repos.addAll(getUserRepos(auth));
+
+    String path = "/user/orgs?" + PER_PAGE;
+    PagedRequest<GithubOrg> request = new PagedRequest<GithubOrg>(path, GithubOrg.class, GithubOrgRaw[].class);
+
+    for (GithubOrg org : request.getAll(auth)) {
+      String pathOrg = "/orgs/" + org.getLogin() + "/repos?type=member&" + PER_PAGE;
+      PagedRequest<GithubRepo> requestOrg = new PagedRequest<GithubRepo>(pathOrg, GithubRepo.class, GithubRepoRaw[].class);
+      repos.addAll(requestOrg.getAll(auth));
+    }
+
+    String pathWatched = "/user/subscriptions?" + PER_PAGE;
+    PagedRequest<GithubRepo> requestWatched = new PagedRequest<GithubRepo>(pathWatched, GithubRepo.class, GithubRepoRaw[].class);
+    repos.addAll(requestWatched.getAll(auth));
+
+    return repos;
+  }
+
+  @NotNull
   public static GithubRepoDetailed getDetailedRepoInfo(@NotNull GithubAuthData auth, @NotNull String owner, @NotNull String name)
     throws IOException {
     final String request = "/repos/" + owner + "/" + name;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubBranchRaw.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubBranchRaw.java
index 4187ae0..e1892c6 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubBranchRaw.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubBranchRaw.java
@@ -22,7 +22,7 @@
  * @author Aleksey Pivovarov
  */
 @SuppressWarnings("UnusedDeclaration")
-public class GithubBranchRaw implements DataConstructor {
+class GithubBranchRaw implements DataConstructor {
   @Nullable public String name;
 
   @SuppressWarnings("ConstantConditions")
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubErrorMessageRaw.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubErrorMessageRaw.java
index 35b39c3..1471a5a 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubErrorMessageRaw.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubErrorMessageRaw.java
@@ -17,15 +17,36 @@
 
 import org.jetbrains.annotations.Nullable;
 
+import java.util.List;
+
 /**
  * @author Aleksey Pivovarov
  */
 @SuppressWarnings("UnusedDeclaration")
 class GithubErrorMessageRaw {
-  @Nullable private String message;
+  @Nullable public String message;
+  @Nullable public List<Error> errors;
+
+  private static class Error {
+    @Nullable public String resource;
+    @Nullable public String field;
+    @Nullable public String code;
+    @Nullable public String message;
+  }
 
   @Nullable
   public String getMessage() {
-    return message;
+    if (errors == null) {
+      return message;
+    }
+    else {
+      StringBuilder s = new StringBuilder(message);
+      for (Error e : errors) {
+        s.append("<br/>").append("[").append(e.resource).append(";").append(e.field).append("]").append(e.code).append(": ")
+          .append(e.message);
+      }
+      return s.toString();
+    }
   }
 }
+
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubFileRaw.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubFileRaw.java
index 52e351f..d0ae9cf 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubFileRaw.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubFileRaw.java
@@ -22,7 +22,7 @@
  * @author Aleksey Pivovarov
  */
 @SuppressWarnings("UnusedDeclaration")
-public class GithubFileRaw implements DataConstructor {
+class GithubFileRaw implements DataConstructor {
   @Nullable public String filename;
 
   @Nullable public Integer additions;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubIssuesSearchResultRaw.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubIssuesSearchResultRaw.java
index 60c9131..7656832c 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubIssuesSearchResultRaw.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubIssuesSearchResultRaw.java
@@ -24,7 +24,7 @@
  * @author Aleksey Pivovarov
  */
 @SuppressWarnings("UnusedDeclaration")
-public class GithubIssuesSearchResultRaw implements DataConstructor {
+class GithubIssuesSearchResultRaw implements DataConstructor {
   List<GithubIssueRaw> items;
 
   @NotNull
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubStatusCodeException.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubOrg.java
similarity index 69%
copy from plugins/github/src/org/jetbrains/plugins/github/api/GithubStatusCodeException.java
copy to plugins/github/src/org/jetbrains/plugins/github/api/GithubOrg.java
index 3b15c00..7a691fb 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubStatusCodeException.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubOrg.java
@@ -15,20 +15,20 @@
  */
 package org.jetbrains.plugins.github.api;
 
-import java.io.IOException;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * @author Aleksey Pivovarov
  */
-public class GithubStatusCodeException extends IOException {
-  private final int myStatusCode;
+public class GithubOrg {
+  @NotNull String myLogin;
 
-  public GithubStatusCodeException(String message, int statusCode) {
-    super(message);
-    myStatusCode = statusCode;
+  public GithubOrg(@NotNull String login) {
+    myLogin = login;
   }
 
-  public int getStatusCode() {
-    return myStatusCode;
+  @NotNull
+  public String getLogin() {
+    return myLogin;
   }
 }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubOrgRaw.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubOrgRaw.java
new file mode 100644
index 0000000..db4bf16
--- /dev/null
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubOrgRaw.java
@@ -0,0 +1,46 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.github.api;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author Aleksey Pivovarov
+ */
+@SuppressWarnings("UnusedDeclaration")
+class GithubOrgRaw implements DataConstructor {
+  @Nullable public String login;
+  @Nullable public Long id;
+  @Nullable public String url;
+
+  @SuppressWarnings("ConstantConditions")
+  @NotNull
+  public GithubOrg createGithubOrg() {
+    return new GithubOrg(login);
+  }
+
+  @SuppressWarnings("unchecked")
+  @NotNull
+  @Override
+  public <T> T create(@NotNull Class<T> resultClass) {
+    if (resultClass.isAssignableFrom(GithubOrg.class)) {
+      return (T)createGithubOrg();
+    }
+
+    throw new ClassCastException(this.getClass().getName() + ": bad class type: " + resultClass.getName());
+  }
+}
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubPullRequestRequest.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubPullRequestRequest.java
index 65662c5..4465f08 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubPullRequestRequest.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubPullRequestRequest.java
@@ -20,7 +20,7 @@
 /**
  * @author Aleksey Pivovarov
  */
-public class GithubPullRequestRequest {
+class GithubPullRequestRequest {
   @NotNull String title;
   @NotNull String body;
   @NotNull String head; // branch with changes
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoOrg.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoOrg.java
new file mode 100644
index 0000000..fda0462
--- /dev/null
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoOrg.java
@@ -0,0 +1,63 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.github.api;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author Aleksey Pivovarov
+ */
+public class GithubRepoOrg extends GithubRepo {
+  @NotNull Permissions myPermissions;
+
+  public static class Permissions {
+    private boolean myAdmin;
+    private boolean myPull;
+    private boolean myPush;
+
+    public Permissions(boolean admin, boolean pull, boolean push) {
+      myAdmin = admin;
+      myPull = pull;
+      myPush = push;
+    }
+
+    public boolean isAdmin() {
+      return myAdmin;
+    }
+
+    public boolean isPull() {
+      return myPull;
+    }
+
+    public boolean isPush() {
+      return myPush;
+    }
+  }
+
+  public GithubRepoOrg(@NotNull String name,
+                       @Nullable String description,
+                       boolean isPrivate,
+                       boolean isFork,
+                       @NotNull String htmlUrl,
+                       @NotNull String cloneUrl,
+                       @Nullable String defaultBranch,
+                       @NotNull GithubUser owner,
+                       @NotNull Permissions permissions) {
+    super(name, description, isPrivate, isFork, htmlUrl, cloneUrl, defaultBranch, owner);
+    myPermissions = permissions;
+  }
+}
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoRaw.java b/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoRaw.java
index 585890d..513f87b 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoRaw.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubRepoRaw.java
@@ -72,6 +72,20 @@
   @Nullable public Date createdAt;
   @Nullable public Date updatedAt;
 
+  @Nullable public Permissions permissions;
+
+  public static class Permissions {
+    @Nullable public Boolean admin;
+    @Nullable public Boolean pull;
+    @Nullable public Boolean push;
+
+    @SuppressWarnings("ConstantConditions")
+    @NotNull
+    public GithubRepoOrg.Permissions create() {
+      return new GithubRepoOrg.Permissions(admin, pull, push);
+    }
+  }
+
   @SuppressWarnings("ConstantConditions")
   @NotNull
   public GithubRepo createRepo() {
@@ -80,6 +94,13 @@
 
   @SuppressWarnings("ConstantConditions")
   @NotNull
+  public GithubRepoOrg createRepoOrg() {
+    return new GithubRepoOrg(name, description, isPrivate, isFork, htmlUrl, cloneUrl, defaultBranch, owner.createUser(),
+                             permissions.create());
+  }
+
+  @SuppressWarnings("ConstantConditions")
+  @NotNull
   public GithubRepoDetailed createRepoDetailed() {
     GithubRepo parent = this.parent == null ? null : this.parent.createRepo();
     GithubRepo source = this.source == null ? null : this.source.createRepo();
@@ -94,6 +115,9 @@
     if (resultClass.isAssignableFrom(GithubRepo.class)) {
       return (T)createRepo();
     }
+    if (resultClass.isAssignableFrom(GithubRepoOrg.class)) {
+      return (T)createRepoOrg();
+    }
     if (resultClass.isAssignableFrom(GithubRepoDetailed.class)) {
       return (T)createRepoDetailed();
     }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubAuthenticationCanceledException.java b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubAuthenticationCanceledException.java
similarity index 95%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubAuthenticationCanceledException.java
rename to plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubAuthenticationCanceledException.java
index ad78491..69ccfbc 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubAuthenticationCanceledException.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubAuthenticationCanceledException.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.exceptions;
 
 /**
  * @author Aleksey Pivovarov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubAuthenticationException.java b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubAuthenticationException.java
similarity index 95%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubAuthenticationException.java
rename to plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubAuthenticationException.java
index 70057ce..31f9490 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubAuthenticationException.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubAuthenticationException.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.exceptions;
 
 import java.io.IOException;
 
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/JsonException.java b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubJsonException.java
similarity index 72%
rename from plugins/github/src/org/jetbrains/plugins/github/api/JsonException.java
rename to plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubJsonException.java
index b73c68b..47cc54b 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/JsonException.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubJsonException.java
@@ -13,27 +13,27 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github.api;
+package org.jetbrains.plugins.github.exceptions;
 
 import java.io.IOException;
 
 /**
  * @author Aleksey Pivovarov
  */
-public class JsonException extends IOException {
-  public JsonException() {
+public class GithubJsonException extends IOException {
+  public GithubJsonException() {
     super();
   }
 
-  public JsonException(String message) {
+  public GithubJsonException(String message) {
     super(message);
   }
 
-  public JsonException(String message, Throwable cause) {
+  public GithubJsonException(String message, Throwable cause) {
     super(message, cause);
   }
 
-  public JsonException(Throwable cause) {
+  public GithubJsonException(Throwable cause) {
     super(cause);
   }
 }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/api/GithubStatusCodeException.java b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubStatusCodeException.java
similarity index 94%
rename from plugins/github/src/org/jetbrains/plugins/github/api/GithubStatusCodeException.java
rename to plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubStatusCodeException.java
index 3b15c00..bfa074a 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubStatusCodeException.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/exceptions/GithubStatusCodeException.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github.api;
+package org.jetbrains.plugins.github.exceptions;
 
 import java.io.IOException;
 
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubAnnotationGutterActionProvider.java b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubAnnotationGutterActionProvider.java
similarity index 95%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubAnnotationGutterActionProvider.java
rename to plugins/github/src/org/jetbrains/plugins/github/extensions/GithubAnnotationGutterActionProvider.java
index 08cab1d..06a3e8b 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubAnnotationGutterActionProvider.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubAnnotationGutterActionProvider.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.extensions;
 
 import com.intellij.openapi.actionSystem.AnAction;
 import com.intellij.openapi.vcs.annotate.AnnotationGutterActionProvider;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubCheckoutListener.java b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubCheckoutListener.java
similarity index 94%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubCheckoutListener.java
rename to plugins/github/src/org/jetbrains/plugins/github/extensions/GithubCheckoutListener.java
index b0fcf5f..6af65ac 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubCheckoutListener.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubCheckoutListener.java
@@ -1,4 +1,4 @@
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.extensions;
 
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.startup.StartupManager;
@@ -11,6 +11,8 @@
 import org.jetbrains.plugins.github.api.GithubFullPath;
 import org.jetbrains.plugins.github.tasks.GithubRepository;
 import org.jetbrains.plugins.github.tasks.GithubRepositoryType;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import java.io.File;
 import java.util.ArrayList;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubCheckoutProvider.java b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubCheckoutProvider.java
similarity index 69%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubCheckoutProvider.java
rename to plugins/github/src/org/jetbrains/plugins/github/extensions/GithubCheckoutProvider.java
index f717a01..5858a65 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubCheckoutProvider.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubCheckoutProvider.java
@@ -13,18 +13,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.extensions;
 
 import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
-import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.vcs.CheckoutProvider;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.util.ThrowableConsumer;
+import com.intellij.util.ThrowableConvertor;
 import git4idea.actions.BasicAction;
 import git4idea.checkout.GitCheckoutProvider;
 import git4idea.checkout.GitCloneDialog;
@@ -33,6 +30,10 @@
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 import org.jetbrains.plugins.github.api.GithubRepo;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import java.io.File;
 import java.io.IOException;
@@ -52,27 +53,26 @@
     }
     BasicAction.saveAll();
 
-    final Ref<List<GithubRepo>> repositoryInfoRef = new Ref<List<GithubRepo>>();
-    ProgressManager.getInstance().run(new Task.Modal(project, "Access to GitHub", true) {
-      public void run(@NotNull ProgressIndicator indicator) {
-        try {
-          GithubUtil.runAndGetValidAuth(project, indicator, new ThrowableConsumer<GithubAuthData, IOException>() {
-            @Override
-            public void consume(GithubAuthData authData) throws IOException {
-              repositoryInfoRef.set(GithubApiUtil.getAvailableRepos(authData));
-            }
+    List<GithubRepo> availableRepos;
+    try {
+      availableRepos = GithubUtil
+        .computeValueInModal(project, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, List<GithubRepo>, IOException>() {
+          @Override
+          public List<GithubRepo> convert(ProgressIndicator indicator) throws IOException {
+            return GithubUtil.runWithValidAuth(project, indicator, new ThrowableConvertor<GithubAuthData, List<GithubRepo>, IOException>() {
+              @Override
+              public List<GithubRepo> convert(GithubAuthData authData) throws IOException {
+                return GithubApiUtil.getAvailableRepos(authData);
+              }
             });
-        }
-        catch (GithubAuthenticationCanceledException e) {
-          // no error message
-        }
-        catch (IOException e) {
-          GithubNotifications.showError(project, "Couldn't get the list of GitHub repositories", e);
-        }
-      }
-    });
-    final List<GithubRepo> availableRepos = repositoryInfoRef.get();
-    if (availableRepos == null){
+          }
+        });
+    }
+    catch (GithubAuthenticationCanceledException e) {
+      return;
+    }
+    catch (IOException e) {
+      GithubNotifications.showError(project, "Couldn't get the list of GitHub repositories", e);
       return;
     }
     Collections.sort(availableRepos, new Comparator<GithubRepo>() {
@@ -85,6 +85,7 @@
 
     final GitCloneDialog dialog = new GitCloneDialog(project);
     // Add predefined repositories to history
+    dialog.prependToHistory("-----------------------------------------------");
     for (int i = availableRepos.size() - 1; i>=0; i--){
       dialog.prependToHistory(availableRepos.get(i).getCloneUrl());
     }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubHttpAuthDataProvider.java b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java
similarity index 89%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubHttpAuthDataProvider.java
rename to plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java
index b13c9a0..403a92a 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubHttpAuthDataProvider.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java
@@ -13,13 +13,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.extensions;
 
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.AuthData;
 import git4idea.jgit.GitHttpAuthDataProvider;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubUrlUtil;
 
 /**
  * @author Kirill Likhodedov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepository.java b/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepository.java
index 8cac256..4f46266 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepository.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepository.java
@@ -18,8 +18,8 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubUtil;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubUtil;
 import org.jetbrains.plugins.github.api.GithubIssue;
 import org.jetbrains.plugins.github.api.GithubIssueComment;
 
diff --git a/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepositoryEditor.java b/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepositoryEditor.java
index 663f6a7..fe63449 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepositoryEditor.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/tasks/GithubRepositoryEditor.java
@@ -1,7 +1,6 @@
 package org.jetbrains.plugins.github.tasks;
 
 import com.intellij.openapi.progress.ProgressIndicator;
-import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Ref;
@@ -14,10 +13,10 @@
 import com.intellij.util.ui.FormBuilder;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubAuthenticationCanceledException;
-import org.jetbrains.plugins.github.GithubNotifications;
-import org.jetbrains.plugins.github.GithubUtil;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubUtil;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 
 import javax.swing.*;
@@ -108,35 +107,27 @@
   }
 
   private void generateToken() {
-    final Ref<String> tokenRef = new Ref<String>();
-    final Ref<IOException> exceptionRef = new Ref<IOException>();
-    ProgressManager.getInstance().run(new Task.Modal(myProject, "Access to GitHub", true) {
-      public void run(@NotNull ProgressIndicator indicator) {
-        try {
-          tokenRef.set(GithubUtil.runWithValidBasicAuthForHost(myProject, indicator, getHost(),
-                                                               new ThrowableConvertor<GithubAuthData, String, IOException>() {
-                                                                 @NotNull
-                                                                 @Override
-                                                                 public String convert(GithubAuthData auth) throws IOException {
-                                                                   return GithubApiUtil
-                                                                     .getReadOnlyToken(auth, getRepoAuthor(), getRepoName(),
-                                                                                       "Intellij tasks plugin");
-                                                                 }
-                                                               }));
-        }
-        catch (IOException e) {
-          exceptionRef.set(e);
-        }
-      }
-    });
-    if (!exceptionRef.isNull()) {
-      if (exceptionRef.get() instanceof GithubAuthenticationCanceledException) {
-        return;
-      }
-      GithubNotifications.showErrorDialog(myProject, "Can't get access token", exceptionRef.get());
-      return;
+    try {
+      myToken.setText(
+        GithubUtil.computeValueInModal(myProject, "Access to GitHub", new ThrowableConvertor<ProgressIndicator, String, IOException>() {
+          @Override
+          public String convert(ProgressIndicator indicator) throws IOException {
+            return GithubUtil
+              .runWithValidBasicAuthForHost(myProject, indicator, getHost(), new ThrowableConvertor<GithubAuthData, String, IOException>() {
+                @NotNull
+                @Override
+                public String convert(GithubAuthData auth) throws IOException {
+                  return GithubApiUtil.getReadOnlyToken(auth, getRepoAuthor(), getRepoName(), "Intellij tasks plugin");
+                }
+              });
+          }
+        }));
     }
-    myToken.setText(tokenRef.get());
+    catch (GithubAuthenticationCanceledException ignore) {
+    }
+    catch (IOException e) {
+      GithubNotifications.showErrorDialog(myProject, "Can't get access token", e);
+    }
   }
 
   @Override
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubBasicLoginDialog.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubBasicLoginDialog.java
index da9a7e9..fac45c5 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubBasicLoginDialog.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubBasicLoginDialog.java
@@ -17,8 +17,8 @@
 
 import com.intellij.openapi.project.Project;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubSettings;
 
 /**
  * @author Aleksey Pivovarov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreateGistDialog.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreateGistDialog.java
index a1efdcf..f3d6c5a 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreateGistDialog.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreateGistDialog.java
@@ -21,7 +21,7 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubSettings;
 
 import javax.swing.*;
 
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestDialog.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestDialog.java
index b906553..528437e 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestDialog.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestDialog.java
@@ -19,14 +19,14 @@
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.ui.ValidationInfo;
 import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.Consumer;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.annotations.TestOnly;
-import org.jetbrains.plugins.github.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubSettings;
 
 import javax.swing.*;
 import java.util.Collection;
-import java.util.List;
 import java.util.regex.Pattern;
 
 /**
@@ -36,9 +36,12 @@
   private final GithubCreatePullRequestPanel myGithubCreatePullRequestPanel;
   private static final Pattern GITHUB_REPO_PATTERN = Pattern.compile("[a-zA-Z0-9_.-]+:[a-zA-Z0-9_.-]+");
 
-  public GithubCreatePullRequestDialog(@NotNull final Project project, @NotNull List<String> branches, @Nullable String suggestedBranch) {
+  public GithubCreatePullRequestDialog(@NotNull final Project project,
+                                       @NotNull Collection<String> branches,
+                                       @Nullable String suggestedBranch,
+                                       @NotNull Consumer<String> showDiff) {
     super(project, true);
-    myGithubCreatePullRequestPanel = new GithubCreatePullRequestPanel();
+    myGithubCreatePullRequestPanel = new GithubCreatePullRequestPanel(showDiff);
 
     myGithubCreatePullRequestPanel.setBranches(branches);
 
@@ -100,7 +103,7 @@
     }
 
     if (!GITHUB_REPO_PATTERN.matcher(getTargetBranch()).matches()) {
-      return new ValidationInfo("Branch must be specified like 'username:branch'", myGithubCreatePullRequestPanel.getComboBox());
+      return new ValidationInfo("Branch must be specified like 'username:branch'", myGithubCreatePullRequestPanel.getBranchEditor());
     }
 
     return null;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.form b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.form
index e5dda90..46864f0 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.form
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.form
@@ -1,6 +1,6 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="org.jetbrains.plugins.github.ui.GithubCreatePullRequestPanel">
-  <grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="4" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+  <grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="4" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
     <margin top="0" left="0" bottom="0" right="0"/>
     <constraints>
       <xy x="20" y="20" width="500" height="400"/>
@@ -34,7 +34,7 @@
       </component>
       <component id="996e9" class="javax.swing.JTextField" binding="myTitleTextField">
         <constraints>
-          <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
+          <grid row="1" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
             <preferred-size width="150" height="-1"/>
           </grid>
         </constraints>
@@ -51,7 +51,7 @@
       </component>
       <scrollpane id="61e54" class="com.intellij.ui.components.JBScrollPane">
         <constraints>
-          <grid row="3" column="0" row-span="1" col-span="2" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false">
+          <grid row="3" column="0" row-span="1" col-span="3" vsize-policy="7" hsize-policy="7" anchor="0" fill="3" indent="0" use-parent-layout="false">
             <minimum-size width="150" height="50"/>
           </grid>
         </constraints>
@@ -64,6 +64,14 @@
           </component>
         </children>
       </scrollpane>
+      <component id="90c93" class="javax.swing.JButton" binding="myShowDiffButton">
+        <constraints>
+          <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+        </constraints>
+        <properties>
+          <text value="Show Diff"/>
+        </properties>
+      </component>
     </children>
   </grid>
 </form>
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.java
index 00e5ba2..e4a4521 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubCreatePullRequestPanel.java
@@ -18,10 +18,13 @@
 import com.intellij.openapi.ui.ComboBox;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.SortedComboBoxModel;
+import com.intellij.util.Consumer;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
 import java.util.Collection;
 import java.util.Comparator;
 
@@ -34,8 +37,9 @@
   private ComboBox myBranchComboBox;
   private SortedComboBoxModel<String> myBranchModel;
   private JPanel myPanel;
+  private JButton myShowDiffButton;
 
-  public GithubCreatePullRequestPanel() {
+  public GithubCreatePullRequestPanel(@NotNull final Consumer<String> showDiff) {
     myDescriptionTextArea.setBorder(BorderFactory.createEtchedBorder());
     myBranchModel = new SortedComboBoxModel<String>(new Comparator<String>() {
       @Override
@@ -44,6 +48,12 @@
       }
     });
     myBranchComboBox.setModel(myBranchModel);
+    myShowDiffButton.addActionListener(new ActionListener() {
+      @Override
+      public void actionPerformed(ActionEvent e) {
+        showDiff.consume(getBranch());
+      }
+    });
   }
 
   @NotNull
@@ -87,7 +97,7 @@
     return myTitleTextField;
   }
 
-  public JComboBox getComboBox() {
+  public JComponent getBranchEditor() {
     return myBranchComboBox;
   }
 
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginDialog.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginDialog.java
index e7968be..5c31857 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginDialog.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginDialog.java
@@ -5,9 +5,9 @@
 import com.intellij.openapi.ui.DialogWrapper;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubSettings;
-import org.jetbrains.plugins.github.GithubUtil;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import javax.swing.*;
 import java.io.IOException;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.form b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.form
index eedbe5e..ba0af85 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.form
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.form
@@ -53,15 +53,6 @@
         </constraints>
         <properties/>
       </component>
-      <component id="f851a" class="javax.swing.JComboBox" binding="myAuthTypeComboBox">
-        <constraints>
-          <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
-        </constraints>
-        <properties>
-          <model/>
-          <toolTipText value=""/>
-        </properties>
-      </component>
       <component id="b466f" class="javax.swing.JCheckBox" binding="mySavePasswordCheckBox">
         <constraints>
           <grid row="1" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false">
@@ -105,6 +96,12 @@
           <text value="Login:"/>
         </properties>
       </component>
+      <component id="548fc" class="com.intellij.openapi.ui.ComboBox" binding="myAuthTypeComboBox">
+        <constraints>
+          <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+        </constraints>
+        <properties/>
+      </component>
     </children>
   </grid>
 </form>
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.java
index 34783d2..9141ea7 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubLoginPanel.java
@@ -16,14 +16,17 @@
 package org.jetbrains.plugins.github.ui;
 
 import com.intellij.ide.BrowserUtil;
+import com.intellij.openapi.ui.ComboBox;
+import com.intellij.openapi.util.Condition;
 import com.intellij.ui.DocumentAdapter;
 import com.intellij.ui.HyperlinkAdapter;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.util.ui.table.ComponentsListFocusTraversalPolicy;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubUtil;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import javax.swing.*;
 import javax.swing.event.DocumentEvent;
@@ -46,7 +49,7 @@
   private JPasswordField myPasswordField;
   private JTextPane mySignupTextField;
   private JCheckBox mySavePasswordCheckBox;
-  private JComboBox myAuthTypeComboBox;
+  private ComboBox myAuthTypeComboBox;
   private JLabel myPasswordLabel;
   private JLabel myLoginLabel;
 
@@ -102,8 +105,8 @@
 
     List<Component> order = new ArrayList<Component>();
     order.add(myHostTextField);
-    order.add(myLoginTextField);
     order.add(myAuthTypeComboBox);
+    order.add(myLoginTextField);
     order.add(myPasswordField);
     order.add(mySavePasswordCheckBox);
     myPane.setFocusTraversalPolicyProvider(true);
@@ -174,7 +177,7 @@
   }
 
   public JComponent getPreferrableFocusComponent() {
-    return myLoginTextField;
+    return myLoginTextField.isVisible() ? myLoginTextField : myPasswordField;
   }
 
   @NotNull
@@ -196,7 +199,12 @@
     @NotNull
     @Override
     protected List<Component> getOrderedComponents() {
-      return myOrder;
+      return ContainerUtil.filter(myOrder, new Condition<Component>() {
+        @Override
+        public boolean value(Component component) {
+          return component.isVisible() && component.isEnabled();
+        }
+      });
     }
   }
 }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsConfigurable.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsConfigurable.java
index f4c312d..87e137b 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsConfigurable.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsConfigurable.java
@@ -7,7 +7,7 @@
 import com.intellij.openapi.vcs.VcsConfigurableProvider;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubSettings;
 
 import javax.swing.*;
 
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.form b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.form
index cc28385..c0d2af8 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.form
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.form
@@ -76,14 +76,11 @@
         </constraints>
         <properties/>
       </component>
-      <component id="be50e" class="javax.swing.JComboBox" binding="myAuthTypeComboBox">
+      <component id="5a680" class="com.intellij.openapi.ui.ComboBox" binding="myAuthTypeComboBox">
         <constraints>
-          <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="1" indent="0" use-parent-layout="false"/>
+          <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
         </constraints>
-        <properties>
-          <model/>
-          <toolTipText value=""/>
-        </properties>
+        <properties/>
       </component>
     </children>
   </grid>
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.java
index 908c4f4..b1f08bc 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSettingsPanel.java
@@ -17,17 +17,18 @@
 
 import com.intellij.ide.BrowserUtil;
 import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.ui.ComboBox;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.DocumentAdapter;
 import com.intellij.ui.HyperlinkAdapter;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubAuthenticationException;
-import org.jetbrains.plugins.github.GithubSettings;
-import org.jetbrains.plugins.github.GithubUtil;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException;
+import org.jetbrains.plugins.github.util.GithubNotifications;
+import org.jetbrains.plugins.github.util.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubUtil;
 import org.jetbrains.plugins.github.api.GithubUser;
 
 import javax.swing.*;
@@ -57,7 +58,7 @@
   private JPanel myPane;
   private JButton myTestButton;
   private JTextField myHostTextField;
-  private JComboBox myAuthTypeComboBox;
+  private ComboBox myAuthTypeComboBox;
   private JLabel myLoginLabel;
 
   private boolean myCredentialsModified;
@@ -83,18 +84,18 @@
         try {
           GithubUser user = GithubUtil.checkAuthData(getAuthData());
           if (GithubAuthData.AuthType.TOKEN.equals(getAuthType())) {
-            Messages.showInfoMessage(myPane, "Connection successful for user " + user.getLogin(), "Success");
+            GithubNotifications.showInfoDialog(myPane, "Connection successful for user " + user.getLogin(), "Success");
           }
           else {
-            Messages.showInfoMessage(myPane, "Connection successful", "Success");
+            GithubNotifications.showInfoDialog(myPane, "Connection successful", "Success");
           }
         }
         catch (GithubAuthenticationException ex) {
-          Messages.showErrorDialog(myPane, "Can't login using given credentials: " + ex.getMessage(), "Login Failure");
+          GithubNotifications.showErrorDialog(myPane, "Can't login using given credentials: " + ex.getMessage(), "Login Failure");
         }
         catch (IOException ex) {
           LOG.info(ex);
-          Messages.showErrorDialog(myPane, "Can't login: " + GithubUtil.getErrorTextFromException(ex), "Login Failure");
+          GithubNotifications.showErrorDialog(myPane, "Can't login: " + GithubUtil.getErrorTextFromException(ex), "Login Failure");
         }
       }
     });
diff --git a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSharePanel.java b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSharePanel.java
index bd198e1..647a811 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSharePanel.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/ui/GithubSharePanel.java
@@ -4,7 +4,6 @@
 
 import javax.swing.*;
 import javax.swing.event.DocumentEvent;
-import javax.swing.event.DocumentListener;
 
 /**
  * @author oleg
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubAuthData.java b/plugins/github/src/org/jetbrains/plugins/github/util/GithubAuthData.java
similarity index 98%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubAuthData.java
rename to plugins/github/src/org/jetbrains/plugins/github/util/GithubAuthData.java
index c8b16eb..5de9a65 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubAuthData.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/util/GithubAuthData.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.util;
 
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubNotifications.java b/plugins/github/src/org/jetbrains/plugins/github/util/GithubNotifications.java
similarity index 85%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubNotifications.java
rename to plugins/github/src/org/jetbrains/plugins/github/util/GithubNotifications.java
index 790ae36..8cb16c4 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubNotifications.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/util/GithubNotifications.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.util;
 
 import com.intellij.notification.Notification;
 import com.intellij.notification.NotificationListener;
@@ -25,6 +25,8 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.awt.*;
+
 /**
  * @author Aleksey Pivovarov
  */
@@ -102,11 +104,21 @@
     Messages.showInfoMessage(project, message, title);
   }
 
+  public static void showInfoDialog(final @NotNull Component component, final @NotNull String title, final @NotNull String message) {
+    LOG.info(title + "; " + message);
+    Messages.showInfoMessage(component, message, title);
+  }
+
   public static void showWarningDialog(final @Nullable Project project, final @NotNull String title, final @NotNull String message) {
     LOG.info(title + "; " + message);
     Messages.showWarningDialog(project, message, title);
   }
 
+  public static void showWarningDialog(final @NotNull Component component, final @NotNull String title, final @NotNull String message) {
+    LOG.info(title + "; " + message);
+    Messages.showWarningDialog(component, message, title);
+  }
+
   public static void showErrorDialog(final @Nullable Project project, final @NotNull String title, final @NotNull String message) {
     LOG.info(title + "; " + message);
     Messages.showErrorDialog(project, message, title);
@@ -117,6 +129,16 @@
     Messages.showErrorDialog(project, e.getMessage(), title);
   }
 
+  public static void showErrorDialog(final @NotNull Component component, final @NotNull String title, final @NotNull String message) {
+    LOG.info(title + "; " + message);
+    Messages.showErrorDialog(component, message, title);
+  }
+
+  public static void showErrorDialog(final @NotNull Component component, final @NotNull String title, final @NotNull Exception e) {
+    LOG.info(title, e);
+    Messages.showInfoMessage(component, e.getMessage(), title);
+  }
+
   public static int showYesNoDialog(final @Nullable Project project, final @NotNull String title, final @NotNull String message) {
     return Messages.showYesNoDialog(project, message, title, Messages.getQuestionIcon());
   }
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubSettings.java b/plugins/github/src/org/jetbrains/plugins/github/util/GithubSettings.java
similarity index 98%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubSettings.java
rename to plugins/github/src/org/jetbrains/plugins/github/util/GithubSettings.java
index 5b599b2..4afb2a9 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubSettings.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/util/GithubSettings.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.util;
 
 import com.intellij.ide.passwordSafe.PasswordSafe;
 import com.intellij.ide.passwordSafe.PasswordSafeException;
@@ -29,7 +29,7 @@
 import java.util.ArrayList;
 import java.util.Collection;
 
-import static org.jetbrains.plugins.github.GithubAuthData.AuthType;
+import static org.jetbrains.plugins.github.util.GithubAuthData.AuthType;
 
 /**
  * @author oleg
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubSslSupport.java b/plugins/github/src/org/jetbrains/plugins/github/util/GithubSslSupport.java
similarity index 98%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubSslSupport.java
rename to plugins/github/src/org/jetbrains/plugins/github/util/GithubSslSupport.java
index 4e20aef2..d2aa2f1 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubSslSupport.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/util/GithubSslSupport.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.util;
 
 import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.ui.Messages;
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubUrlUtil.java b/plugins/github/src/org/jetbrains/plugins/github/util/GithubUrlUtil.java
similarity index 97%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubUrlUtil.java
rename to plugins/github/src/org/jetbrains/plugins/github/util/GithubUrlUtil.java
index 4b11cc5..78d3ab9 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubUrlUtil.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/util/GithubUrlUtil.java
@@ -13,13 +13,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.util;
 
 import com.intellij.openapi.util.text.StringUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 import org.jetbrains.plugins.github.api.GithubFullPath;
+import org.jetbrains.plugins.github.util.GithubSettings;
 
 /**
  * @author Aleksey Pivovarov
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubUtil.java b/plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.java
similarity index 86%
rename from plugins/github/src/org/jetbrains/plugins/github/GithubUtil.java
rename to plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.java
index da71c4a..829fac7 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubUtil.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/util/GithubUtil.java
@@ -13,12 +13,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.github;
+package org.jetbrains.plugins.github.util;
 
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicator;
+import com.intellij.openapi.progress.ProgressManager;
+import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.Ref;
@@ -26,6 +28,7 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.ThrowableConsumer;
 import com.intellij.util.ThrowableConvertor;
+import com.intellij.util.ThrowableRunnable;
 import git4idea.GitUtil;
 import git4idea.config.GitVcsApplicationSettings;
 import git4idea.config.GitVersion;
@@ -37,8 +40,11 @@
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 import org.jetbrains.plugins.github.api.GithubUserDetailed;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationCanceledException;
+import org.jetbrains.plugins.github.exceptions.GithubAuthenticationException;
 import org.jetbrains.plugins.github.ui.GithubBasicLoginDialog;
 import org.jetbrains.plugins.github.ui.GithubLoginDialog;
+import org.jetbrains.plugins.github.util.*;
 
 import java.io.IOException;
 import java.util.List;
@@ -69,9 +75,6 @@
     }
     catch (GithubAuthenticationException e) {
       auth = getValidAuthData(project, indicator);
-      if (auth == null) {
-        throw new GithubAuthenticationCanceledException("Can't get valid credentials");
-      }
       task.consume(auth);
       return auth;
     }
@@ -96,9 +99,6 @@
     }
     catch (GithubAuthenticationException e) {
       auth = getValidAuthData(project, indicator);
-      if (auth == null) {
-        throw new GithubAuthenticationCanceledException("Can't get valid credentials");
-      }
       return task.convert(auth);
     }
     catch (IOException e) {
@@ -126,9 +126,6 @@
     }
     catch (GithubAuthenticationException e) {
       auth = getValidBasicAuthDataForHost(project, indicator, host);
-      if (auth == null) {
-        throw new GithubAuthenticationCanceledException("Can't get valid credentials");
-      }
       return task.convert(auth);
     }
     catch (IOException e) {
@@ -157,8 +154,9 @@
   /**
    * @return null if user canceled login dialog. Valid GithubAuthData otherwise.
    */
-  @Nullable
-  public static GithubAuthData getValidAuthData(@Nullable Project project, @NotNull ProgressIndicator indicator) {
+  @NotNull
+  public static GithubAuthData getValidAuthData(@Nullable Project project, @NotNull ProgressIndicator indicator)
+    throws GithubAuthenticationCanceledException {
     final GithubLoginDialog dialog = new GithubLoginDialog(project);
     ApplicationManager.getApplication().invokeAndWait(new Runnable() {
       @Override
@@ -167,7 +165,7 @@
       }
     }, indicator.getModalityState());
     if (!dialog.isOK()) {
-      return null;
+      throw new GithubAuthenticationCanceledException("Can't get valid credentials");
     }
     return dialog.getAuthData();
   }
@@ -175,10 +173,10 @@
   /**
    * @return null if user canceled login dialog. Valid GithubAuthData otherwise.
    */
-  @Nullable
+  @NotNull
   public static GithubAuthData getValidBasicAuthDataForHost(@Nullable Project project,
-                                                            @NotNull ProgressIndicator indicator,
-                                                            @NotNull String host) {
+                                                            @NotNull ProgressIndicator indicator, @NotNull String host)
+    throws GithubAuthenticationCanceledException {
     final GithubLoginDialog dialog = new GithubBasicLoginDialog(project);
     dialog.lockHost(host);
     ApplicationManager.getApplication().invokeAndWait(new Runnable() {
@@ -188,13 +186,14 @@
       }
     }, indicator.getModalityState());
     if (!dialog.isOK()) {
-      return null;
+      throw new GithubAuthenticationCanceledException("Can't get valid credentials");
     }
     return dialog.getAuthData();
   }
 
-  @Nullable
-  public static GithubAuthData getValidAuthDataFromConfig(@Nullable Project project, @NotNull ProgressIndicator indicator) {
+  @NotNull
+  public static GithubAuthData getValidAuthDataFromConfig(@Nullable Project project, @NotNull ProgressIndicator indicator)
+    throws IOException {
     GithubAuthData auth = GithubSettings.getInstance().getAuthData();
     try {
       checkAuthData(auth);
@@ -203,10 +202,6 @@
     catch (GithubAuthenticationException e) {
       return getValidAuthData(project, indicator);
     }
-    catch (IOException e) {
-      LOG.info("Connection error", e);
-      return null;
-    }
   }
 
   @NotNull
@@ -242,6 +237,34 @@
     return GithubApiUtil.getCurrentUserDetailed(auth);
   }
 
+  public static <T, E extends Throwable> T computeValueInModal(@NotNull Project project,
+                                                               @NotNull String caption,
+                                                               @NotNull final ThrowableConvertor<ProgressIndicator, T, E> task) throws E {
+    final Ref<T> dataRef = new Ref<T>();
+    final Ref<E> exceptionRef = new Ref<E>();
+    ProgressManager.getInstance().run(new Task.Modal(project, caption, true) {
+      public void run(@NotNull ProgressIndicator indicator) {
+        try {
+          dataRef.set(task.convert(indicator));
+        }
+        catch (Error e) {
+          throw e;
+        }
+        catch (RuntimeException e) {
+          throw e;
+        }
+        catch (Throwable e) {
+          //noinspection unchecked
+          exceptionRef.set((E)e);
+        }
+      }
+    });
+    if (!exceptionRef.isNull()) {
+      throw exceptionRef.get();
+    }
+    return dataRef.get();
+  }
+
   /*
   * Git utils
   */
@@ -343,5 +366,4 @@
     }
     return manager.getRepositoryForFile(project.getBaseDir());
   }
-
 }
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTest.java b/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTest.java
index ee0060a..7968008 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTest.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTest.java
@@ -16,6 +16,7 @@
 package org.jetbrains.plugins.github;
 
 import com.intellij.notification.NotificationType;
+import org.jetbrains.plugins.github.util.GithubAuthData;
 
 import java.util.Collections;
 import java.util.List;
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTestBase.java b/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTestBase.java
index 0450fdc..b564267 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTestBase.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubCreateGistTestBase.java
@@ -17,7 +17,6 @@
 
 import com.intellij.openapi.util.Clock;
 import com.intellij.openapi.util.Comparing;
-import com.intellij.util.containers.HashMap;
 import com.intellij.util.text.DateFormatUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
@@ -27,7 +26,6 @@
 import java.io.IOException;
 import java.util.ArrayList;
 import java.util.List;
-import java.util.Map;
 
 import static org.jetbrains.plugins.github.api.GithubGist.FileContent;
 
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubCreatePullRequestTestBase.java b/plugins/github/test/org/jetbrains/plugins/github/GithubCreatePullRequestTestBase.java
index ff3da71..5058513 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubCreatePullRequestTestBase.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubCreatePullRequestTestBase.java
@@ -20,15 +20,13 @@
 import com.intellij.openapi.util.Clock;
 import com.intellij.testFramework.VfsTestUtil;
 import com.intellij.util.text.DateFormatUtil;
-import git4idea.GitUtil;
 import git4idea.actions.GitInit;
 import git4idea.commands.Git;
 import git4idea.repo.GitRepository;
-import git4idea.repo.GitRepositoryManager;
-import git4idea.test.GitExecutor;
 import git4idea.test.TestDialogHandler;
 import org.jetbrains.plugins.github.test.GithubTest;
 import org.jetbrains.plugins.github.ui.GithubCreatePullRequestDialog;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import java.util.Random;
 
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubRequestPagingTest.java b/plugins/github/test/org/jetbrains/plugins/github/GithubRequestPagingTest.java
index 5b06666..c72cbc3 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubRequestPagingTest.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubRequestPagingTest.java
@@ -36,7 +36,7 @@
 
   public void testAvailableRepos() throws Throwable {
 
-    List<GithubRepo> availableRepos = GithubApiUtil.getAvailableRepos(myGitHubSettings.getAuthData(), myLogin2);
+    List<GithubRepo> availableRepos = GithubApiUtil.getUserRepos(myGitHubSettings.getAuthData(), myLogin2);
     List<String> realData = new ArrayList<String>();
     for (GithubRepo info : availableRepos) {
       realData.add(info.getName());
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTest.java b/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTest.java
index 756fabc..fe2f40a 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTest.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTest.java
@@ -5,6 +5,7 @@
 import git4idea.commands.Git;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
 import org.jetbrains.plugins.github.api.GithubRepoDetailed;
+import org.jetbrains.plugins.github.util.GithubAuthData;
 
 import java.io.IOException;
 
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTestBase.java b/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTestBase.java
index 1860e49..4eee8e1 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTestBase.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubShareProjectTestBase.java
@@ -20,11 +20,8 @@
 import com.intellij.util.text.DateFormatUtil;
 import git4idea.GitUtil;
 import git4idea.repo.GitRepository;
-import git4idea.repo.GitRepositoryManager;
-import git4idea.test.GitExecutor;
 import git4idea.test.TestDialogHandler;
 import org.jetbrains.plugins.github.api.GithubApiUtil;
-import org.jetbrains.plugins.github.api.GithubRepoDetailed;
 import org.jetbrains.plugins.github.test.GithubTest;
 import org.jetbrains.plugins.github.ui.GithubShareDialog;
 
diff --git a/plugins/github/test/org/jetbrains/plugins/github/GithubUrlUtilTest.java b/plugins/github/test/org/jetbrains/plugins/github/GithubUrlUtilTest.java
index b8506d6..0c8c501 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/GithubUrlUtilTest.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/GithubUrlUtilTest.java
@@ -25,7 +25,7 @@
 import java.util.ArrayList;
 import java.util.List;
 
-import static org.jetbrains.plugins.github.GithubUrlUtil.*;
+import static org.jetbrains.plugins.github.util.GithubUrlUtil.*;
 
 /**
  * @author Aleksey Pivovarov
diff --git a/plugins/github/test/org/jetbrains/plugins/github/test/GithubTest.java b/plugins/github/test/org/jetbrains/plugins/github/test/GithubTest.java
index f62a4c2..0f2da38 100644
--- a/plugins/github/test/org/jetbrains/plugins/github/test/GithubTest.java
+++ b/plugins/github/test/org/jetbrains/plugins/github/test/GithubTest.java
@@ -42,13 +42,9 @@
 import git4idea.test.TestNotificator;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.github.GithubAuthData;
-import org.jetbrains.plugins.github.GithubSettings;
-import org.jetbrains.plugins.github.GithubUtil;
-import org.jetbrains.plugins.github.api.GithubApiUtil;
-import org.jetbrains.plugins.github.api.GithubRepoDetailed;
-
-import java.io.IOException;
+import org.jetbrains.plugins.github.util.GithubAuthData;
+import org.jetbrains.plugins.github.util.GithubSettings;
+import org.jetbrains.plugins.github.util.GithubUtil;
 
 import static org.junit.Assume.assumeNotNull;
 
diff --git a/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java b/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java
index 803bdc3..dea389a 100644
--- a/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java
+++ b/plugins/google-app-engine/source/com/intellij/appengine/actions/AppEngineUploader.java
@@ -304,7 +304,16 @@
     public void processTerminated(ProcessEvent event) {
       int exitCode = event.getExitCode();
       if (exitCode == 0) {
-        myCallback.succeeded(new DeploymentRuntime());
+        myCallback.succeeded(new DeploymentRuntime() {
+          @Override
+          public boolean isUndeploySupported() {
+            return false;
+          }
+
+          @Override
+          public void undeploy(@NotNull UndeploymentTaskCallback callback) {
+          }
+        });
       }
       else {
         myCallback.errorOccurred("Process terminated with exit code " + exitCode);
diff --git a/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineCloudType.java b/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineCloudType.java
index 2557877..5d92076 100644
--- a/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineCloudType.java
+++ b/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineCloudType.java
@@ -22,15 +22,12 @@
 import com.intellij.openapi.options.UnnamedConfigurable;
 import com.intellij.openapi.project.Project;
 import com.intellij.packaging.artifacts.Artifact;
-import com.intellij.packaging.artifacts.ArtifactPointerManager;
 import com.intellij.remoteServer.ServerType;
 import com.intellij.remoteServer.configuration.deployment.*;
-import com.intellij.remoteServer.runtime.Deployment;
 import com.intellij.remoteServer.runtime.ServerConnector;
 import com.intellij.remoteServer.runtime.ServerTaskExecutor;
 import com.intellij.remoteServer.runtime.deployment.DeploymentTask;
 import com.intellij.remoteServer.runtime.deployment.ServerRuntimeInstance;
-import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.FormBuilder;
 import icons.GoogleAppEngineIcons;
 import org.jetbrains.annotations.NotNull;
@@ -38,7 +35,6 @@
 
 import javax.swing.*;
 import java.awt.*;
-import java.util.ArrayList;
 import java.util.List;
 
 /**
@@ -134,12 +130,7 @@
     @Override
     public List<DeploymentSource> getAvailableDeploymentSources() {
       List<Artifact> artifacts = AppEngineUtil.collectWebArtifacts(myProject, true);
-      List<DeploymentSource> sources = new ArrayList<DeploymentSource>();
-      ArtifactPointerManager pointerManager = ArtifactPointerManager.getInstance(myProject);
-      for (Artifact artifact : artifacts) {
-        sources.add(DeploymentSourceUtil.getInstance().createArtifactDeploymentSource(pointerManager.createPointer(artifact)));
-      }
-      return sources;
+      return DeploymentSourceUtil.getInstance().createArtifactDeploymentSources(myProject, artifacts);
     }
 
     @NotNull
@@ -165,10 +156,6 @@
     public void connect(@NotNull final ConnectionCallback<DummyDeploymentConfiguration> callback) {
       callback.connected(new AppEngineRuntimeInstance(myConfiguration));
     }
-
-    @Override
-    public void disconnect() {
-    }
   }
 
   private static class AppEngineRuntimeInstance extends ServerRuntimeInstance<DummyDeploymentConfiguration> {
@@ -190,8 +177,12 @@
     }
 
     @Override
-    public void computeDeployments(@NotNull ComputeDeploymentsCallback deployments) {
-      deployments.succeeded(ContainerUtil.<Deployment>emptyList());
+    public void computeDeployments(@NotNull ComputeDeploymentsCallback callback) {
+      callback.succeeded();
+    }
+
+    @Override
+    public void disconnect() {
     }
   }
 }
diff --git a/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineServerConfiguration.java b/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineServerConfiguration.java
index 9291f37..4576fb4 100644
--- a/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineServerConfiguration.java
+++ b/plugins/google-app-engine/source/com/intellij/appengine/cloud/AppEngineServerConfiguration.java
@@ -15,16 +15,13 @@
  */
 package com.intellij.appengine.cloud;
 
-import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.remoteServer.configuration.ServerConfiguration;
-import com.intellij.util.xmlb.XmlSerializerUtil;
+import com.intellij.remoteServer.configuration.ServerConfigurationBase;
 import com.intellij.util.xmlb.annotations.Attribute;
-import org.jetbrains.annotations.Nullable;
 
 /**
  * @author nik
  */
-public class AppEngineServerConfiguration extends ServerConfiguration implements PersistentStateComponent<AppEngineServerConfiguration> {
+public class AppEngineServerConfiguration extends ServerConfigurationBase<AppEngineServerConfiguration> {
   private String myEmail;
 
   @Attribute("email")
@@ -35,20 +32,4 @@
   public void setEmail(String email) {
     myEmail = email;
   }
-
-  @Nullable
-  @Override
-  public AppEngineServerConfiguration getState() {
-    return this;
-  }
-
-  @Override
-  public void loadState(AppEngineServerConfiguration state) {
-    XmlSerializerUtil.copyBean(state, this);
-  }
-
-  @Override
-  public PersistentStateComponent<?> getSerializer() {
-    return this;
-  }
 }
diff --git a/plugins/gradle/resources/i18n/GradleBundle.properties b/plugins/gradle/resources/i18n/GradleBundle.properties
index 7a46d91..8252d8b 100644
--- a/plugins/gradle/resources/i18n/GradleBundle.properties
+++ b/plugins/gradle/resources/i18n/GradleBundle.properties
@@ -14,4 +14,4 @@
 
 gradle.toolwindow.text.no.linked.project=\nThere is no linked Gradle project\nYou can {@action Gradle.LinkToProject} one.
 gradle.action.open.script.text=Open linked Gradle project
-gradle.action.open.script.description=Allows to open project file of the linked Gradle project at the editor
+gradle.action.open.script.description=Allows to open project file of the linked Gradle project at the editor
\ No newline at end of file
diff --git a/plugins/gradle/src/META-INF/plugin.xml b/plugins/gradle/src/META-INF/plugin.xml
index 458486a..a065418 100644
--- a/plugins/gradle/src/META-INF/plugin.xml
+++ b/plugins/gradle/src/META-INF/plugin.xml
@@ -25,8 +25,15 @@
 
   <extensionPoints>
     <extensionPoint name="projectResolve" interface="org.jetbrains.plugins.gradle.service.project.GradleProjectResolverExtension"/>
+    <extensionPoint name="resolve.contributor" interface="org.jetbrains.plugins.gradle.service.resolve.GradleMethodContextContributor"/>
   </extensionPoints>
 
+  <extensions defaultExtensionNs="org.jetbrains.plugins.gradle">
+    <resolve.contributor implementation="org.jetbrains.plugins.gradle.service.resolve.GradleRepositoriesContributor"/>
+    <resolve.contributor implementation="org.jetbrains.plugins.gradle.service.resolve.GradleDependenciesContributor"/>
+    <resolve.contributor implementation="org.jetbrains.plugins.gradle.service.resolve.GradleRootContributor"/>
+  </extensions>
+  
   <extensions defaultExtensionNs="com.intellij">
     <errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
     <projectImportProvider implementation="org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportProvider"/>
@@ -63,10 +70,9 @@
     <groovyFrameworkConfigNotification implementation="org.jetbrains.plugins.gradle.config.GradleGroovyConfigNotification"/>
     
     <membersContributor implementation="org.jetbrains.plugins.gradle.service.resolve.GradleScriptContributor"/>
-    <methodDescriptor class="org.gradle.api.Project"
-                      name="apply"
-                      namedArgsProvider="org.jetbrains.plugins.gradle.service.resolve.GradleProjectApplyArgsProvider"/>
-    
+    <methodDescriptor class="org.gradle.api.Project" name="apply">
+      <namedArgument name="plugin" values="java,groovy,idea,eclipse,scala"/>
+    </methodDescriptor>
   </extensions>
   
 </idea-plugin>
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
index efece15..732e702 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
@@ -173,14 +173,8 @@
                                                                      useWrapper,
                                                                      settings.getGradleVmOptions());
 
-        boolean inProcessMode = ExternalSystemApiUtil.isInProcessMode();
         for (GradleProjectResolverExtension extension : RESOLVER_EXTENSIONS.getValue()) {
-          if (inProcessMode) {
-            result.addResolverExtensionClass(extension.getClass());
-          }
-          else {
-            result.addResolverExtensionClass(extension.getClass().getName());
-          }
+          result.addResolverExtensionClass(ClassHolder.from(extension.getClass()));
         }
         String javaHome = myJavaHelper.getJdkHome(pair.first);
         if (!StringUtil.isEmpty(javaHome)) {
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java
index c9ec846..c3036d2 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/config/GradleLibraryPresentationProvider.java
@@ -15,7 +15,6 @@
  */
 package org.jetbrains.plugins.gradle.config;
 
-import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
 import com.intellij.openapi.roots.OrderRootType;
 import com.intellij.openapi.roots.libraries.LibraryKind;
 import com.intellij.openapi.roots.ui.configuration.libraryEditor.LibraryEditor;
@@ -26,8 +25,8 @@
 import org.jetbrains.annotations.Nls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.util.GradleConstants;
 import org.jetbrains.plugins.gradle.service.GradleInstallationManager;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
 import org.jetbrains.plugins.groovy.config.GroovyLibraryPresentationProviderBase;
 
 import javax.swing.*;
@@ -90,7 +89,7 @@
   @NotNull
   @Override
   public String getLibraryCategoryName() {
-    return ExternalSystemBundle.message(GradleConstants.SYSTEM_ID.getReadableName());
+    return "Gradle";
   }
 
   @Override
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java
index 19e0fcc..6a0b53f 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleExecutionHelper.java
@@ -15,11 +15,15 @@
  */
 package org.jetbrains.plugins.gradle.service.project;
 
+import com.intellij.execution.configurations.CommandLineTokenizer;
 import com.intellij.openapi.externalSystem.model.ExternalSystemException;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.ArrayUtilRt;
 import com.intellij.util.Function;
+import com.intellij.util.containers.ContainerUtilRt;
 import org.gradle.tooling.*;
 import org.gradle.tooling.internal.consumer.DefaultGradleConnector;
 import org.gradle.tooling.model.idea.BasicIdeaProject;
@@ -30,6 +34,8 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.util.Collections;
+import java.util.List;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -45,19 +51,21 @@
                                                              @NotNull ExternalSystemTaskNotificationListener listener,
                                                              boolean downloadLibraries)
   {
-    return getModelBuilder(downloadLibraries ? IdeaProject.class : BasicIdeaProject.class, id, settings, connection, listener);
+    return getModelBuilder(downloadLibraries ? IdeaProject.class : BasicIdeaProject.class, id, settings, connection, listener,
+                           Collections.<String>emptyList());
   }
-  
+
   @SuppressWarnings("MethodMayBeStatic")
   @NotNull
   public <T> ModelBuilder<T> getModelBuilder(@NotNull Class<T> modelType,
                                              @NotNull final ExternalSystemTaskId id,
                                              @Nullable GradleExecutionSettings settings,
                                              @NotNull ProjectConnection connection,
-                                             @NotNull ExternalSystemTaskNotificationListener listener)
+                                             @NotNull ExternalSystemTaskNotificationListener listener,
+                                             @NotNull List<String> extraJvmArgs)
   {
     ModelBuilder<T> result = connection.model(modelType);
-    prepare(result, id, settings, listener);
+    prepare(result, id, settings, listener, extraJvmArgs);
     return result;
   }
 
@@ -69,23 +77,38 @@
                                         @NotNull ExternalSystemTaskNotificationListener listener)
   {
     BuildLauncher result = connection.newBuild();
-    prepare(result, id, settings, listener);
+    prepare(result, id, settings, listener, Collections.<String>emptyList());
     return result;
   }
 
   @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
-  private static void prepare(@NotNull LongRunningOperation operation,
-                              @NotNull final ExternalSystemTaskId id,
-                              @Nullable GradleExecutionSettings settings,
-                              @NotNull final ExternalSystemTaskNotificationListener listener)
+  public static void prepare(@NotNull LongRunningOperation operation,
+                             @NotNull final ExternalSystemTaskId id,
+                             @Nullable GradleExecutionSettings settings,
+                             @NotNull final ExternalSystemTaskNotificationListener listener,
+                             @NotNull List<String> extraJvmArgs)
   {
     if (settings == null) {
       return;
     }
 
+    List<String> jvmArgs = ContainerUtilRt.newArrayList();
+
     String vmOptions = settings.getDaemonVmOptions();
-    if (vmOptions != null) {
-      operation.setJvmArguments(vmOptions.trim());
+    if (!StringUtil.isEmpty(vmOptions)) {
+      CommandLineTokenizer tokenizer = new CommandLineTokenizer(vmOptions);
+      while(tokenizer.hasMoreTokens()) {
+        String vmOption = tokenizer.nextToken();
+        if (!StringUtil.isEmpty(vmOption)) {
+          jvmArgs.add(vmOption);
+        }
+      }
+    }
+
+    jvmArgs.addAll(extraJvmArgs);
+
+    if (!jvmArgs.isEmpty()) {
+      operation.setJvmArguments(ArrayUtilRt.toStringArray(jvmArgs));
     }
 
     listener.onStart(id);
@@ -120,7 +143,7 @@
       }
     }
   }
-  
+
   /**
    * Allows to retrieve gradle api connection to use for the given project.
    *
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
index 65fec6d..8dde4a8 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
@@ -29,15 +29,13 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.gradle.remote.impl.GradleLibraryNamesMixer;
+import org.jetbrains.plugins.gradle.settings.ClassHolder;
 import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
 import org.jetbrains.plugins.gradle.util.GradleUtil;
 
 import java.io.File;
-import java.util.Collection;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
+import java.util.*;
 
 /**
  * @author Denis Zhdanov
@@ -51,7 +49,8 @@
 
   private final GradleLibraryNamesMixer myLibraryNamesMixer = new GradleLibraryNamesMixer();
 
-  @Nullable private Pair<List<Pair<String, Class<?>>>, List<GradleProjectResolverExtension>> myCachedExtensions;
+  @Nullable
+  private Pair<List<ClassHolder<? extends GradleProjectResolverExtension>>, List<GradleProjectResolverExtension>> myCachedExtensions;
   
   @Nullable
   @Override
@@ -63,30 +62,23 @@
     throws ExternalSystemException, IllegalArgumentException, IllegalStateException
   {
     if (settings != null) {
-      List<Pair<String, Class<?>>> extensionClasses = settings.getResolverExtensions();
+      List<ClassHolder<? extends GradleProjectResolverExtension>> extensionClasses = settings.getResolverExtensions();
       if (myCachedExtensions == null || !myCachedExtensions.first.equals(extensionClasses)) {
-        List<Pair<String, Class<?>>> pairs = ContainerUtilRt.newArrayList(extensionClasses);
         List<GradleProjectResolverExtension> extensions = ContainerUtilRt.newArrayList();
-        for (Pair<String, Class<?>> p : pairs) {
+        for (ClassHolder<? extends GradleProjectResolverExtension> holder : extensionClasses) {
           try {
-            final GradleProjectResolverExtension extension;
-            if (p.second != null) {
-              //noinspection unchecked
-              extension = ExternalSystemApiUtil.reloadIfNecessary((Class<GradleProjectResolverExtension>)p.second);
-            }
-            else if (p.first != null) {
-              extension = (GradleProjectResolverExtension)Class.forName(p.first).newInstance();
-            }
-            else {
-              continue;
-            }
+            final GradleProjectResolverExtension extension = holder.getTargetClass().newInstance();
             extensions.add(extension);
           }
           catch (Throwable e) {
-            throw new IllegalArgumentException(String.format("Can't instantiate project resolve extension for class '%s'", p.first), e);
+            throw new IllegalArgumentException(
+              String.format("Can't instantiate project resolve extension for class '%s'", holder.getTargetClassName()),
+              e
+            );
           }
         }
-        myCachedExtensions = Pair.create(pairs, extensions);
+        List<ClassHolder<? extends GradleProjectResolverExtension>> key = ContainerUtilRt.newArrayList(extensionClasses);
+        myCachedExtensions = Pair.create(key, extensions);
       }
       for (GradleProjectResolverExtension extension : myCachedExtensions.second) {
         DataNode<ProjectData> result = extension.resolveProjectInfo(id, projectPath, downloadLibraries, settings, listener);
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java
new file mode 100644
index 0000000..2b980cc
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleDependenciesContributor.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.gradle.service.resolve;
+
+import com.intellij.psi.*;
+import com.intellij.psi.scope.PsiScopeProcessor;
+import com.intellij.psi.util.PsiTreeUtil;
+import org.gradle.api.artifacts.dsl.DependencyHandler;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrNamedArgument;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager;
+import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder;
+import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightParameter;
+
+import java.util.List;
+
+/**
+ * @author Denis Zhdanov
+ * @since 8/14/13 12:58 PM
+ */
+public class GradleDependenciesContributor implements GradleMethodContextContributor {
+  
+  @Override
+  public void process(@NotNull List<String> methodCallInfo,
+                      @NotNull PsiScopeProcessor processor,
+                      @NotNull ResolveState state,
+                      @NotNull PsiElement place)
+  {
+    if (methodCallInfo.isEmpty()) {
+      return;
+    }
+
+    int i = methodCallInfo.indexOf("dependencies");
+    if (i != 1) {
+      return;
+    }
+    
+    // Assuming that the method call is addition of new dependency into configuration.
+    GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject());
+    PsiClass contributorClass = psiManager.findClassWithCache(DependencyHandler.class.getName(), place.getResolveScope());
+    if (contributorClass == null) {
+      return;
+    }
+    processDependencyAddition(methodCallInfo.get(0), contributorClass, processor, state, place);
+  }
+
+  private static void processDependencyAddition(@NotNull String gradleConfigurationName,
+                                                @NotNull PsiClass dependencyHandlerClass,
+                                                @NotNull PsiScopeProcessor processor,
+                                                @NotNull ResolveState state,
+                                                @NotNull PsiElement place)
+  {
+    GrLightMethodBuilder builder = new GrLightMethodBuilder(place.getManager(), gradleConfigurationName);
+    PsiClassType type = PsiType.getJavaLangObject(place.getManager(), place.getResolveScope());
+    builder.addParameter(new GrLightParameter("dependencyInfo", type, builder));
+    processor.execute(builder, state);
+    
+    GrMethodCall call = PsiTreeUtil.getParentOfType(place, GrMethodCall.class);
+    if (call == null) {
+      return;
+    }
+    GrArgumentList args = call.getArgumentList();
+    if (args == null) {
+      return;
+    }
+    int argsCount = 0;
+    boolean namedArgProcessed = false;
+    for (GroovyPsiElement arg : args.getAllArguments()) {
+      if (arg instanceof GrNamedArgument) {
+        if (!namedArgProcessed) {
+          namedArgProcessed = true;
+          argsCount++;
+        }
+      }
+      else {
+        argsCount++;
+      }
+    }
+    
+    argsCount++; // Configuration name is delivered as an argument.
+
+    for (PsiMethod method : dependencyHandlerClass.findMethodsByName("add", false)) {
+      if (method.getParameterList().getParametersCount() == argsCount) {
+        builder.setNavigationElement(method);
+      }
+    }
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java
index f7a29c2..06dbb75 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleMethodContextContributor.java
@@ -15,12 +15,15 @@
  */
 package org.jetbrains.plugins.gradle.service.resolve;
 
+import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.ResolveState;
 import com.intellij.psi.scope.PsiScopeProcessor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor;
 
+import java.util.List;
+
 /**
  * This interface narrows {@link NonCodeMembersContributor} to a closure executed inside particular method call at a gradle script.
  * <p/>
@@ -42,14 +45,19 @@
  */
 public interface GradleMethodContextContributor {
 
+  ExtensionPointName<GradleMethodContextContributor> EP_NAME = ExtensionPointName.create("org.jetbrains.plugins.gradle.resolve.contributor");
+  
   /**
    * Tries to resolve target element.
    * 
-   * @param processor  the processor receiving the declarations.
-   * @param state      current resolve state
-   * @param place      the original element from which the tree up walk was initiated.
+   * @param methodCallInfo   information about method call hierarchy which points to the target place. Every entry is a method name
+   *                         and the deepest one is assumed to be added the head
+   * @param processor        the processor receiving the declarations.
+   * @param state            current resolve state
+   * @param place            the original element from which the tree up walk was initiated.
    */
-  void process(@NotNull PsiScopeProcessor processor,
+  void process(@NotNull List<String> methodCallInfo,
+               @NotNull PsiScopeProcessor processor,
                @NotNull ResolveState state,
                @NotNull PsiElement place);
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleProjectApplyArgsProvider.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleProjectApplyArgsProvider.java
deleted file mode 100644
index 3f1792b..0000000
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleProjectApplyArgsProvider.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2000-2013 JetBrains s.r.o.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jetbrains.plugins.gradle.service.resolve;
-
-import com.intellij.psi.PsiElement;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.groovy.extensions.GroovyNamedArgumentProvider;
-import org.jetbrains.plugins.groovy.extensions.NamedArgumentDescriptor;
-import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall;
-
-import java.util.Map;
-
-/**
- * @author Denis Zhdanov
- * @since 7/23/13 5:53 PM
- */
-public class GradleProjectApplyArgsProvider extends GroovyNamedArgumentProvider {
-
-  @Override
-  public void getNamedArguments(@NotNull GrCall call,
-                                @Nullable PsiElement resolve,
-                                @Nullable String argumentName,
-                                boolean forCompletion,
-                                Map<String, NamedArgumentDescriptor> result)
-  {
-    result.put("plugin", new NamedArgumentDescriptor());
-  }
-}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java
new file mode 100644
index 0000000..db58a1a
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleRepositoriesContributor.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.gradle.service.resolve;
+
+import com.intellij.psi.PsiClass;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.ResolveState;
+import com.intellij.psi.scope.PsiScopeProcessor;
+import com.intellij.util.containers.Stack;
+import org.gradle.api.artifacts.dsl.RepositoryHandler;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager;
+
+import java.util.List;
+
+/**
+ * @author Denis Zhdanov
+ * @since 8/14/13 12:56 PM
+ */
+public class GradleRepositoriesContributor implements GradleMethodContextContributor {
+
+  @Override
+  public void process(@NotNull List<String> methodCallInfo,
+                      @NotNull PsiScopeProcessor processor,
+                      @NotNull ResolveState state,
+                      @NotNull PsiElement place)
+  {
+    if (methodCallInfo.isEmpty() || methodCallInfo.size() < 2 || !"repositories".equals(methodCallInfo.get(1))) {
+      return;
+    }
+    GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject());
+    PsiClass contributorClass = psiManager.findClassWithCache(RepositoryHandler.class.getName(), place.getResolveScope());
+    if (contributorClass != null) {
+      contributorClass.processDeclarations(processor, state, null, place);
+    }
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java
new file mode 100644
index 0000000..2e5613f
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleRootContributor.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.gradle.service.resolve;
+
+import com.intellij.psi.PsiClass;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.ResolveState;
+import com.intellij.psi.scope.PsiScopeProcessor;
+import com.intellij.util.containers.Stack;
+import org.gradle.api.Project;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager;
+
+import java.util.List;
+
+/**
+ * @author Denis Zhdanov
+ * @since 8/14/13 1:03 PM
+ */
+public class GradleRootContributor implements GradleMethodContextContributor {
+
+  @Override
+  public void process(@NotNull List<String> methodCallInfo,
+                      @NotNull PsiScopeProcessor processor,
+                      @NotNull ResolveState state,
+                      @NotNull PsiElement place) {
+    if (methodCallInfo.size() > 1) {
+      return;
+    }
+
+    GroovyPsiManager psiManager = GroovyPsiManager.getInstance(place.getProject());
+    PsiClass contributorClass = psiManager.findClassWithCache(Project.class.getName(), place.getResolveScope());
+    if (contributorClass != null) {
+      contributorClass.processDeclarations(processor, state, null, place);
+    }
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java
index 2dc07f9..29bce66 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleScriptContributor.java
@@ -19,16 +19,15 @@
 import com.intellij.psi.scope.PsiScopeProcessor;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.containers.ContainerUtilRt;
-import org.jetbrains.annotations.NonNls;
+import com.intellij.util.containers.Stack;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
-import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager;
 import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GroovyScriptClass;
 import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor;
 
-import java.util.Map;
+import java.util.List;
 
 /**
  * @author Denis Zhdanov
@@ -36,21 +35,13 @@
  */
 public class GradleScriptContributor extends NonCodeMembersContributor {
 
-  // TODO den add doc
-  @NotNull private static final Map<String, String> CONTRIBUTORS = ContainerUtilRt.newHashMap();
-  static {
-    CONTRIBUTORS.put("repositories", "org.gradle.api.artifacts.dsl.RepositoryHandler");
-    CONTRIBUTORS.put("dependencies", "org.gradle.api.artifacts.dsl.DependencyHandler");
-  }
-
-  @NotNull @NonNls private static final String ROOT_CONTRIBUTOR_CLASS_NAME = "org.gradle.api.Project";
-
   @Override
   public void processDynamicElements(@NotNull PsiType qualifierType,
                                      PsiClass aClass,
                                      PsiScopeProcessor processor,
                                      PsiElement place,
-                                     ResolveState state) {
+                                     ResolveState state)
+  {
     if (place == null) {
       return;
     }
@@ -64,29 +55,23 @@
       return;
     }
 
-    GroovyPsiManager psiManager = GroovyPsiManager.getInstance(aClass.getProject());
-    String contributorClassName = ROOT_CONTRIBUTOR_CLASS_NAME;
+    List<String> methodInfo = ContainerUtilRt.newArrayList();
     for (GrMethodCall current = PsiTreeUtil.getParentOfType(place, GrMethodCall.class);
          current != null;
          current = PsiTreeUtil.getParentOfType(current, GrMethodCall.class))
     {
       GrExpression expression = current.getInvokedExpression();
-      if (expression != null) {
-        String text = expression.getText();
-        if (text == null || text.equals(place.getText())) {
-          continue;
-        }
-        String s = CONTRIBUTORS.get(text);
-        if (s != null) {
-          contributorClassName = s;
-          break;
-        }
+      if (expression == null) {
+        continue;
+      }
+      String text = expression.getText();
+      if (text != null) {
+        methodInfo.add(text);
       }
     }
 
-    PsiClass contributorClass = psiManager.findClassWithCache(contributorClassName, place.getResolveScope());
-    if (contributorClass != null) {
-      contributorClass.processDeclarations(processor, state, null, place);
+    for (GradleMethodContextContributor contributor : GradleMethodContextContributor.EP_NAME.getExtensions()) {
+      contributor.process(methodInfo, processor, state, place);
     }
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/ClassHolder.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/ClassHolder.java
new file mode 100644
index 0000000..97c30bc
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/ClassHolder.java
@@ -0,0 +1,88 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.gradle.settings;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.io.Serializable;
+
+/**
+ * Holds information about target class.
+ * 
+ * @author Denis Zhdanov
+ * @since 8/15/13 2:52 PM
+ */
+public class ClassHolder<T> implements Serializable {
+
+  private static final long serialVersionUID = 1L;
+
+  @NotNull private final String myClassName;
+  
+  @Nullable private transient Class<T> myTargetClass;
+
+  /**
+   * @param targetClass  class to use
+   */
+  @SuppressWarnings("NullableProblems")
+  public ClassHolder(@NotNull Class<T> targetClass) {
+    myTargetClass = targetClass;
+    myClassName = myTargetClass.getName();
+  }
+
+  @NotNull
+  public static <T> ClassHolder<T> from(@NotNull Class<T> clazz) {
+    return new ClassHolder<T>(clazz);
+  }
+
+  @SuppressWarnings("unchecked")
+  @NotNull
+  public Class<T> getTargetClass() throws ClassNotFoundException {
+    if (myTargetClass == null) {
+      // We're not afraid of race condition here as the class will be loaded by the same class loader.
+      myTargetClass = (Class<T>)Class.forName(myClassName);
+    }
+    return myTargetClass;
+  }
+
+  @NotNull
+  public String getTargetClassName() {
+    return myClassName;
+  }
+
+  @Override
+  public int hashCode() {
+    return myClassName.hashCode();
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    ClassHolder holder = (ClassHolder)o;
+
+    if (!myClassName.equals(holder.myClassName)) return false;
+    if (myTargetClass != null ? !myTargetClass.equals(holder.myTargetClass) : holder.myTargetClass != null) return false;
+
+    return true;
+  }
+
+  @Override
+  public String toString() {
+    return myClassName;
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java
index da6a114..71f334d 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/settings/GradleExecutionSettings.java
@@ -17,11 +17,11 @@
 
 import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
 import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.util.containers.ContainerUtilRt;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverExtension;
 
 import java.util.List;
 
@@ -35,7 +35,7 @@
 
   private static final long serialVersionUID = 1L;
 
-  @NotNull private final List<Pair<String, Class<?>>> myResolverExtensions = ContainerUtilRt.newArrayList();
+  @NotNull private final List<ClassHolder<? extends GradleProjectResolverExtension>> myResolverExtensions = ContainerUtilRt.newArrayList();
   @Nullable private final String myGradleHome;
   @Nullable private final String myServiceDirectory;
 
@@ -84,20 +84,12 @@
   }
 
   @NotNull
-  public List<Pair<String, Class<?>>> getResolverExtensions() {
+  public List<ClassHolder<? extends GradleProjectResolverExtension>> getResolverExtensions() {
     return myResolverExtensions;
   }
 
-  @SuppressWarnings("ConstantConditions")
-  public void addResolverExtensionClass(@NotNull String className) {
-    Pair<String, Class<?>> p = Pair.create(className, null);
-    myResolverExtensions.add(p);
-  }
-
-  @SuppressWarnings("ConstantConditions")
-  public void addResolverExtensionClass(@NotNull Class<?> clazz) {
-    Pair<String, Class<?>> p = new Pair<String, Class<?>>(null, clazz);
-    myResolverExtensions.add(p);
+  public void addResolverExtensionClass(@NotNull ClassHolder<? extends GradleProjectResolverExtension> holder) {
+    myResolverExtensions.add(holder);
   }
 
   /**
diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml
index bbf316d7..1be7e595 100644
--- a/plugins/groovy/src/META-INF/plugin.xml
+++ b/plugins/groovy/src/META-INF/plugin.xml
@@ -151,8 +151,11 @@
     <typeConverter implementation="org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrBooleanTypeConverter"/>
     <typeConverter implementation="org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrGenericTypeConverter"/>
     <typeConverter implementation="org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureToSamConverter"/>
-
+    <typeConverter implementation="org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrStringConverter"/>
+    <typeConverter implementation="org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrContainerConverter"/>
     <typeConverter implementation="org.jetbrains.plugins.groovy.gpp.GppTypeConverter"/>
+    <typeConverter implementation="org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrNumberConverter"/>
+
     <expectedTypesContributor implementation="org.jetbrains.plugins.groovy.gpp.GppExpectedTypesContributor"/>
     <variableEnhancer implementation="org.jetbrains.plugins.groovy.gpp.GppClosureParameterTypeProvider"/>
     <classSubstitutor implementation="org.jetbrains.plugins.groovy.gpp.GppClassSubstitutor"/>
diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java
index 564677a..bd0122f 100644
--- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java
+++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GroovyLanguageInjectionSupport.java
@@ -81,29 +81,29 @@
     if (!isStringLiteral(psiElement)) return false;
 
 
-    return doInject(language.getID(), psiElement);
+    return doInject(language.getID(), psiElement, psiElement);
   }
 
-  private static boolean doInject(String languageId, PsiElement host) {
-    final PsiElement target = getTopLevelInjectionTarget(host);
+  private static boolean doInject(String languageId, PsiElement psiElement, PsiLanguageInjectionHost host) {
+    final PsiElement target = getTopLevelInjectionTarget(psiElement);
     final PsiElement parent = target.getParent();
-    final Project project = host.getProject();
+    final Project project = psiElement.getProject();
 
     if (parent instanceof GrReturnStatement) {
       final GrControlFlowOwner owner = ControlFlowUtils.findControlFlowOwner(parent);
       if (owner instanceof GrOpenBlock && owner.getParent() instanceof GrMethod) {
-        return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)owner.getParent(), -1, languageId);
+        return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)owner.getParent(), -1, host, languageId);
       }
     }
     else if (parent instanceof GrMethod) {
-      return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (GrMethod)parent, -1, languageId);
+      return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (GrMethod)parent, -1, host, languageId);
     }
     else if (parent instanceof GrAnnotationNameValuePair) {
       final PsiReference ref = parent.getReference();
       if (ref != null) {
         final PsiElement resolved = ref.resolve();
         if (resolved instanceof PsiMethod) {
-          return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)resolved, -1, languageId);
+          return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, (PsiMethod)resolved, -1, host, languageId);
         }
       }
     }
@@ -112,7 +112,7 @@
       if (method != null) {
         final int index = findParameterIndex(target, ((GrMethodCall)parent.getParent()));
         if (index >= 0) {
-          return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, method, index, languageId);
+          return JavaLanguageInjectionSupport.doInjectInJavaMethod(project, method, index, host, languageId);
         }
       }
     }
@@ -121,16 +121,16 @@
       if (expr instanceof GrReferenceExpression) {
         final PsiElement element = ((GrReferenceExpression)expr).resolve();
         if (element != null) {
-          return doInject(languageId, element);
+          return doInject(languageId, element, host);
         }
       }
     }
     else {
       if (parent instanceof PsiVariable) {
-        if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)parent, languageId)) return true;
+        if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)parent, host, languageId)) return true;
       }
       else if (target instanceof PsiVariable && !(target instanceof LightElement)) {
-        if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)target, languageId)) return true;
+        if (JavaLanguageInjectionSupport.doAddLanguageAnnotation(project, (PsiModifierListOwner)target, host, languageId)) return true;
       }
     }
     return false;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/DefaultGroovyFrameworkConfigNotification.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/DefaultGroovyFrameworkConfigNotification.java
index bad8a50..eee671f 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/DefaultGroovyFrameworkConfigNotification.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/annotator/DefaultGroovyFrameworkConfigNotification.java
@@ -15,13 +15,14 @@
  */
 package org.jetbrains.plugins.groovy.annotator;
 
-import com.intellij.ide.util.frameworkSupport.AddFrameworkSupportDialog;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.roots.libraries.Library;
+import com.intellij.openapi.roots.ui.configuration.libraries.AddCustomLibraryDialog;
 import com.intellij.ui.EditorNotificationPanel;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.plugins.groovy.GroovyBundle;
 import org.jetbrains.plugins.groovy.config.GroovyConfigUtils;
+import org.jetbrains.plugins.groovy.config.GroovyLibraryDescription;
 
 /**
 * @author sergey.evdokimov
@@ -46,10 +47,7 @@
     panel.createActionLabel(GroovyBundle.message("configure.groovy.library"), new Runnable() {
       @Override
       public void run() {
-        AddFrameworkSupportDialog dialog = AddFrameworkSupportDialog.createDialog(module);
-        if (dialog != null) {
-          dialog.show();
-        }
+        AddCustomLibraryDialog.createDialog(new GroovyLibraryDescription(), module, null).show();
       }
     });
     return panel;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyInArgumentCheckInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyInArgumentCheckInspection.java
index 453d6f8..141f315 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyInArgumentCheckInspection.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/bugs/GroovyInArgumentCheckInspection.java
@@ -90,7 +90,7 @@
 
       if (component == null) return;
       
-      if (TypesUtil.isAssignable(component, ltype, expression)) return;
+      if (TypesUtil.isAssignableWithoutConversions(component, ltype, expression)) return;
 
       registerError(expression, ltype, rtype);
     }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyMembersWithDocSelectioner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyMembersWithDocSelectioner.java
index 2baace7..5c64f7c 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyMembersWithDocSelectioner.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyMembersWithDocSelectioner.java
@@ -15,7 +15,6 @@
  */
 package org.jetbrains.plugins.groovy.editor.selection;
 
-import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandler;
 import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.TextRange;
@@ -30,7 +29,7 @@
 /**
  * @author Max Medvedev
  */
-public class GroovyMembersWithDocSelectioner implements ExtendWordSelectionHandler {
+public class GroovyMembersWithDocSelectioner extends ExtendWordSelectionHandlerBase {
   @Override
   public boolean canSelect(PsiElement e) {
     return e instanceof GrDocComment || e instanceof GrDocCommentOwner;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyStatementSelectioner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyStatementSelectioner.java
index 8f0bab0..12df73c 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyStatementSelectioner.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyStatementSelectioner.java
@@ -15,7 +15,6 @@
  */
 package org.jetbrains.plugins.groovy.editor.selection;
 
-import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandler;
 import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.TextRange;
@@ -32,7 +31,7 @@
 /**
  * @author Max Medvedev
  */
-public class GroovyStatementSelectioner implements ExtendWordSelectionHandler {
+public class GroovyStatementSelectioner extends ExtendWordSelectionHandlerBase {
   @Override
   public boolean canSelect(PsiElement e) {
     return e instanceof GrExpression && PsiUtil.isExpressionStatement(e) ||
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyWordSelectionHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyWordSelectionHandler.java
index e19137e..5f5f683 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyWordSelectionHandler.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/editor/selection/GroovyWordSelectionHandler.java
@@ -15,7 +15,6 @@
  */
 package org.jetbrains.plugins.groovy.editor.selection;
 
-import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandler;
 import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase;
 import com.intellij.codeInsight.editorActions.SelectWordUtil;
 import com.intellij.openapi.diagnostic.Logger;
@@ -43,7 +42,7 @@
 /**
  * @author Max Medvedev
  */
-public class GroovyWordSelectionHandler implements ExtendWordSelectionHandler {
+public class GroovyWordSelectionHandler extends ExtendWordSelectionHandlerBase {
   private static final Logger LOG = Logger.getInstance(GroovyWordSelectionHandler.class);
 
   @Override
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodDescriptor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodDescriptor.java
index 9d7f9a5..4f06c15 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodDescriptor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodDescriptor.java
@@ -71,6 +71,9 @@
     @Attribute("referenceProvider")
     public String referenceProvider;
 
+    @Attribute("values")
+    public String values;
+
     protected Iterable<String> getNames() {
       assert !StringUtil.isEmptyOrSpaces(name);
       return StringUtil.tokenize(name, ATTR_NAMES_DELIMITER);
@@ -100,23 +103,6 @@
     }
   }
 
-  public Map<String, String> getNamedArgumentsReferenceProviders() {
-    if (myArguments == null) return Collections.emptyMap();
-
-    Map<String, String> res = new HashMap<String, String>();
-
-    for (NamedArgument argument : myArguments) {
-      if (argument.referenceProvider != null) {
-        for (String name : argument.getNames()) {
-          Object oldValue = res.put(name, argument.referenceProvider);
-          assert oldValue == null;
-        }
-      }
-    }
-
-    return res;
-  }
-
   @Nullable
   public Map<String, NamedArgumentDescriptor> getArgumentsMap() {
     if (myArguments == null && namedArgs == null) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodInfo.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodInfo.java
index 655e6cb..ae2972e 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodInfo.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/extensions/GroovyMethodInfo.java
@@ -12,6 +12,7 @@
 import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder;
 import org.jetbrains.plugins.groovy.refactoring.GroovyNamesUtil;
 import org.jetbrains.plugins.groovy.util.ClassInstanceCache;
+import org.jetbrains.plugins.groovy.util.FixedValuesReferenceProvider;
 
 import java.lang.reflect.Modifier;
 import java.util.*;
@@ -37,7 +38,7 @@
   private final String myNamedArgProviderClassName;
   private GroovyNamedArgumentProvider myNamedArgProviderInstance;
 
-  private Map<String, String> myNamedArgReferenceProviderClassNames;
+  private Map<String, NamedArgumentReference> myNamedArgReferenceProviders;
 
   private static void ensureInit() {
     if (METHOD_INFOS != null) return;
@@ -136,9 +137,9 @@
     myNamedArguments = method.getArgumentsMap();
     myNamedArgProviderClassName = method.namedArgsProvider;
 
-    myNamedArgReferenceProviderClassNames = method.getNamedArgumentsReferenceProviders();
+    myNamedArgReferenceProviders = getNamedArgumentsReferenceProviders(method);
 
-    myAllSupportedNamedArguments.addAll(myNamedArgReferenceProviderClassNames.keySet());
+    myAllSupportedNamedArguments.addAll(myNamedArgReferenceProviders.keySet());
 
     if (ApplicationManager.getApplication().isInternal()) {
       // Check classes to avoid typo.
@@ -147,8 +148,8 @@
 
       assertClassExists(myReturnTypeCalculatorClassName, PairFunction.class);
 
-      for (String className : myNamedArgReferenceProviderClassNames.values()) {
-        assertClassExists(className, PsiReferenceProvider.class, GroovyNamedArgumentReferenceProvider.class);
+      for (NamedArgumentReference r : myNamedArgReferenceProviders.values()) {
+        assertClassExists(r.myProviderClassName, PsiReferenceProvider.class, GroovyNamedArgumentReferenceProvider.class);
       }
     }
   }
@@ -171,6 +172,39 @@
     }
   }
 
+  private static Map<String, NamedArgumentReference> getNamedArgumentsReferenceProviders(GroovyMethodDescriptor methodDescriptor) {
+    if (methodDescriptor.myArguments == null) return Collections.emptyMap();
+
+    Map<String, NamedArgumentReference> res = new HashMap<String, NamedArgumentReference>();
+
+    for (GroovyMethodDescriptor.NamedArgument argument : methodDescriptor.myArguments) {
+      NamedArgumentReference r;
+
+      if (argument.referenceProvider != null) {
+        assert argument.values == null;
+        r = new NamedArgumentReference(argument.referenceProvider);
+      }
+      else if (argument.values != null) {
+        List<String> values = new ArrayList<String>();
+        for (StringTokenizer st = new StringTokenizer(argument.values, " ,;"); st.hasMoreTokens(); ) {
+          values.add(st.nextToken());
+        }
+
+        r = new NamedArgumentReference(values.toArray(new String[values.size()]));
+      }
+      else {
+        continue;
+      }
+
+      for (String name : argument.getNames()) {
+        Object oldValue = res.put(name, r);
+        assert oldValue == null;
+      }
+    }
+
+    return res;
+  }
+
   private static void addMethodDescriptor(Map<String, Map<String, List<GroovyMethodInfo>>> res,
                                           GroovyMethodDescriptor method,
                                           @NotNull ClassLoader classLoader,
@@ -235,10 +269,10 @@
    */
   @Nullable
   public Object getNamedArgReferenceProvider(String namedArgumentName) {
-    String className = myNamedArgReferenceProviderClassNames.get(namedArgumentName);
-    if (className == null) return null;
+    NamedArgumentReference r = myNamedArgReferenceProviders.get(namedArgumentName);
+    if (r == null) return null;
 
-    return ClassInstanceCache.getInstance(className, myClassLoader);
+    return r.getProvider(myClassLoader);
   }
 
   @Nullable
@@ -275,4 +309,40 @@
 
     return true;
   }
+
+  private static class NamedArgumentReference {
+    private final String myProviderClassName;
+    private final String[] myValues;
+
+    private volatile Object myProvider;
+
+    public NamedArgumentReference(String providerClassName) {
+      myProviderClassName = providerClassName;
+      myValues = null;
+    }
+
+    public NamedArgumentReference(String[] values) {
+      myValues = values;
+      myProviderClassName = null;
+    }
+
+    private Object doGetProvider(ClassLoader classLoader) {
+      if (myProviderClassName != null) {
+        return ClassInstanceCache.getInstance(myProviderClassName, classLoader);
+      }
+
+      return new FixedValuesReferenceProvider(myValues);
+    }
+
+    // @return instance of PsiReferenceProvider or GroovyNamedArgumentReferenceProvider or null.
+    public Object getProvider(ClassLoader classLoader) {
+      Object res = myProvider;
+      if (res == null) {
+        res = doGetProvider(classLoader);
+        myProvider = res;
+      }
+
+      return res;
+    }
+  }
 }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
index 25cbf3a..b3955ee 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
@@ -48,7 +48,6 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
 import org.jetbrains.plugins.groovy.lang.psi.impl.*;
 import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureImpl;
-import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.ClosureParameterEnhancer;
 import org.jetbrains.plugins.groovy.lang.psi.typeEnhancers.GrTypeConverter;
 import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames;
 import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
@@ -257,51 +256,31 @@
       return true;
     }
 
-    if (rType == PsiType.NULL) {
-      return !(lType instanceof PsiPrimitiveType);
-    }
-
-    if (isNumericType(lType) && isNumericType(rType)) {
+    if (isAssignableWithoutConversions(lType, rType, context)) {
       return true;
     }
 
-    if (isClassType(lType, JAVA_LANG_STRING)) {
-      return true;
+    Boolean byConversionInMethodCall = isAssignableByConversion(lType, rType, context, true);
+    if (byConversionInMethodCall != null) {
+      return byConversionInMethodCall.booleanValue();
+    }
+
+    if (lType instanceof PsiPrimitiveType && rType == PsiType.NULL) { //check it because now we will wrap primitive type.
+      return false;
     }
 
     final PsiManager manager = context.getManager();
     final GlobalSearchScope scope = context.getResolveScope();
 
-    if (lType instanceof PsiArrayType) {
-      PsiType lComponentType = ((PsiArrayType)lType).getComponentType();
-      PsiType rComponentType = ClosureParameterEnhancer.findTypeForIteration(rType, context);
-      if (rComponentType != null && isAssignable(lComponentType, rComponentType, context)) {
-        return true;
-      }
-    }
-
-    if (unboxPrimitiveTypeWrapper(lType) == PsiType.CHAR &&
-        (isClassType(rType, JAVA_LANG_STRING) || isClassType(rType, GROOVY_LANG_GSTRING))) {
-      return true;
-    }
-
-    if (isAssignableByMethodCallConversion(lType, rType, context)) return true;
-
     lType = boxPrimitiveType(lType, manager, scope);
     rType = boxPrimitiveType(rType, manager, scope);
     if (lType.isAssignableFrom(rType)) {
       return true;
     }
 
-    if (context instanceof GroovyPsiElement) {
-      for (GrTypeConverter converter : GrTypeConverter.EP_NAME.getExtensions()) {
-        if (!converter.isAllowedInMethodCall()) {
-          Boolean result = converter.isConvertible(lType, rType, (GroovyPsiElement)context);
-          if (result != null) {
-            return result;
-          }
-        }
-      }
+    Boolean byConversion = isAssignableByConversion(lType, rType, context, false);
+    if (byConversion != null) {
+      return byConversion.booleanValue();
     }
 
     return false;
@@ -316,7 +295,7 @@
 
     if (rType instanceof PsiIntersectionType) {
       for (PsiType child : ((PsiIntersectionType)rType).getConjuncts()) {
-        if (isAssignable(lType, child, context)) {
+        if (isAssignableByMethodCallConversion(lType, child, context)) {
           return true;
         }
       }
@@ -324,24 +303,33 @@
     }
     if (lType instanceof PsiIntersectionType) {
       for (PsiType child : ((PsiIntersectionType)lType).getConjuncts()) {
-        if (!isAssignable(child, rType, context)) {
+        if (!isAssignableByMethodCallConversion(child, rType, context)) {
           return false;
         }
       }
       return true;
     }
 
-    if (rType == PsiType.NULL) {
-      return !(lType instanceof PsiPrimitiveType);
-    }
-
     if (isAssignableWithoutConversions(lType, rType, context)) {
       return true;
     }
 
+    Boolean byConversion = isAssignableByConversion(lType, rType, context, true);
+    if (byConversion != null) {
+      return byConversion.booleanValue();
+    }
+
+    return false;
+  }
+
+  @Nullable
+  private static Boolean isAssignableByConversion(@NotNull PsiType lType,
+                                                  @NotNull PsiType rType,
+                                                  @NotNull PsiElement context,
+                                                  boolean inMethodCall) {
     if (context instanceof GroovyPsiElement) {
       for (GrTypeConverter converter : GrTypeConverter.EP_NAME.getExtensions()) {
-        if (converter.isAllowedInMethodCall()) {
+        if (inMethodCall == converter.isAllowedInMethodCall()) {
           final Boolean result = converter.isConvertible(lType, rType, (GroovyPsiElement)context);
           if (result != null) {
             return result;
@@ -349,8 +337,7 @@
         }
       }
     }
-
-    return false;
+    return null;
   }
 
   public static boolean isAssignableWithoutConversions(@Nullable PsiType lType,
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrContainerConverter.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrContainerConverter.java
new file mode 100644
index 0000000..fc92a50
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrContainerConverter.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.groovy.lang.psi.typeEnhancers;
+
+import com.intellij.psi.PsiArrayType;
+import com.intellij.psi.PsiType;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
+import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
+
+/**
+ * Created by Max Medvedev on 8/15/13
+ */
+public class GrContainerConverter extends GrTypeConverter {
+  @Override
+  public boolean isAllowedInMethodCall() {
+    return false;
+  }
+
+  @Nullable
+  @Override
+  public Boolean isConvertible(@NotNull PsiType lType, @NotNull PsiType rType, @NotNull GroovyPsiElement context) {
+    if (lType instanceof PsiArrayType) {
+      PsiType lComponentType = ((PsiArrayType)lType).getComponentType();
+      PsiType rComponentType = ClosureParameterEnhancer.findTypeForIteration(rType, context);
+      if (rComponentType != null && TypesUtil.isAssignable(lComponentType, rComponentType, context)) {
+        return Boolean.TRUE;
+      }
+    }
+
+    return null;
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrNumberConverter.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrNumberConverter.java
new file mode 100644
index 0000000..65ac67d
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrNumberConverter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.groovy.lang.psi.typeEnhancers;
+
+import com.intellij.psi.PsiType;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
+import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
+
+/**
+ * Created by Max Medvedev on 8/16/13
+ */
+public class GrNumberConverter extends GrTypeConverter {
+  @Override
+  public boolean isAllowedInMethodCall() {
+    return false;
+  }
+
+  @Nullable
+  @Override
+  public Boolean isConvertible(@NotNull PsiType lType, @NotNull PsiType rType, @NotNull GroovyPsiElement context) {
+    if (TypesUtil.isNumericType(lType) && TypesUtil.isNumericType(rType)) {
+      return Boolean.TRUE;
+    }
+
+    return null;
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrStringConverter.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrStringConverter.java
new file mode 100644
index 0000000..377c093
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/GrStringConverter.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.groovy.lang.psi.typeEnhancers;
+
+import com.intellij.psi.PsiType;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
+
+import static com.intellij.psi.CommonClassNames.JAVA_LANG_STRING;
+import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.isClassType;
+import static org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil.unboxPrimitiveTypeWrapper;
+import static org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_GSTRING;
+
+/**
+ * Created by Max Medvedev on 8/15/13
+ */
+public class GrStringConverter extends GrTypeConverter {
+  @Override
+  public boolean isAllowedInMethodCall() {
+    return false;
+  }
+
+  @Nullable
+  @Override
+  public Boolean isConvertible(@NotNull PsiType lType, @NotNull PsiType rType, @NotNull GroovyPsiElement context) {
+    if (isClassType(lType, JAVA_LANG_STRING)) {
+      return Boolean.TRUE;
+    }
+
+    if (unboxPrimitiveTypeWrapper(lType) == PsiType.CHAR &&
+        (isClassType(rType, JAVA_LANG_STRING) || isClassType(rType, GROOVY_LANG_GSTRING))) {
+      return Boolean.TRUE;
+    }
+
+    return null;
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunConfigurationEditor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunConfigurationEditor.java
index 1f2b126..6de8565 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunConfigurationEditor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcRunConfigurationEditor.java
@@ -21,8 +21,8 @@
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SettingsEditor;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.ui.PanelWithAnchor;
 import com.intellij.ui.DocumentAdapter;
+import com.intellij.ui.PanelWithAnchor;
 import com.intellij.ui.RawCommandLineEditor;
 import com.intellij.ui.components.JBLabel;
 import org.jetbrains.annotations.NotNull;
@@ -155,7 +155,4 @@
 
     return myMainPanel;
   }
-
-  protected void disposeEditor() {
-  }
 }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GrVariableInliner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GrVariableInliner.java
index 91d423e..7110ced 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GrVariableInliner.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GrVariableInliner.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -23,6 +23,7 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiReference;
 import com.intellij.psi.PsiSubstitutor;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
 import com.intellij.psi.util.PsiFormatUtil;
 import com.intellij.psi.util.PsiFormatUtilBase;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
@@ -40,9 +41,9 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrAccessorMethod;
 import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle;
 import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;
+import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase;
 
 import static org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.LOG;
-import static org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipParentheses;
 
 /**
  * @author Max Medvedev
@@ -59,7 +60,9 @@
       initializer = variable.getInitializerGroovy();
       LOG.assertTrue(initializer != null);
     }
-    myTempExpr = (GrExpression)skipParentheses(initializer, false);
+
+    myTempExpr = GrIntroduceHandlerBase.insertExplicitCastIfNeeded(variable, initializer);
+
   }
 
   @Nullable
@@ -112,6 +115,7 @@
 
     GrExpression newExpr = exprToBeReplaced.replaceWithExpression((GrExpression)initializer.copy(), true);
     final Project project = usage.getProject();
+    JavaCodeStyleManager.getInstance(project).shortenClassReferences(newExpr);
     Editor editor = FileEditorManager.getInstance(project).getSelectedTextEditor();
     GroovyRefactoringUtil.highlightOccurrences(project, editor, new PsiElement[]{newExpr});
     WindowManager.getInstance().getStatusBar(project).setInfo(GroovyRefactoringBundle.message("press.escape.to.remove.the.highlighting"));
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalProcessor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalProcessor.java
index b0173f0..ee4038d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalProcessor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/inline/GroovyInlineLocalProcessor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -47,6 +47,7 @@
 import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ControlFlowBuilder;
 import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
 import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringBundle;
+import org.jetbrains.plugins.groovy.refactoring.introduce.GrIntroduceHandlerBase;
 
 import java.util.ArrayList;
 import java.util.BitSet;
@@ -194,11 +195,14 @@
   protected void performRefactoring(UsageInfo[] usages) {
     CommonRefactoringUtil.sortDepthFirstRightLeftOrder(usages);
 
+    final GrExpression initializer = mySettings.getInitializer();
+
+    GrExpression initializerToUse = GrIntroduceHandlerBase.insertExplicitCastIfNeeded(myLocal, mySettings.getInitializer());
+
     for (UsageInfo usage : usages) {
-      GrVariableInliner.inlineReference(usage, myLocal, mySettings.getInitializer());
+      GrVariableInliner.inlineReference(usage, myLocal, initializerToUse);
     }
 
-    final GrExpression initializer = mySettings.getInitializer();
     final PsiElement initializerParent = initializer.getParent();
 
     if (initializerParent instanceof GrAssignmentExpression) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java
index f2fee48..bed8605 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/GrIntroduceHandlerBase.java
@@ -62,6 +62,7 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrLiteral;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.params.GrParameter;
+import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
 import org.jetbrains.plugins.groovy.lang.psi.util.GrStringUtil;
 import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
 import org.jetbrains.plugins.groovy.refactoring.GrRefactoringError;
@@ -71,6 +72,8 @@
 
 import java.util.*;
 
+import static org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil.skipParentheses;
+
 /**
  * @author Maxim.Medvedev
  */
@@ -82,6 +85,38 @@
     }
   };
 
+  public static GrExpression insertExplicitCastIfNeeded(GrVariable variable, GrExpression initializer) {
+    PsiType ltype = findLValueType(initializer);
+    PsiType rtype = initializer.getType();
+
+    GrExpression rawExpr = (GrExpression)skipParentheses(initializer, false);
+
+    if (ltype == null || TypesUtil.isAssignableWithoutConversions(ltype, rtype, initializer) || !TypesUtil.isAssignable(ltype, rtype, initializer)) {
+      return rawExpr;
+    }
+    else { // implicit coercion should be replaced with explicit cast
+      GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(variable.getProject());
+      GrSafeCastExpression cast =
+        (GrSafeCastExpression)factory.createExpressionFromText("a as B");
+      cast.getOperand().replaceWithExpression(rawExpr, false);
+      cast.getCastTypeElement().replace(factory.createTypeElement(ltype));
+      return cast;
+    }
+  }
+
+  @Nullable
+  private static PsiType findLValueType(GrExpression initializer) {
+    if (initializer.getParent() instanceof GrAssignmentExpression && ((GrAssignmentExpression)initializer.getParent()).getRValue() == initializer) {
+      return ((GrAssignmentExpression)initializer.getParent()).getLValue().getNominalType();
+    }
+    else if (initializer.getParent() instanceof GrVariable) {
+      return ((GrVariable)initializer.getParent()).getDeclaredType();
+    }
+    else {
+      return null;
+    }
+  }
+
   @NotNull
   protected abstract String getRefactoringName();
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyRunConfigurationEditor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyRunConfigurationEditor.java
index 82f760b..251e7c1 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyRunConfigurationEditor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/runner/GroovyRunConfigurationEditor.java
@@ -138,9 +138,6 @@
     return myMainPanel;
   }
 
-  public void disposeEditor() {
-  }
-
   @Override
   public JComponent getAnchor() {
     return anchor;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/util/FixedValuesReferenceProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/util/FixedValuesReferenceProvider.java
new file mode 100644
index 0000000..5ccdd81
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/util/FixedValuesReferenceProvider.java
@@ -0,0 +1,48 @@
+package org.jetbrains.plugins.groovy.util;
+
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiReference;
+import com.intellij.psi.PsiReferenceBase;
+import com.intellij.psi.PsiReferenceProvider;
+import com.intellij.util.ProcessingContext;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author Sergey Evdokimov
+ */
+public class FixedValuesReferenceProvider extends PsiReferenceProvider {
+
+  private final String[] myValues;
+
+  private boolean mySoft;
+
+  public FixedValuesReferenceProvider(@NotNull String[] values) {
+    this(values, false);
+  }
+
+  public FixedValuesReferenceProvider(@NotNull String[] values, boolean soft) {
+    myValues = values;
+    mySoft = soft;
+  }
+
+  @NotNull
+  @Override
+  public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull ProcessingContext context) {
+    return new PsiReference[]{
+      new PsiReferenceBase<PsiElement>(element, mySoft) {
+        @Nullable
+        @Override
+        public PsiElement resolve() {
+          return null;
+        }
+
+        @NotNull
+        @Override
+        public Object[] getVariants() {
+          return myValues;
+        }
+      }
+    };
+  }
+}
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/inline/InlineVariableTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/inline/InlineVariableTest.groovy
index 789ef53..a0a96d2 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/inline/InlineVariableTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/refactoring/inline/InlineVariableTest.groovy
@@ -1,5 +1,6 @@
 /*
- * Copyright 2000-2007 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
  * You may obtain a copy of the License at
@@ -71,6 +72,9 @@
 
   public void testUndefinedVarInline() {doTest()}
 
+  public void testImplicitCast() { doTest() }
+  public void testImplicitCast2() { doTest() }
+
   protected void doFieldTest() {
     InlineMethodTest.doInlineTest(myFixture, testDataPath + getTestName(true) + ".test", new GroovyInlineHandler());
   }
diff --git a/plugins/groovy/testdata/groovy/refactoring/inlineLocal/ImplicitCast.test b/plugins/groovy/testdata/groovy/refactoring/inlineLocal/ImplicitCast.test
new file mode 100644
index 0000000..9cfa98f
--- /dev/null
+++ b/plugins/groovy/testdata/groovy/refactoring/inlineLocal/ImplicitCast.test
@@ -0,0 +1,5 @@
+String s = 2
+
+print <selection>s</selection>
+-----
+print 2 as String
diff --git a/plugins/groovy/testdata/groovy/refactoring/inlineLocal/implicitCast2.test b/plugins/groovy/testdata/groovy/refactoring/inlineLocal/implicitCast2.test
new file mode 100644
index 0000000..871700e
--- /dev/null
+++ b/plugins/groovy/testdata/groovy/refactoring/inlineLocal/implicitCast2.test
@@ -0,0 +1,6 @@
+String s = 'a'
+s = 2
+print <selection>s</selection>
+-----
+String s = 'a'
+print 2 as String
diff --git a/plugins/groovy/testdata/highlighting/MemberShipOperatorCheck.groovy b/plugins/groovy/testdata/highlighting/MemberShipOperatorCheck.groovy
index 816c31c..8e5bb16 100644
--- a/plugins/groovy/testdata/highlighting/MemberShipOperatorCheck.groovy
+++ b/plugins/groovy/testdata/highlighting/MemberShipOperatorCheck.groovy
@@ -21,10 +21,10 @@
 }
 
 print (1 in [1])
-print (1 in ['a'])
+print (<warning descr="'ArrayList<String>' cannot contain 'Integer'">1 in ['a']</warning>)
 print (1 in 1)
 print (<warning descr="'ArrayList<Integer>' cannot contain 'ArrayList<Integer>'">[2] in [2]</warning>)
 
 print (1 in new ArrayList())
 print (<warning descr="'Integer' cannot contain 'Date'">new Date() in 2</warning>)
-print (<warning>'a' in [1]</warning>)
\ No newline at end of file
+print (<warning descr="'ArrayList<Integer>' cannot contain 'String'">'a' in [1]</warning>)
\ No newline at end of file
diff --git a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXHighlightingTest.java b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXHighlightingTest.java
index a88550b..7d902cf 100644
--- a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXHighlightingTest.java
+++ b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXHighlightingTest.java
@@ -245,6 +245,10 @@
     doTest();
   }
 
+  public void testReadOnly1() throws Exception {
+    doTest();
+  }
+
   public void testScriptSource() throws Exception {
     doTest("s1.js");
   }
diff --git a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXUnresolvedFxIdReferenceInspectionTest.java b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXUnresolvedFxIdReferenceInspectionTest.java
index 831169f..5a49915 100644
--- a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXUnresolvedFxIdReferenceInspectionTest.java
+++ b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/fxml/JavaFXUnresolvedFxIdReferenceInspectionTest.java
@@ -43,6 +43,17 @@
     assertEmpty(intentionActions);
   }
 
+  public void testFieldsFromControllerSuper() throws Exception {
+    myFixture.addClass("import javafx.scene.control.RadioButton;\n" +
+                       "public class SuperController {\n" +
+                       "    public RadioButton option1;\n" +
+                       "}\n");
+    myFixture.addClass("public class Controller extends SuperController {}");
+    final String testFxml = getTestName(true) + ".fxml";
+    myFixture.configureByFile(testFxml);
+    myFixture.testHighlighting(true, false, false, testFxml);
+  }
+
   private void doTest(final String controllerName) {
     myFixture.configureByFiles(getTestName(true) + ".fxml", controllerName + ".java");
     final IntentionAction singleIntention = myFixture.findSingleIntention(getHint("unknown"));
diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java
index f680469..0becfab 100644
--- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java
+++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/JavaFxPsiUtil.java
@@ -187,7 +187,7 @@
   public static PsiMethod findPropertySetter(String attributeName, PsiClass classWithStaticProperty) {
     final String setterName = PropertyUtil.suggestSetterName(StringUtil.getShortName(attributeName));
     final PsiMethod[] setters = classWithStaticProperty.findMethodsByName(setterName, true);
-    if (setters.length == 1) {
+    if (setters.length >= 1) {
       return setters[0];
     }
     return null;
diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java
index 3ec363f..09cd1a5 100644
--- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java
+++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/fxml/refs/JavaFxFieldIdReferenceProvider.java
@@ -36,7 +36,7 @@
   protected PsiReference[] getReferencesByElement(@NotNull final PsiClass aClass,
                                                   final XmlAttributeValue xmlAttributeValue,
                                                   ProcessingContext context) {
-    final PsiField field = aClass.findFieldByName(xmlAttributeValue.getValue(), false);
+    final PsiField field = aClass.findFieldByName(xmlAttributeValue.getValue(), true);
     return new PsiReference[]{new JavaFxControllerFieldRef(xmlAttributeValue, field, aClass)};
   }
 
diff --git a/plugins/javaFX/testData/highlighting/readOnly1.fxml b/plugins/javaFX/testData/highlighting/readOnly1.fxml
new file mode 100644
index 0000000..a5fb9ae
--- /dev/null
+++ b/plugins/javaFX/testData/highlighting/readOnly1.fxml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<?import javafx.scene.control.RadioButton?>
+<?import javafx.scene.control.ToggleGroup?>
+<?import javafx.scene.layout.StackPane?>
+<StackPane xmlns:fx="http://javafx.com/fxml">
+    <RadioButton fx:id="option1" disable="true" mnemonicParsing="false" text="Option 1">
+        <toggleGroup>
+            <ToggleGroup fx:id="toggleGroup1"/>
+        </toggleGroup>
+    </RadioButton>
+    <RadioButton fx:id="option2" disable="true" mnemonicParsing="false" text="Option 2" toggleGroup="$toggleGroup1"/>
+</StackPane>
diff --git a/plugins/javaFX/testData/inspections/unresolvedFxId/fieldsFromControllerSuper.fxml b/plugins/javaFX/testData/inspections/unresolvedFxId/fieldsFromControllerSuper.fxml
new file mode 100644
index 0000000..12139f3
--- /dev/null
+++ b/plugins/javaFX/testData/inspections/unresolvedFxId/fieldsFromControllerSuper.fxml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+
+<?import javafx.scene.control.RadioButton?>
+<?import javafx.scene.control.ToggleGroup?>
+<?import javafx.scene.layout.StackPane?>
+<StackPane xmlns:fx="http://javafx.com/fxml" fx:controller="Controller">
+    <RadioButton fx:id="option1" disable="true" mnemonicParsing="false" text="Option 1">
+        <toggleGroup>
+            <ToggleGroup fx:id="<warning descr="Unresolved fx:id reference">toggleGroup1</warning>"/>
+        </toggleGroup>
+    </RadioButton>
+    <RadioButton fx:id="<warning descr="Unresolved fx:id reference">option2</warning>" disable="true" mnemonicParsing="false" text="$option1" toggleGroup="$toggleGroup1"/>
+</StackPane>
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java
index cdd5ad0..1020065 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java
@@ -295,6 +295,7 @@
         }
       }
     };
+    Disposer.register(consoleView, packetsReceiver);
 
     final DeferredActionsQueue queue = new DeferredActionsQueueImpl();
     handler.getOut().setPacketDispatcher(packetsReceiver, queue);
diff --git a/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurable.java b/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurable.java
index 4be99ae..d564b54 100644
--- a/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurable.java
+++ b/plugins/junit/src/com/intellij/execution/junit2/configuration/JUnitConfigurable.java
@@ -31,14 +31,13 @@
 import com.intellij.execution.ui.CommonJavaParametersPanel;
 import com.intellij.execution.ui.ConfigurationModuleSelector;
 import com.intellij.icons.AllIcons;
-import com.intellij.openapi.fileTypes.PlainTextLanguage;
-import com.intellij.ui.ListCellRendererWrapper;
 import com.intellij.ide.util.ClassFilter;
 import com.intellij.ide.util.PackageChooserDialog;
 import com.intellij.openapi.fileChooser.FileChooser;
 import com.intellij.openapi.fileChooser.FileChooserDescriptor;
 import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
 import com.intellij.openapi.fileChooser.FileChooserFactory;
+import com.intellij.openapi.fileTypes.PlainTextLanguage;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.options.SettingsEditor;
 import com.intellij.openapi.project.Project;
@@ -47,10 +46,7 @@
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
-import com.intellij.ui.EditorTextField;
-import com.intellij.ui.EditorTextFieldWithBrowseButton;
-import com.intellij.ui.InsertPathAction;
-import com.intellij.ui.PanelWithAnchor;
+import com.intellij.ui.*;
 import com.intellij.ui.components.JBLabel;
 import com.intellij.util.IconUtil;
 import com.intellij.util.TextFieldCompletionProvider;
@@ -577,9 +573,6 @@
     return myWholePanel;
   }
 
-  public void disposeEditor() {
-  }
-
   private void applyHelpersTo(final JUnitConfiguration currentState) {
     myCommonJavaParameters.applyTo(currentState);
     getModuleSelector().applyTo(currentState);
diff --git a/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java b/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java
index b6c1257..90aa442 100644
--- a/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java
+++ b/plugins/junit/src/com/intellij/execution/junit2/ui/TestsPacketsReceiver.java
@@ -83,7 +83,6 @@
     myUnboundOutput = unboundOutput;
     myObjectRegistry = new InputObjectRegistry();
     myConsoleProperties = (JUnitConsoleProperties)consoleView.getProperties();
-    Disposer.register(consoleView, this);
   }
 
   @Override
diff --git a/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/model/MavenConstants.java b/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/model/MavenConstants.java
index 4c8c854..dea93b3 100644
--- a/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/model/MavenConstants.java
+++ b/plugins/maven/maven-server-api/src/org/jetbrains/idea/maven/model/MavenConstants.java
@@ -50,6 +50,6 @@
                   "post-integration-test",
                   "verify", "install", "site", "deploy");
   public static final List<String> BASIC_PHASES =
-    Arrays.asList("clean", "validate", "compile", "test", "package", "install", "deploy", "site");
+    Arrays.asList("clean", "validate", "compile", "test", "package", "verify", "install", "deploy", "site");
 
 }
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/DependencyId.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/DependencyId.java
deleted file mode 100644
index f71270c..0000000
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/DependencyId.java
+++ /dev/null
@@ -1,63 +0,0 @@
-package org.jetbrains.idea.maven.dom;
-
-import com.intellij.openapi.util.text.StringUtil;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.idea.maven.dom.model.MavenDomDependency;
-
-/**
-* @author Sergey Evdokimov
-*/
-public class DependencyId {
-  private final String groupId;
-  private final String artifactId;
-  private final String type;
-  private final String classifier;
-
-  public DependencyId(@NotNull String groupId, @NotNull String artifactId, @Nullable String type, @Nullable String classifier) {
-    this.groupId = groupId;
-    this.artifactId = artifactId;
-    this.type = StringUtil.isEmpty(type) ? "jar" : type;
-    this.classifier = classifier;
-  }
-
-  @Nullable
-  public static DependencyId create(@NotNull MavenDomDependency dep) {
-    String groupId = dep.getGroupId().getStringValue();
-    if (StringUtil.isEmpty(groupId)) return null;
-
-    String artifactId = dep.getArtifactId().getStringValue();
-    if (StringUtil.isEmpty(artifactId)) return null;
-
-    //noinspection ConstantConditions
-    return new DependencyId(groupId, artifactId, dep.getType().getStringValue(), dep.getClassifier().getStringValue());
-  }
-
-  public boolean isValid() {
-    return StringUtil.isNotEmpty(groupId) && StringUtil.isNotEmpty(artifactId);
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (!(o instanceof DependencyId)) return false;
-
-    DependencyId id = (DependencyId)o;
-
-    if (artifactId != null ? !artifactId.equals(id.artifactId) : id.artifactId != null) return false;
-    if (classifier != null ? !classifier.equals(id.classifier) : id.classifier != null) return false;
-    if (groupId != null ? !groupId.equals(id.groupId) : id.groupId != null) return false;
-    if (!type.equals(id.type)) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    int result = groupId != null ? groupId.hashCode() : 0;
-    result = 31 * result + (artifactId != null ? artifactId.hashCode() : 0);
-    result = 31 * result + type.hashCode();
-    result = 31 * result + (classifier != null ? classifier.hashCode() : 0);
-    return result;
-  }
-}
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java
index 87d9dea..b31928c 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenRunnerSettingsEditor.java
@@ -75,9 +75,4 @@
     myUseProjectSettings = pair.second;
     return pair.first;
   }
-
-  @Override
-  protected void disposeEditor() {
-
-  }
 }
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java
index 09c9c6c..23ddb24 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenConsoleImpl.java
@@ -39,7 +39,6 @@
 import org.jetbrains.idea.maven.execution.MavenRunnerSettings;
 import org.jetbrains.idea.maven.utils.MavenUtil;
 
-import java.util.List;
 import java.util.concurrent.atomic.AtomicBoolean;
 
 public class MavenConsoleImpl extends MavenConsole {
@@ -79,10 +78,7 @@
   public static TextConsoleBuilder createConsoleBuilder(final Project project) {
     TextConsoleBuilder builder = TextConsoleBuilderFactory.getInstance().createBuilder(project);
 
-    final List<Filter> filters = ExceptionFilters.getFilters(GlobalSearchScope.allScope(project));
-    for (Filter filter : filters) {
-      builder.addFilter(filter);
-    }
+    builder.filters(ExceptionFilters.getFilters(GlobalSearchScope.allScope(project)));
     builder.addFilter(new RegexpFilter(project, CONSOLE_FILTER_REGEXP) {
       @Nullable
       @Override
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java
index 5a32398..989a5e6 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/actions/SwitchTaskCombo.java
@@ -112,7 +112,6 @@
 
   private static String getText(LocalTask activeTask) {
     String text = activeTask.getPresentableName();
-    return StringUtil.first(text, 80, true);
+    return StringUtil.first(text, 50, true);
   }
-
 }
diff --git a/plugins/tasks/tasks-tests/test/com/intellij/tasks/vcs/TaskBranchesTest.java b/plugins/tasks/tasks-tests/test/com/intellij/tasks/vcs/TaskBranchesTest.java
index 1dbfff0..1261d12 100644
--- a/plugins/tasks/tasks-tests/test/com/intellij/tasks/vcs/TaskBranchesTest.java
+++ b/plugins/tasks/tasks-tests/test/com/intellij/tasks/vcs/TaskBranchesTest.java
@@ -25,7 +25,9 @@
 import com.intellij.util.Function;
 import com.intellij.util.containers.ContainerUtil;
 import git4idea.branch.GitBranchesCollection;
+import git4idea.config.GitVcsSettings;
 import git4idea.repo.GitRepository;
+import git4idea.test.GitExecutor;
 import git4idea.test.GitTestUtil;
 
 import java.io.File;
@@ -125,5 +127,6 @@
   protected void setUp() throws Exception {
     super.setUp();
     myTaskManager = (TaskManagerImpl)TaskManager.getManager(getProject());
+    GitVcsSettings.getInstance(myProject).getAppSettings().setPathToGit(GitExecutor.GIT_EXECUTABLE);
   }
 }
diff --git a/plugins/terminal/lib/jediterm-pty-0.08.jar b/plugins/terminal/lib/jediterm-pty-0.08.jar
index 5fe6a5f..e9bf336 100644
--- a/plugins/terminal/lib/jediterm-pty-0.08.jar
+++ b/plugins/terminal/lib/jediterm-pty-0.08.jar
Binary files differ
diff --git a/plugins/terminal/lib/win/x86/libwinpty.dll b/plugins/terminal/lib/win/x86/libwinpty.dll
index 9a7eaf6..2b581b2 100644
--- a/plugins/terminal/lib/win/x86/libwinpty.dll
+++ b/plugins/terminal/lib/win/x86/libwinpty.dll
Binary files differ
diff --git a/plugins/terminal/lib/win/x86_64/libwinpty.dll b/plugins/terminal/lib/win/x86_64/libwinpty.dll
new file mode 100644
index 0000000..dea8dcf
--- /dev/null
+++ b/plugins/terminal/lib/win/x86_64/libwinpty.dll
Binary files differ
diff --git a/plugins/terminal/lib/win/x86_64/winpty-agent.exe b/plugins/terminal/lib/win/x86_64/winpty-agent.exe
new file mode 100644
index 0000000..9083e03
--- /dev/null
+++ b/plugins/terminal/lib/win/x86_64/winpty-agent.exe
Binary files differ
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java
index 926fbd1..0ddfd9f 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/AbstractTerminalRunner.java
@@ -14,11 +14,13 @@
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.wm.IdeFocusManager;
 import com.intellij.openapi.wm.ToolWindow;
 import com.intellij.openapi.wm.ToolWindowManager;
 import com.intellij.util.ui.UIUtil;
 import com.jediterm.terminal.TtyConnector;
+import com.jediterm.terminal.emulator.ColorPalette;
 import com.jediterm.terminal.ui.AbstractSystemSettingsProvider;
 import com.jediterm.terminal.ui.TerminalSession;
 import com.jediterm.terminal.ui.TerminalWidget;
@@ -43,9 +45,9 @@
   }
 
   public void run() {
-    ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Connecting to terminal", false) {
+    ProgressManager.getInstance().run(new Task.Backgroundable(myProject, "Running the terminal", false) {
       public void run(@NotNull final ProgressIndicator indicator) {
-        indicator.setText("Connecting to terminal...");
+        indicator.setText("Running the terminal...");
         try {
           doRun();
         }
@@ -85,7 +87,7 @@
 
   protected abstract ProcessHandler createProcessHandler(T process);
 
-  public TerminalWidget createTerminalWidget() {
+  public JBTabbedTerminalWidget createTerminalWidget() {
     JBTerminalSystemSettingsProvider provider = new JBTerminalSystemSettingsProvider();
     JBTabbedTerminalWidget terminalWidget = new JBTabbedTerminalWidget(provider);
     provider.setTerminalWidget(terminalWidget);
@@ -126,8 +128,7 @@
   }
 
   public static void openSession(TerminalWidget terminal, TtyConnector ttyConnector) {
-    TerminalSession session = terminal.createTerminalSession();
-    session.setTtyConnector(ttyConnector);
+    TerminalSession session = terminal.createTerminalSession(ttyConnector);
     session.start();
   }
 
@@ -184,6 +185,11 @@
       return getKeyStrokesByActionId("$Paste");
     }
 
+    @Override
+    public ColorPalette getPalette() {
+      return SystemInfo.isWindows ? ColorPalette.WINDOWS_PALETTE : ColorPalette.XTERM_PALETTE;
+    }
+
     private KeyStroke[] getKeyStrokesByActionId(String actionId) {
       java.util.List<KeyStroke> keyStrokes = new ArrayList<KeyStroke>();
       Shortcut[] shortcuts = KeymapManager.getInstance().getActiveKeymap().getShortcuts(actionId);
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java
index 20866c6..7a83c32 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java
@@ -27,6 +27,7 @@
 import com.intellij.openapi.ide.CopyPasteManager;
 import com.intellij.util.ui.GraphicsUtil;
 import com.intellij.util.ui.UIUtil;
+import com.jediterm.terminal.TerminalColor;
 import com.jediterm.terminal.TextStyle;
 import com.jediterm.terminal.display.BackBuffer;
 import com.jediterm.terminal.display.StyleState;
@@ -52,20 +53,21 @@
                          @NotNull EditorColorsScheme scheme) {
     super(settingsProvider, backBuffer, styleState);
     myColorScheme = scheme;
-    
 
-    styleState.setDefaultStyle(new TextStyle(myColorScheme.getDefaultForeground(), myColorScheme.getDefaultBackground()));
 
-    setSelectionColor(new TextStyle(myColorScheme.getColor(EditorColors.SELECTION_FOREGROUND_COLOR),
-                                    myColorScheme.getColor(EditorColors.SELECTION_BACKGROUND_COLOR)));
-    
+    styleState.setDefaultStyle(new TextStyle(TerminalColor.awt(myColorScheme.getDefaultForeground()), TerminalColor.awt(
+      myColorScheme.getDefaultBackground())));
+
+    setSelectionColor(new TextStyle(TerminalColor.awt(myColorScheme.getColor(EditorColors.SELECTION_FOREGROUND_COLOR)),
+                                    TerminalColor.awt(myColorScheme.getColor(EditorColors.SELECTION_BACKGROUND_COLOR))));
+
     setLineSpace(myColorScheme.getConsoleLineSpacing());
   }
 
   protected Font createFont() {
 
     Font normalFont = Font.decode(getFontName());
-    
+
     if (normalFont == null) {
       normalFont = super.createFont();
     }
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalToolWindowFactory.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalToolWindowFactory.java
index 5b4cf95..ad7d06a 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalToolWindowFactory.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalToolWindowFactory.java
@@ -11,6 +11,6 @@
   @Override
   public void createToolWindowContent(Project project, ToolWindow toolWindow) {
     TerminalView terminalView = TerminalView.getInstance();
-    terminalView.createTerminal(project, toolWindow);
+    terminalView.initTerminal(project, toolWindow);
   }
 }
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java
index 34757ae..73c8d69 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalView.java
@@ -23,21 +23,27 @@
  */
 public class TerminalView {
 
-  private TerminalWidget myTerminalWidget;
+  private JBTabbedTerminalWidget myTerminalWidget;
+  private Project myProject;
 
-  public void createTerminal(Project project, ToolWindow toolWindow) {
-
+  public void initTerminal(Project project, ToolWindow toolWindow) {
+    myProject = project;
     LocalTerminalDirectRunner terminalRunner = OpenLocalTerminalAction.createTerminalRunner(project);
-
+    
+    toolWindow.setToHideOnEmptyContent(true);
+    
     if (terminalRunner != null) {
       myTerminalWidget = terminalRunner.createTerminalWidget();
     }
 
-    final Content content = createToolWindowContentPanel(terminalRunner, myTerminalWidget);
+    Content content = createToolWindowContentPanel(terminalRunner, myTerminalWidget, toolWindow);
+    
     toolWindow.getContentManager().addContent(content);
   }
 
-  private Content createToolWindowContentPanel(@Nullable LocalTerminalDirectRunner terminalRunner, TerminalWidget terminalWidget) {
+  private Content createToolWindowContentPanel(@Nullable LocalTerminalDirectRunner terminalRunner,
+                                               JBTabbedTerminalWidget terminalWidget,
+                                               ToolWindow toolWindow) {
     SimpleToolWindowPanel panel = new SimpleToolWindowPanel(false, true) {
       @Override
       public Object getData(@NonNls String dataId) {
@@ -50,12 +56,13 @@
       panel.addFocusListener(createFocusListener());
     }
 
-    ActionToolbar toolbar = createToolbar(terminalRunner, terminalWidget);
+    ActionToolbar toolbar = createToolbar(terminalRunner, terminalWidget, toolWindow);
     toolbar.getComponent().addFocusListener(createFocusListener());
     toolbar.setTargetComponent(panel);
     panel.setToolbar(toolbar.getComponent());
 
     final Content content = ContentFactory.SERVICE.getInstance().createContent(panel, "", false);
+    content.setCloseable(true);
 
     if (getComponentToFocus() != null) {
       content.setPreferredFocusableComponent(getComponentToFocus());
@@ -89,18 +96,18 @@
     openSession(terminal, terminalRunner);
   }
 
-  private void openSession(ToolWindow terminal, AbstractTerminalRunner terminalRunner) {
+  private void openSession(ToolWindow toolWindow, AbstractTerminalRunner terminalRunner) {
     if (myTerminalWidget == null) {
       myTerminalWidget = terminalRunner.createTerminalWidget();
-      terminal.getContentManager().removeAllContents(true);
-      final Content content = createToolWindowContentPanel(null, myTerminalWidget);
-      terminal.getContentManager().addContent(content);
+      toolWindow.getContentManager().removeAllContents(true);
+      final Content content = createToolWindowContentPanel(null, myTerminalWidget, toolWindow);
+      toolWindow.getContentManager().addContent(content);
     }
     else {
       terminalRunner.openSession(myTerminalWidget);
     }
 
-    terminal.activate(new Runnable() {
+    toolWindow.activate(new Runnable() {
       @Override
       public void run() {
 
@@ -112,26 +119,25 @@
     return ServiceManager.getService(TerminalView.class);
   }
 
-  private static ActionToolbar createToolbar(@Nullable final LocalTerminalDirectRunner terminalRunner,
-                                             final TerminalWidget terminal) {
+  private ActionToolbar createToolbar(@Nullable final LocalTerminalDirectRunner terminalRunner,
+                                             final JBTabbedTerminalWidget terminal, ToolWindow toolWindow) {
     DefaultActionGroup group = new DefaultActionGroup();
 
     if (terminalRunner != null) {
       group.add(new NewSession(terminalRunner, terminal));
+      group.add(new CloseSession(terminal, toolWindow));
     }
 
     return ActionManager.getInstance().createActionToolbar(ActionPlaces.UNKNOWN, group, false);
   }
 
-  public void createNewSession(Project project, AbstractTerminalRunner terminalRunner) {
-    ToolWindow terminal = ToolWindowManager.getInstance(project).getToolWindow("Terminal");
+  public void createNewSession(Project project, final AbstractTerminalRunner terminalRunner) {
+    final ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow("Terminal");
 
-    openSession(terminal, terminalRunner);
-
-    terminal.activate(new Runnable() {
+    toolWindow.activate(new Runnable() {
       @Override
       public void run() {
-
+        openSession(toolWindow, terminalRunner);
       }
     }, true);
   }
@@ -151,4 +157,33 @@
       myTerminalRunner.openSession(myTerminal);
     }
   }
+
+  private class CloseSession extends AnAction {
+    private final JBTabbedTerminalWidget myTerminal;
+    private ToolWindow myToolWindow;
+
+    public CloseSession(JBTabbedTerminalWidget terminal, ToolWindow toolWindow) {
+      super("Close Session", "Close Terminal Session", AllIcons.Actions.Delete);
+      myTerminal = terminal;
+      myToolWindow = toolWindow;
+    }
+
+    @Override
+    public void actionPerformed(AnActionEvent e) {
+      boolean singleSession = myTerminal.isSingleSession();
+      
+      myTerminal.closeCurrentSession();
+      
+      if (singleSession) {
+        myToolWindow.getContentManager().removeAllContents(true);
+        
+        myToolWindow.getActivation().doWhenDone(new Runnable() {
+          @Override
+          public void run() {
+            initTerminal(myProject, myToolWindow);
+          }
+        });
+      }
+    }
+  }
 }
diff --git a/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java b/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java
index c167004..f91e7fc 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java
@@ -36,7 +36,6 @@
 import com.intellij.psi.*;
 import com.intellij.psi.filters.ElementFilter;
 import com.intellij.psi.filters.position.FilterPattern;
-import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProviderBase;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.util.ArrayUtil;
@@ -57,26 +56,26 @@
   }
 
   public void registerReferenceProviders(PsiReferenceRegistrar registrar) {
-    registrar.registerReferenceProvider(getElementPattern("dependsOnMethods"), new PsiReferenceProviderBase() {
+    registrar.registerReferenceProvider(getElementPattern("dependsOnMethods"), new PsiReferenceProvider() {
       @NotNull
       public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
         return new MethodReference[]{new MethodReference((PsiLiteralExpression)element)};
       }
     });
 
-    registrar.registerReferenceProvider(getElementPattern("dataProvider"), new PsiReferenceProviderBase() {
+    registrar.registerReferenceProvider(getElementPattern("dataProvider"), new PsiReferenceProvider() {
       @NotNull
       public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
         return new DataProviderReference[]{new DataProviderReference((PsiLiteralExpression)element)};
       }
     });
-    registrar.registerReferenceProvider(getElementPattern("groups"), new PsiReferenceProviderBase() {
+    registrar.registerReferenceProvider(getElementPattern("groups"), new PsiReferenceProvider() {
       @NotNull
       public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
         return new GroupReference[]{new GroupReference(element.getProject(), (PsiLiteralExpression)element)};
       }
     });
-    registrar.registerReferenceProvider(getElementPattern("dependsOnGroups"), new PsiReferenceProviderBase() {
+    registrar.registerReferenceProvider(getElementPattern("dependsOnGroups"), new PsiReferenceProvider() {
       @NotNull
       public PsiReference[] getReferencesByElement(@NotNull PsiElement element, @NotNull final ProcessingContext context) {
         return new GroupReference[]{new GroupReference(element.getProject(), (PsiLiteralExpression)element)};
diff --git a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGConfigurationEditor.java b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGConfigurationEditor.java
index 6c21e17..524d311 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGConfigurationEditor.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/configuration/TestNGConfigurationEditor.java
@@ -505,10 +505,6 @@
       }).disableUpDownActions().createPanel(), BorderLayout.CENTER);
   }
 
-  @Override
-  protected void disposeEditor() {
-  }
-
   public void onTypeChanged(TestType type) {
     //LOGGER.info("onTypeChanged with " + type);
     if (type != TestType.PACKAGE && type != TestType.SUITE) {
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/LightToolWindow.java b/plugins/ui-designer-core/src/com/intellij/designer/LightToolWindow.java
index 89019e0..a2a62f7 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/LightToolWindow.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/LightToolWindow.java
@@ -20,6 +20,7 @@
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.actionSystem.impl.ActionManagerImpl;
 import com.intellij.openapi.actionSystem.impl.MenuItemPresentationFactory;
+import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.ThreeComponentsSplitter;
 import com.intellij.openapi.util.SystemInfo;
@@ -479,7 +480,7 @@
       myAction = action;
 
       Presentation presentation = action.getTemplatePresentation();
-      InplaceButton button = new InplaceButton(AnAction.createTooltipText(presentation.getText(), action), EmptyIcon.ICON_16, this) {
+      InplaceButton button = new InplaceButton(KeymapUtil.createTooltipText(presentation.getText(), action), EmptyIcon.ICON_16, this) {
         @Override
         public boolean isActive() {
           return LightToolWindow.this.isActive();
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/componentTree/ComponentTree.java b/plugins/ui-designer-core/src/com/intellij/designer/componentTree/ComponentTree.java
index 79f935c..f7735c5 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/componentTree/ComponentTree.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/componentTree/ComponentTree.java
@@ -17,7 +17,6 @@
 
 import com.intellij.codeHighlighting.HighlightDisplayLevel;
 import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
 import com.intellij.designer.actions.DesignerActionPanel;
 import com.intellij.designer.actions.StartInplaceEditing;
 import com.intellij.designer.designSurface.DesignerEditorPanel;
@@ -159,7 +158,7 @@
   @Nullable
   private static HighlightDisplayLevel getHighlightDisplayLevel(Project project, RadComponent component) {
     HighlightDisplayLevel displayLevel = null;
-    SeverityRegistrar severityRegistrar = SeverityUtil.getSeverityRegistrar(project);
+    SeverityRegistrar severityRegistrar = SeverityRegistrar.getSeverityRegistrar(project);
     for (ErrorInfo errorInfo : RadComponent.getError(component)) {
       if (displayLevel == null || severityRegistrar.compare(errorInfo.getLevel().getSeverity(), displayLevel.getSeverity()) > 0) {
         displayLevel = errorInfo.getLevel();
@@ -174,7 +173,7 @@
 
     if (level != null) {
       TextAttributesKey attributesKey =
-        SeverityUtil.getSeverityRegistrar(myDesigner.getProject()).getHighlightInfoTypeBySeverity(level.getSeverity()).getAttributesKey();
+        SeverityRegistrar.getSeverityRegistrar(myDesigner.getProject()).getHighlightInfoTypeBySeverity(level.getSeverity()).getAttributesKey();
       final TextAttributes textAttributes = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(attributesKey);
 
       wrapper = new AttributeWrapper() {
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/componentTree/TreeEditableArea.java b/plugins/ui-designer-core/src/com/intellij/designer/componentTree/TreeEditableArea.java
index 31357b0..bce7b2f 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/componentTree/TreeEditableArea.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/componentTree/TreeEditableArea.java
@@ -31,6 +31,7 @@
 import javax.swing.event.EventListenerList;
 import javax.swing.event.TreeSelectionEvent;
 import javax.swing.event.TreeSelectionListener;
+import javax.swing.tree.DefaultMutableTreeNode;
 import javax.swing.tree.TreePath;
 import java.awt.*;
 import java.util.ArrayList;
@@ -274,7 +275,8 @@
 
   private TreePath getPath(RadComponent component) {
     // TODO: I don't know better way gets tree path for element
-    return new TreePath(myTreeBuilder.getNodeForElement(component).getPath());
+    DefaultMutableTreeNode node = myTreeBuilder.getNodeForElement(component);
+    return node == null ? null : new TreePath(node.getPath());
   }
 
   @Override
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/RadPropertyTable.java b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/RadPropertyTable.java
index f9975f9..0fe7d64 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/RadPropertyTable.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/RadPropertyTable.java
@@ -15,7 +15,7 @@
  */
 package com.intellij.designer.propertyTable;
 
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.designer.DesignerBundle;
 import com.intellij.designer.designSurface.ComponentSelectionListener;
 import com.intellij.designer.designSurface.DesignerEditorPanel;
@@ -104,7 +104,7 @@
 
   @NotNull
   protected TextAttributesKey getErrorAttributes(@NotNull HighlightSeverity severity) {
-    return SeverityUtil.getSeverityRegistrar(myProject).getHighlightInfoTypeBySeverity(severity).getAttributesKey();
+    return SeverityRegistrar.getSeverityRegistrar(myProject).getHighlightInfoTypeBySeverity(severity).getAttributesKey();
   }
 
   //////////////////////////////////////////////////////////////////////////////////////////
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/ErrorAnalyzer.java b/plugins/ui-designer/src/com/intellij/uiDesigner/ErrorAnalyzer.java
index c6c9681..8d38863 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/ErrorAnalyzer.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/ErrorAnalyzer.java
@@ -16,7 +16,7 @@
 package com.intellij.uiDesigner;
 
 import com.intellij.codeHighlighting.HighlightDisplayLevel;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.module.Module;
@@ -392,7 +392,7 @@
   public static HighlightDisplayLevel getHighlightDisplayLevel(final Project project, @NotNull final RadComponent component) {
     HighlightDisplayLevel displayLevel = null;
     for(ErrorInfo errInfo: getAllErrorsForComponent(component)) {
-      if (displayLevel == null || SeverityUtil.getSeverityRegistrar(project).compare(errInfo.getHighlightDisplayLevel().getSeverity(), displayLevel.getSeverity()) > 0) {
+      if (displayLevel == null || SeverityRegistrar.getSeverityRegistrar(project).compare(errInfo.getHighlightDisplayLevel().getSeverity(), displayLevel.getSeverity()) > 0) {
         displayLevel = errInfo.getHighlightDisplayLevel();
       }
     }
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTree.java b/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTree.java
index 0889ca17..a2f50bb 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTree.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/componentTree/ComponentTree.java
@@ -16,7 +16,7 @@
 package com.intellij.uiDesigner.componentTree;
 
 import com.intellij.codeHighlighting.HighlightDisplayLevel;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.icons.AllIcons;
 import com.intellij.ide.DeleteProvider;
 import com.intellij.ide.highlighter.JavaHighlightingColors;
@@ -328,7 +328,7 @@
 
     SimpleTextAttributes result = highlightMap.get(attrs);
     if (result == null) {
-      final TextAttributesKey attrKey = SeverityUtil.getSeverityRegistrar(myProject).getHighlightInfoTypeBySeverity(level.getSeverity()).getAttributesKey();
+      final TextAttributesKey attrKey = SeverityRegistrar.getSeverityRegistrar(myProject).getHighlightInfoTypeBySeverity(level.getSeverity()).getAttributesKey();
       TextAttributes textAttrs = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(attrKey);
       textAttrs = TextAttributes.merge(attrs.toTextAttributes(), textAttrs);
       result = SimpleTextAttributes.fromTextAttributes(textAttrs);
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java
index 22d95ba..a711578 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/propertyInspector/PropertyInspectorTable.java
@@ -15,7 +15,7 @@
  */
 package com.intellij.uiDesigner.propertyInspector;
 
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.icons.AllIcons;
 import com.intellij.ide.ui.LafManager;
 import com.intellij.ide.ui.LafManagerListener;
@@ -1131,7 +1131,7 @@
         Map<HighlightSeverity, SimpleTextAttributes> cache = modified ? myModifiedHighlightAttributes : myHighlightAttributes;
         result = cache.get(severity);
         if (result == null) {
-          final TextAttributesKey attrKey = SeverityUtil.getSeverityRegistrar(myProject).getHighlightInfoTypeBySeverity(severity).getAttributesKey();
+          final TextAttributesKey attrKey = SeverityRegistrar.getSeverityRegistrar(myProject).getHighlightInfoTypeBySeverity(severity).getAttributesKey();
           TextAttributes textAttrs = EditorColorsManager.getInstance().getGlobalScheme().getAttributes(attrKey);
           if (modified) {
             textAttrs = textAttrs.clone();
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/RadContainer.java b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/RadContainer.java
index 663dfc3..78e386c 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/RadContainer.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/radComponents/RadContainer.java
@@ -680,7 +680,7 @@
 
   public RadAbstractGridLayoutManager getGridLayoutManager() {
     if (!(myLayoutManager instanceof RadAbstractGridLayoutManager)) {
-      throw new RuntimeException("Not a grid container");
+      throw new RuntimeException("Not a grid container: " + myLayoutManager);
     }
     return (RadAbstractGridLayoutManager)myLayoutManager;
   }
diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPathStringLiteralSelectioner.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPathStringLiteralSelectioner.java
index bb72186..a90237b 100644
--- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPathStringLiteralSelectioner.java
+++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/XPathStringLiteralSelectioner.java
@@ -15,7 +15,7 @@
  */
 package org.intellij.lang.xpath;
 
-import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandler;
+import com.intellij.codeInsight.editorActions.ExtendWordSelectionHandlerBase;
 import com.intellij.lang.ASTNode;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.TextRange;
@@ -30,7 +30,7 @@
  * Date: 08.10.2009
  * Time: 21:06:04
  */
-public class XPathStringLiteralSelectioner implements ExtendWordSelectionHandler {
+public class XPathStringLiteralSelectioner extends ExtendWordSelectionHandlerBase {
   public boolean canSelect(PsiElement e) {
     ASTNode astNode = e.getNode();
     return astNode != null &&
diff --git a/resources-en/src/messages/DebuggerBundle.properties b/resources-en/src/messages/DebuggerBundle.properties
index 0d8d276..11189d3 100644
--- a/resources-en/src/messages/DebuggerBundle.properties
+++ b/resources-en/src/messages/DebuggerBundle.properties
@@ -424,7 +424,7 @@
 label.breakpoint.properties.panel.group.suspend.policy=Suspend policy
 active.tooltip.title=Evaluation of {0}
 active.tooltip.suggestion=Click here to view object tree
-error.text.invalid.port.0=Invalid port: ''{0,number,#}''
+error.text.invalid.port=Port is not specified
 error.cannot.invoke.method.in.collected.thread=Cannot invoke method: the invocation thread has been collected
 title.smart.step.popup=Method to Step Into
 action.show.watches.description=Shows or hides 'watches' pane
diff --git a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java
index 4842c4c..9a40ed5 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsErrorPanel.java
@@ -17,7 +17,6 @@
 package com.intellij.util.xml.highlighting;
 
 import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
 import com.intellij.codeInsight.daemon.impl.TrafficLightRenderer;
 import com.intellij.icons.AllIcons;
 import com.intellij.lang.annotation.HighlightSeverity;
@@ -171,7 +170,7 @@
         int sum = 0;
         for (DomElement element : myDomElements) {
           final DomElementsProblemsHolder holder = myAnnotationsManager.getCachedProblemHolder(element);
-          sum += (SeverityUtil.getSeverityRegistrar(getProject()).compare(minSeverity, HighlightSeverity.WARNING) >= 0 ? holder
+          sum += (SeverityRegistrar.getSeverityRegistrar(getProject()).compare(minSeverity, HighlightSeverity.WARNING) >= 0 ? holder
             .getProblems(element, true, true) : holder.getProblems(element, true, minSeverity)).size();
         }
         status.errorCount[i] = sum;
diff --git a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java
index 840a75a..a9f70bc 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/highlighting/DomElementsProblemsHolderImpl.java
@@ -16,7 +16,7 @@
 
 package com.intellij.util.xml.highlighting;
 
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.SeverityRegistrar;
 import com.intellij.lang.annotation.Annotation;
 import com.intellij.lang.annotation.HighlightSeverity;
 import com.intellij.openapi.util.Condition;
@@ -129,7 +129,7 @@
   public List<DomElementProblemDescriptor> getProblems(final DomElement domElement, final boolean withChildren, final HighlightSeverity minSeverity) {
     return ContainerUtil.findAll(getProblems(domElement, true, withChildren), new Condition<DomElementProblemDescriptor>() {
       public boolean value(final DomElementProblemDescriptor object) {
-        return SeverityUtil.getSeverityRegistrar(domElement.getManager().getProject()).compare(object.getHighlightSeverity(), minSeverity) >= 0;
+        return SeverityRegistrar.getSeverityRegistrar(domElement.getManager().getProject()).compare(object.getHighlightSeverity(), minSeverity) >= 0;
       }
     });
 
diff --git a/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java b/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java
index c15924c..0794955 100644
--- a/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java
+++ b/xml/dom-openapi/src/com/intellij/util/xml/converters/DelimitedListConverter.java
@@ -25,6 +25,7 @@
 import com.intellij.codeInsight.daemon.EmptyResolveMessageProvider;
 import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.util.text.DelimitedListProcessor;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiReference;
diff --git a/xml/dom-tests/tests/com/intellij/util/xml/DelimitedListProcessorTest.java b/xml/dom-tests/tests/com/intellij/util/xml/DelimitedListProcessorTest.java
index a206e43..0dd231e 100644
--- a/xml/dom-tests/tests/com/intellij/util/xml/DelimitedListProcessorTest.java
+++ b/xml/dom-tests/tests/com/intellij/util/xml/DelimitedListProcessorTest.java
@@ -1,6 +1,6 @@
 package com.intellij.util.xml;
 
-import com.intellij.util.xml.converters.DelimitedListProcessor;
+import com.intellij.openapi.util.text.DelimitedListProcessor;
 import junit.framework.TestCase;
 
 import java.util.ArrayList;
diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlErrorQuickFixProvider.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlErrorQuickFixProvider.java
index 828e654..5e23d82 100644
--- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlErrorQuickFixProvider.java
+++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlErrorQuickFixProvider.java
@@ -32,7 +32,7 @@
 public class XmlErrorQuickFixProvider implements ErrorQuickFixProvider {
   @NonNls private static final String AMP_ENTITY = "&amp;";
 
-  public void registerErrorQuickFix(final PsiErrorElement element, final HighlightInfo highlightInfo) {
+  public void registerErrorQuickFix(@NotNull final PsiErrorElement element, @NotNull final HighlightInfo highlightInfo) {
     if (PsiTreeUtil.getParentOfType(element, XmlTag.class) != null) {
       registerXmlErrorQuickFix(element,highlightInfo);
     }
diff --git a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
index 2404f75..624e0c0 100644
--- a/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
+++ b/xml/impl/src/com/intellij/codeInsight/daemon/impl/analysis/XmlHighlightVisitor.java
@@ -17,10 +17,7 @@
 
 import com.intellij.BundleBase;
 import com.intellij.codeInsight.daemon.*;
-import com.intellij.codeInsight.daemon.impl.HighlightInfo;
-import com.intellij.codeInsight.daemon.impl.HighlightInfoType;
-import com.intellij.codeInsight.daemon.impl.HighlightVisitor;
-import com.intellij.codeInsight.daemon.impl.SeverityUtil;
+import com.intellij.codeInsight.daemon.impl.*;
 import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixAction;
 import com.intellij.codeInsight.daemon.impl.quickfix.QuickFixActionRegistrarImpl;
 import com.intellij.codeInsight.intention.IntentionAction;
@@ -361,7 +358,7 @@
         localizedMessage,
         isInjectedHtmlTagForWhichNoProblemsReporting((HtmlTag)tag) ?
           HighlightInfoType.INFORMATION :
-          SeverityUtil.getSeverityRegistrar(tag.getProject()).getHighlightInfoTypeBySeverity(profile.getErrorLevel(key, tag).getSeverity()),
+          SeverityRegistrar.getSeverityRegistrar(tag.getProject()).getHighlightInfoTypeBySeverity(profile.getErrorLevel(key, tag).getSeverity()),
         addAttributeFix,
         basicIntention);
     } else if (!htmlTag) {
@@ -690,7 +687,7 @@
         addElementsForTag((XmlTag)context, message, infoType, null);
       }
       else {
-        addToResults(HighlightInfo.newHighlightInfo(HighlightInfoType.WRONG_REF).range(context).descriptionAndTooltip(message).create());
+        addToResults(HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(context).descriptionAndTooltip(message).create());
       }
     }
   }
diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/DtdSelectioner.java b/xml/impl/src/com/intellij/codeInsight/editorActions/DtdSelectioner.java
index 9f884a8..b394bf9 100644
--- a/xml/impl/src/com/intellij/codeInsight/editorActions/DtdSelectioner.java
+++ b/xml/impl/src/com/intellij/codeInsight/editorActions/DtdSelectioner.java
@@ -15,18 +15,18 @@
  */
 package com.intellij.codeInsight.editorActions;
 
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.xml.XmlAttlistDecl;
 import com.intellij.psi.xml.XmlElementDecl;
 import com.intellij.psi.xml.XmlToken;
 import com.intellij.psi.xml.XmlTokenType;
-import com.intellij.openapi.util.TextRange;
-import com.intellij.openapi.editor.Editor;
 
-import java.util.List;
 import java.util.ArrayList;
+import java.util.List;
 
-public class DtdSelectioner implements ExtendWordSelectionHandler {
+public class DtdSelectioner extends ExtendWordSelectionHandlerBase {
   public boolean canSelect(PsiElement e) {
     return e instanceof XmlAttlistDecl || e instanceof XmlElementDecl;
   }
diff --git a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java
index 11677b3..71cba6f 100644
--- a/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java
+++ b/xml/impl/src/com/intellij/codeInsight/editorActions/XmlGtTypedHandler.java
@@ -47,7 +47,12 @@
 public class XmlGtTypedHandler extends TypedHandlerDelegate {
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.editorActions.TypedHandler");
 
-  public Result beforeCharTyped(final char c, final Project project, final Editor editor, final PsiFile editedFile, final FileType fileType) {
+  public Result beforeCharTyped(final char c, final Project project, Editor editor, PsiFile editedFile, final FileType fileType) {
+    final Editor injectedEditor = InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, editedFile);
+    if (editor != injectedEditor) {
+      editor = injectedEditor;
+      editedFile = PsiDocumentManager.getInstance(project).getPsiFile(injectedEditor.getDocument());
+    }
     final WebEditorOptions webEditorOptions = WebEditorOptions.getInstance();
     if (c == '>' && webEditorOptions != null && webEditorOptions.isAutomaticallyInsertClosingTag() && fileContainsXmlLanguage(editedFile)) {
       PsiDocumentManager.getInstance(project).commitAllDocuments();
@@ -66,13 +71,6 @@
           // <xml_code><caret><outer_element>
           elementAtCaret = element = provider.findElementAt(offset - 1, XMLLanguage.class);
         }
-        if (element == null && offset > 0) {
-          // seems like an injection in a template file
-          final PsiElement injectedElement = InjectedLanguageUtil.findInjectedElementNoCommit(file, offset);
-          if (injectedElement != null && injectedElement.getContainingFile() instanceof XmlFile) {
-            elementAtCaret = element = injectedElement;
-          }
-        }
         if (!(element instanceof PsiWhiteSpace)) {
           boolean nonAcceptableDelimiter = true;
 
diff --git a/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/IdReferenceProvider.java b/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/IdReferenceProvider.java
index f7dd52a..f8b1453 100644
--- a/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/IdReferenceProvider.java
+++ b/xml/impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/IdReferenceProvider.java
@@ -19,7 +19,6 @@
 import com.intellij.psi.PsiReference;
 import com.intellij.psi.PsiReferenceProvider;
 import com.intellij.psi.filters.ElementFilter;
-import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProviderBase;
 import com.intellij.psi.templateLanguages.OuterLanguageElement;
 import com.intellij.psi.xml.XmlAttribute;
 import com.intellij.psi.xml.XmlAttributeValue;
diff --git a/xml/impl/src/com/intellij/xml/util/XmlRefCountHolder.java b/xml/impl/src/com/intellij/xml/util/XmlRefCountHolder.java
index 0a43ad1..023e3a9 100644
--- a/xml/impl/src/com/intellij/xml/util/XmlRefCountHolder.java
+++ b/xml/impl/src/com/intellij/xml/util/XmlRefCountHolder.java
@@ -226,28 +226,28 @@
       if (descriptor == null) return;
 
       final XmlAttributeDescriptor attributeDescriptor = descriptor.getAttributeDescriptor(attribute);
-      if (attributeDescriptor == null) return;
-
-      if (attributeDescriptor.hasIdType()) {
-        updateMap(attribute, value, false);
-      }
-      else {
-        final PsiReference[] references = value.getReferences();
-        for (PsiReference r : references) {
-          if (r instanceof IdReferenceProvider.GlobalAttributeValueSelfReference /*&& !r.isSoft()*/) {
-            updateMap(attribute, value, r.isSoft());
-          }
-          else if (r instanceof SchemaPrefixReference) {
-            SchemaPrefix prefix = ((SchemaPrefixReference)r).resolve();
-            if (prefix != null) {
-              myHolder.addUsedPrefix(prefix.getName());
+      if (attributeDescriptor != null) {
+        if (attributeDescriptor.hasIdType()) {
+          updateMap(attribute, value, false);
+        }
+        else {
+          final PsiReference[] references = value.getReferences();
+          for (PsiReference r : references) {
+            if (r instanceof IdReferenceProvider.GlobalAttributeValueSelfReference /*&& !r.isSoft()*/) {
+              updateMap(attribute, value, r.isSoft());
+            }
+            else if (r instanceof SchemaPrefixReference) {
+              SchemaPrefix prefix = ((SchemaPrefixReference)r).resolve();
+              if (prefix != null) {
+                myHolder.addUsedPrefix(prefix.getName());
+              }
             }
           }
         }
-      }
 
-      if (attributeDescriptor.hasIdRefType() && PsiTreeUtil.getChildOfType(value, OuterLanguageElement.class) == null) {
-        myHolder.registerIdReference(value);
+        if (attributeDescriptor.hasIdRefType() && PsiTreeUtil.getChildOfType(value, OuterLanguageElement.class) == null) {
+          myHolder.registerIdReference(value);
+        }
       }
 
       String s = value.getValue();
diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/references/IdRefProvider.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/references/IdRefProvider.java
index af803b4..d3857c7 100644
--- a/xml/relaxng/src/org/intellij/plugins/relaxNG/references/IdRefProvider.java
+++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/references/IdRefProvider.java
@@ -23,7 +23,7 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiReference;
 import com.intellij.psi.PsiReferenceBase;
-import com.intellij.psi.impl.source.resolve.reference.PsiReferenceProviderBase;
+import com.intellij.psi.PsiReferenceProvider;
 import com.intellij.psi.impl.source.resolve.reference.impl.providers.AttributeValueSelfReference;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.xml.XmlAttribute;
@@ -40,7 +40,7 @@
 import static com.intellij.patterns.XmlPatterns.xmlAttribute;
 import static com.intellij.patterns.XmlPatterns.xmlAttributeValue;
 
-public class IdRefProvider extends PsiReferenceProviderBase {
+public class IdRefProvider extends PsiReferenceProvider {
   public static final HasIdRefTypeCondition HAS_ID_REF_TYPE = new HasIdRefTypeCondition();
   public static final HasIdTypeCondition HAS_ID_TYPE = new HasIdTypeCondition();
 
diff --git a/xml/tests/src/com/intellij/xml/XmlNamespacesTest.java b/xml/tests/src/com/intellij/xml/XmlNamespacesTest.java
index e457bdc1..5e0932b 100644
--- a/xml/tests/src/com/intellij/xml/XmlNamespacesTest.java
+++ b/xml/tests/src/com/intellij/xml/XmlNamespacesTest.java
@@ -216,6 +216,10 @@
     myFixture.checkResultByFile("spring_after.xml");
   }
 
+  public void testXsiType() throws Exception {
+    myFixture.testHighlighting("import.xml", "import.xsd");
+  }
+
   private void doUnusedDeclarationTest(String text, String after, String name) throws Exception {
     doUnusedDeclarationTest(text, after, name, true);
   }
diff --git a/xml/tests/testData/unusedNs/import.xml b/xml/tests/testData/unusedNs/import.xml
new file mode 100644
index 0000000..9468f0f
--- /dev/null
+++ b/xml/tests/testData/unusedNs/import.xml
@@ -0,0 +1,5 @@
+<A xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+   xmlns="myNamespace"
+   xmlns:c="myNamespace"
+   xsi:type="c:CType">
+</A>
\ No newline at end of file
diff --git a/xml/tests/testData/unusedNs/import.xsd b/xml/tests/testData/unusedNs/import.xsd
new file mode 100644
index 0000000..e40fae5
--- /dev/null
+++ b/xml/tests/testData/unusedNs/import.xsd
@@ -0,0 +1,6 @@
+<?xml version="1.0" encoding="utf-8"?>
+<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
+           version="eeee" blockDefault="#all" finalDefault="" targetNamespace="myNamespace">
+
+    <xsd:simpleType name="CType"></xsd:simpleType>
+</xsd:schema>
\ No newline at end of file
diff --git a/xml/tests/testData/xml/ComplexSchemaValidation12.xsd b/xml/tests/testData/xml/ComplexSchemaValidation12.xsd
index 345e223..9bfe5ce 100644
--- a/xml/tests/testData/xml/ComplexSchemaValidation12.xsd
+++ b/xml/tests/testData/xml/ComplexSchemaValidation12.xsd
@@ -7,7 +7,7 @@
 	<xs:complexType>
 	    <xs:sequence>
                 <!--Type is not allowed with ref-->
-                <xs:element ref="TestElement" <error>type="xs:string"</error>/>
+                <xs:element ref="TestElement" <error descr="Attribute type is not allowed here when element reference is used">type</error>="xs:string"/>
 	    </xs:sequence>
 	</xs:complexType>
     </xs:element>
diff --git a/xml/tests/testData/xml/DefaultAndFixedInSchema.xsd b/xml/tests/testData/xml/DefaultAndFixedInSchema.xsd
index 263864e..5128190 100644
--- a/xml/tests/testData/xml/DefaultAndFixedInSchema.xsd
+++ b/xml/tests/testData/xml/DefaultAndFixedInSchema.xsd
@@ -2,9 +2,9 @@
             xmlns:xsd="http://www.w3.org/2001/XMLSchema"
             targetNamespace="http://www.foo.org/test"
             elementFormDefault="qualified" attributeFormDefault="unqualified">
-  <<error>xsd:element</error>>
+  <<error descr="Either 'name' or 'ref' attribute should present"><error descr="Element xsd:element doesn't have required attribute name">xsd:element</error></error>>
     <xsd:complexType>
-      <<error>xsd:attribute</error> <error>default="aaa"</error> <error>fixed="bbb"</error> />
+      <<error descr="Either 'name' or 'ref' attribute should present">xsd:attribute</error> <error descr="'default' and 'fixed' attributes should not be present in the same time">default</error>="aaa" <error descr="'default' and 'fixed' attributes should not be present in the same time">fixed</error>="bbb" />
     </xsd:complexType>
-  </<error>xsd:element</error>>
+  </<error descr="Either 'name' or 'ref' attribute should present"><error descr="Element xsd:element doesn't have required attribute name">xsd:element</error></error>>
 </xsd:schema>
\ No newline at end of file
diff --git a/xml/xml-psi-api/src/com/intellij/psi/xml/XmlAttribute.java b/xml/xml-psi-api/src/com/intellij/psi/xml/XmlAttribute.java
index 73fc2cd..fb2a1be 100644
--- a/xml/xml-psi-api/src/com/intellij/psi/xml/XmlAttribute.java
+++ b/xml/xml-psi-api/src/com/intellij/psi/xml/XmlAttribute.java
@@ -34,6 +34,8 @@
 
   @NonNls @NotNull String getLocalName();
 
+  XmlElement getNameElement();
+
   @NonNls @NotNull String getNamespace();
 
   @NonNls @NotNull String getNamespacePrefix();
diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlAttributeImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlAttributeImpl.java
index 8923767..c3afa3f 100644
--- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlAttributeImpl.java
+++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlAttributeImpl.java
@@ -107,6 +107,7 @@
     });
   }
 
+  @Override
   public XmlElement getNameElement() {
     return (XmlElement)XmlChildRole.ATTRIBUTE_NAME_FINDER.findChild(this);
   }
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/SchemaNSDescriptor.java b/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/SchemaNSDescriptor.java
index e5d7a19..8601554 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/SchemaNSDescriptor.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/SchemaNSDescriptor.java
@@ -56,7 +56,7 @@
               !ID_ATTR_NAME.equals(name) &&
               !REF_ATTR_NAME.equals(name)) {
             host.addMessage(
-              attr,
+              attr.getNameElement(),
               XmlErrorMessages.message("xml.schema.validation.attr.not.allowed.with.ref", name),
               ValidationHost.ERROR
             );
@@ -108,13 +108,13 @@
 
       if (tag.getAttributeValue(DEFAULT_ATTR_NAME) != null && tag.getAttributeValue(FIXED_ATTR_NAME) != null) {
         host.addMessage(
-          tag.getAttribute(DEFAULT_ATTR_NAME, null),
+          tag.getAttribute(DEFAULT_ATTR_NAME, null).getNameElement(),
           XmlErrorMessages.message("xml.schema.validation.default.or.fixed.should.be.specified.but.not.both"),
           Validator.ValidationHost.ERROR
         );
 
         host.addMessage(
-          tag.getAttribute(FIXED_ATTR_NAME, null),
+          tag.getAttribute(FIXED_ATTR_NAME, null).getNameElement(),
           XmlErrorMessages.message("xml.schema.validation.default.or.fixed.should.be.specified.but.not.both"),
           Validator.ValidationHost.ERROR
         );
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/util/IncludedXmlAttribute.java b/xml/xml-psi-impl/src/com/intellij/xml/util/IncludedXmlAttribute.java
index 988b7d0..2aecdc7 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/util/IncludedXmlAttribute.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/util/IncludedXmlAttribute.java
@@ -19,6 +19,7 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.xml.XmlAttribute;
 import com.intellij.psi.xml.XmlAttributeValue;
+import com.intellij.psi.xml.XmlElement;
 import com.intellij.psi.xml.XmlTag;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.xml.XmlAttributeDescriptor;
@@ -53,6 +54,11 @@
     return getOriginal().getLocalName();
   }
 
+  @Override
+  public XmlElement getNameElement() {
+    return getOriginal().getNameElement();
+  }
+
   @NonNls
   @NotNull
   public String getNamespace() {