Snapshot idea/136.1761 from git://git.jetbrains.org/idea/community.git

3608216: Merge remote-tracking branch 'origin/master'
0d16248: Django inspection HTMLs moved to appropriate place
1ed8715: PY-1194 Provide completion and navigation for url tag in django template Inspection added.
4c6ec52: Naive fix for EA-53569
44c2a03: Do not wrap border with TitledBorder if there is not title
8591130: omg2 [r=ignatov]
dce57e7: omg
3b164b9: Merge remote-tracking branch 'origin/master'
9c04fe7: Ctrl-Q: process java 8 signature style as 1.8 javadoc could also be run on sources 1.6 (IDEA-124175)
b073132: javadoc: ensure that generic arguments are shown in error presentation
b8fb550: IDEA-124271
209d176: disable stream api conversion on iterable (IDEA-124222)
6ca89eb: default external javadoc url for java 8 fixed (IDEA-124175)
2fe28f0: Merge remote-tracking branch 'origin/master'
f65712c: Merge remote-tracking branch 'origin/master'
7de60e2f: Don't escape spaces as it brakes mappings and they are escaped later in GeneralCommandLine (PY-12550).
2bd67bc: IDEA-90194 Ability to disable drag & drop in Project View
f772fb2: Merge remote-tracking branch 'origin/master'
817908d: fixed importing for the iron python
053b716: Merge remote-tracking branch 'origin/master'
1d04dc7: fixed unittest folder tests
76f35f3: suppress doCancelAction
0d9b47d: IDEA-124260 Data Sources and Drivers: can't apply changes to schemas that are shown and used to resolve
f72e4f5: testdata for IDEA-124148
1c431a8: create meth reference from usage: substitute param types (IDEA-124322)
c160fc5: copy to temp/array for non-effectively final variables used in lambda expressions
265f0dc: lambda -> anonymous: static calls (IDEA-124187)
2200bba: method hierarchy: search functional expressions by current method only (IDEA-124320); navigation (IDEA-124319)
54ced00: highlight all pairs of methods with same erasures (IDEA-124116)
f3efd90: IDEA-120865 jre7 osx fullscreen: "space" is not freed when project is closed
6924cc4: IDEA-118062 Gradle Run Configuration: 'working directory' is set incorrectly
09333b1: External system: source package prefix support added; fix for out-of-process mode support
6de52dc: Gradle: update Tooling API version up to 1.12-rc-1, fix classpath for out-of-process mode
4ff20d5: InconsistentResourceBundle test fixed
90bb5ab: IDEA-124301 jdk9 builds cannot be used for project/module compilation
1236318: always go to file if nothing found
43f40bf: Merge remote-tracking branch 'origin/master'
b2d0942: Add default mapping to /vagrant only in case of absent mappings in Vagrantfile (PY-12700).
fc31680: IDEA-124290
773f103: Offer to launch Vagrant if it is down on getting ssh-config (PY-12672).
460ef41: DumbService.smartInvokeLater(...)
577579d: cleanup after extracting java postfix template provider
214f99b: IDEA-103836
a41e7d8: Merge remote-tracking branch 'origin/master'
4076596: fixed memory leak
c5207b2: fixed PY-12543 Project Interpreters: too big or too small details popup
40d91f5: IDEA-63106 new inspections added to InconsistentResourceBundleInspection
4bc9f42: fixed PY-12690 Detected from creating virtualenv interpreter has invalid slashes
e6d8c98: extract right arrow
43b861b: don't use borders and insets in output html/rtf (IDEA-67767)
6c4dbea: use service instead of application component (IDEA-67767)
aa6fb9f: remove 'Strip common indent' setting from UI (IDEA-67767)
5651ab5: IDEA-123775 (String.equals("") inspection fixes code incorrectly)
c1d9f5f: fixed PY-12696 Create VirtualEnv: when adding first base interpreter it is not selected right away
482491a: Platform: Local History can survive for more than 30 days now (int overflow fixed)
a0125dc: Platform: always allow writing module files (IDEA-123899)
3a294e9: removed unused component methods
7cc124e: optimisation: avoid containingfile calculation
06f574a: readable toString()
60f2a36: perforce tests fixed
46fea0f: fewer create/delete operations
7269bce: drain file type detection queue in tests
d0c6ef5: cleanup
9df7136: Gradle: installer build fix
152c230: Platform: Local History can survive for more than 30 days now
f5e7215: do not rely on memory index storage isBufferedFlag to process physical file contents
ebe62cf: customize password field labels
97ade8d: ability to enable only visible components
3541938: introduce beforeOKAction()
13bf7e1: cleanup
4a12b1f: junit: workaround for old junit versions (IDEA-124201)
21003e0: Merge remote-tracking branch 'origin/master'
c2067ff: PY-1194 Provide completion and navigation for url tag in django template PY-3591  Support {% url %} tag arguments completion
5f295fe: do not cancel offline inspections
2b8e2e8: add unchecked warning calls also for method references
57e886f: testdata: check that method ref on static interface method is accepted
8bad807: lambda: do not skip generic method when non-generic method exist in the same class
7d74b9d: NPE
0da9f91: testdata: ensure overload resolution prefer correct one from methods with boxed types
2c49817: NPE
d5107d6: testdata: ensure intersection type is not missed during inference
7898108: testdata: ensure lambda can't be inferred from type parameter
5b91054: testdata: ensure overload resolution by return type should not take place for interrupted control flow
9aa2f3a: testdata: ensure correct parameters number in functional interface method
1698f7b: testdata: ensure method ref qualified are checked over static problems
b49d8e75: testdata
f1f6fcf: functional interfaces: ignore methods with type parameters during abstract method choosing
a55db18: lambda: accept intersection type when exactly one conjunct is functional
4a34bd5: do not report unrelated return type error only for generics methods
76a9293: testdata
17b020f: new overload resolution: covariant comparison of return types
98ab76f: new overload resolution: most specific check on invalid class exceptions fixed
552dfe9: lambda: intersection type produces conjunction of abstract methods
bd9dbfc: testdata
9914757: warn about underscore identifier
72ae579: IDEA-109187  new HgReference validator implemented
d86307e: tip reference moved as a separated static constant to HgUtil
71cd276: Fix scrolling in module aware configurables [r=ushakov]
37ed33e: Missed commit for IDEA-79312
da52f84: IDEA-79312 text cursor gets lost - could bee disabled by focus.fix.lost.cursor key
a39b289: [git log] IDEA-122305 Fix structure filter.
339dd23: beforeShown() & preselect laf-default editor scheme 2
f9d8704: PY-1194 Provide completion and navigation for url tag in django template PY-3591  Support {% url %} tag arguments completion
17e8b30: ctrl+delete/ctrl+backspace enhancements IDEA-100906 Ruby-Editor: CTRL+BACKSPACE Could Not Delete A String
a95fd00: remove copyright messages
bf06d9d: read-action for getFilesForFastWordSearch
cdcd770: IDEA-123687 Velocity formatter inserts wrong linebreak
562443f: Fixed WI-17474 Custom Folding:  defaultstate="collapsed" does not seem to have any effect (the node itself is already a line comment)
d86998d: Cleanup warnings
4bbd22c: jb v8 debug protocol: evaluate
46eaf0b: NPE
4101b8c: cleanup
399e745: write action required
004dfc4: IDEA-124220 Auto-popup parameter info should work after smart completion which inserted a comma
0bd06e5: More on comparison that is always false due to being out of type range on implicit type conversion (IDEA-124210)
b6bccb7: AppCode: minimum OS X version specified in .app
ca8a657: add aliases for Lafs
e254ebf: Merge branch 'master' of git.labs.intellij.net:idea/community
5c594f6: Gradle: update Tooling API version up to 1.12-rc-1
17fcca3: Merge remote-tracking branch 'origin/master'
5248eb0: IDEA-119996 FilePathImpl: avoid VFS refresh from getVirtualFile etc.
9c69111: [vcs] Reuse the VirtualFile instead of creating FilePathImpl on File
c08f50b: fixed EA-54835 - NPE: PythonNoseTestConfigurationProducer.isAvailable
d627711: fixed EA-55749 - AIOOBE: PyStructuredDocstringFormatter.formatDocstring
c9a1c11: apply laf once, fix stale bg, add beforeShown() & preselect laf-default editor scheme
3e576c2: fixed EA-55872 - NPE: PyProtectedMemberInspection$Visitor.checkReference
147c647: use ValueType enum instead of plain numbers
2e517c5: IDEA-112050 vcs: fix ByteBuffer to array conversion
97a6a21: possible race condition fixed
cb20ef5: Prevent horizontal scrollbar appearance if an error message is too long
cbb86d4: IDEA-124021 Cannot resolve method 'print(int)' with JSP custom tags: comment
362b4d7: IDEA-123986 New project wizard: remove highlighting from disabled templates
cc57b39: do not include runtime dependencies to compilation scope (ZD-25927)
7ac3c11: paste rich-text data: NPE fixed
89ca157: Extract Java live postfix templates provider
e5eb7aa: EA-31437 - assert: DocumentFoldingInfo.writeExternal
e2461d5: use JBImageIcon
e9eb171: initial
ed33f35: fix Keymap page on Mac/Darcula. see same in LafManager for more info.
99bc2e9: open some API
d9aed3f: process class names just once in completion
094f040: IDEA-122362 'getClass()' should be suggested in smart completion if Class<? extends SomeAncestorOfCurrentClass> is expected
1a34573: IDEA-120139 Autopopup doesn't popup sometimes after completion
e8c981a: create LookupUi and move there some ui-related code from LookupImpl; skip this code in tests
89d771e: @NotNull
8d25ba3: Merge remote-tracking branch 'origin/master'
7fcce27: fix darcula lafinfo
bfef59e: Start plugins wizard #19 usability improvements
5cbd491: minor fix
58d2f15: fix bg
40fa260: don't create content entry for temp directory of temp project when opening single file
e31a4c1: Correctly handle custom folding "desc" attribute followed by "defaultstate"
448e9f8: don't report on incomplete code or comparisons that are already reported by "Constant conditions & exceptions"
6e68111: remove superfluous inspection
a2cc5ba: expand description
814378f: Gradle: gradle distribution pattern updated
e9485f0: use TransparentPanel
db66426: initial
a712571: suppress unused params inspection
640ddf3: make labels have constant height to avoid relayout and blinking
921f39e: don't fill bg if component is not opaque
a43d7f8: added new test for live postfix templates
50addd3: IDEA-123935 New Project wizard: no project/global libraries are created on new module adding via project structure
6021da6: Merge remote-tracking branch 'origin/master'
36848a5: fixed test data
7a63d2b: Gradle: tooling extensions integration tests, avoid dependency for explicit distributions downloading in a separate run configuration (like this one http://buildserver.labs.intellij.net/viewType.html?buildTypeId=IDEATrunk_GradleDownloads)
405332a: make richCopy functionality work properly on Linux (IDEA-67767)
3dca908: some 'finally' blocks
00a4968: reverted content-dependent flag
6064460: Merge remote-tracking branch 'origin/master'
5f203cb: Fixed IDEA-124191 Code style preference : space within empty method call/declaration parentheses are not saved
0419dcc: EA-56035 - NCDFE: UnixProcessManager.<clinit>
0285ece: cleanup: use ordinary invokeLater and avoid unnecessary synchronization
0922a97: Vagrant error messaging fixed.
2676330: Save vagrant executable path to application settings (PY-12680).
947d8ab: missing test data
6154126: IDEA-124137 (Inspection: "equals() between objects of inconvertible types" should support java.util.Objects.equals() or com.google.common.base.Objects.equal())
c9fd1bb: fix name
f3ec0f7: lookup arranger tweak [zolotov, shrago] relates to IDEA-121998 SQL code completion too aggressive
c324511: fix escaping, parse decimal literals #WEB-11938 fixed
a5bcae9: Github: fix error message
95d057d: Github: fix invalid condition
dda5341: Github: log invalid requests
d493d76: it is even better to store deltas for direct mapping values
a67ac0b: proper unpacking code
3ea5951: Properties AST factory moved to impl
c0550f7: save keys of particular snapshot before and out of index update optimistically load keys of particular snapshot before and out of index update
d6a5968: custom implementation for IdIndex inputs mapping: -20% for saving deltas
b52691e: saving / reading longs in compact variable byte format + using it for simplier code in PersistentHashMapValueStorage
0ae869e: cleanup
3222cd0: cleanup
e96aa7b: use Gray.TRANSPARENT
2861f10: use Gray.TRANSPARENT
c009821: Merge remote-tracking branch 'origin/master'
caa86fc: what a nice NPE!
3c769ac: goto popup calculations should be cancellable even after Ctrl+Space (IDEA-123714 ?)
c6fcabf: IDEA-122250 New Package: qualified name is checked against ignored directories as a whole
3af306c: IDEA-55556 Inspection suggestion: Comparison that is always false due to being out of type range on implicit type conversion
996d0c6: IDEA-123782 "Complete current statement" doesn't put colon for case branches
7a2cc54: IDEA-122383 PageUp/PageDown don't work in ShowUsages popup (Ctrl-Alt-F7)
29fec22: IDEA-123948 Constant condition and exceptions: false positive on MappedByteBuffer.getInt
0fd86de: IDEA-122946 final modifier not inserted when completing a sequence of parameters from an inner method IDEA-123493 Smart completion makes completed variable final
019a68b: IDEA-123289 Infer nullability of 'for each' variable from type annotations of the collection parameter
c18c4ff: IDEA-120964 Make it more obvious that background compiler is disabled in power save mode
dc2f64a: use superclass for inner class variable name suggestion (IDEA-122109)
c47713f: prefer T if Class<? extends T> is expected (IDEA-121339)
c960901: OC-9559 IDEA-107592
64fc873: cleanup
c159a1a: Start plugins wizard #17
043fa14: extra assert
7eac40c: larger btree block size / load factor increased for better space utilization
a4598a1: enable snapshot mapping
e80c2b3: trigram index enabled in internal mode
527f139: delta encoding of file id set to decrease output size ~3x
a47785b: move to MnemonicHelper
5b12f32: cleanup
27ef5f4: bg progresses for presentation mode
656e311: add transparent color
ddce960: EA-55788 - assert: GitRepositoryImpl
dfc2ef7: external-system: project import fixed to use correct fileToImport
675d14e: OC-9559 IDEA-107592
e6d5ea6: IDEA-86665 hg annotate: ignore whitespace changes
6e551ba: test hg executor updated with ignoreNonZeroExitCode addition option
8798162d: cleanup
45f98c5: IDEA-124021 Cannot resolve method 'print(int)' with JSP custom tags
67f1d44: Better fix for IDEA-124096 open commit actions popup on ctrl+alt+P
8aab4ce: IDEA-123691 Minor project wizard edits: moving settings to the first page
9cb1c40: IDEA-122845 Try to fetch issues, if resource with information about user is not available in this version of Redmine
a2c9393: Add key to JiraRepository to enable old behavior where credentials were sent with every request via basic auth
ce17994: Add special type of exception to indicate request failure from response handlers and other callbacks. ResponseHandler has option to suppress exceptions, if requested resource was not found.
de0f3df: notnull, toString
10c30e2: IDEA-123886, dropped UTF guessing setting
bf14e11: remove obsolete cruft
7b15687: notnull
c82fb9d: mem leak
de48566: test
8a9b3d0: doc leak
d163e52: comment
1274dba: removed confusing createTempPath()
057c5f9: do not expand usage tree if there are too many nodes
e7f245f: debugging IDEA-120167 Phantom eternal Ant task on make
6bf1671: Merge remote-tracking branch 'origin/master'
be70ee8: PY-2880: Django: provide completion for context_object_name value in django template * test added * fixture:complete() is reenterable now
1a99a14: Start plugins wizard #16 and it works
30f6e0e: fix false positive with smart tabs
76fcb91: use provided value description instead of just classname don't compute object presentation by custom configured properties if value description is not equals to class name
014c0e3: jb v8 debug protocol: load full string value
223f19a: typo
339e7d6: WEB-11834 IIS ACL Permissions when creating foundation/bootstrap projects from templates
b875e62: remove freemarker leftovers from html lexer #WEB-11907 fixed
b84c236: push language levels synchronously for non-refresh vfs events (IDEA-123876)
a32e2eb: code style
a593533: Github: mark invalid password as invalid
10d5070: [git] IDEA-124081 implement IDEA-98189 for clone
a9fa3a2: IDEA-124096 open commit actions popup on ctrl+alt+P
83bc60b: AppCode: Xcode keymap tunes for tool windows  +review CR-IC-5162
c976200: Merge remote-tracking branch 'origin/master'
48d5f8c: Refactoring: getImportSourceQName() is used
d324bc0: GeneratedFolder icon
5d90886: Add "try-with-resources" live postfix template
cfec5b0: cleanup
e587000: Platform: bug-typo in DnDSupport
814a79a: Unify prefix calculation rules for live templates
f447531: IDEA-124005 Reading resources out of a source directory doesn't make it a resource directory

Change-Id: Ie2989b1157ae12b92c48d9556db64999ea68e83e
diff --git a/.idea/modules.xml b/.idea/modules.xml
index 6e07e20..1e44e12 100644
--- a/.idea/modules.xml
+++ b/.idea/modules.xml
@@ -61,10 +61,8 @@
       <module fileurl="file://$PROJECT_DIR$/plugins/google-app-engine/google-app-engine.iml" filepath="$PROJECT_DIR$/plugins/google-app-engine/google-app-engine.iml" group="plugins/GAE" />
       <module fileurl="file://$PROJECT_DIR$/plugins/google-app-engine/jps-plugin/google-app-engine-jps-plugin.iml" filepath="$PROJECT_DIR$/plugins/google-app-engine/jps-plugin/google-app-engine-jps-plugin.iml" group="plugins/GAE" />
       <module fileurl="file://$PROJECT_DIR$/plugins/gradle/gradle.iml" filepath="$PROJECT_DIR$/plugins/gradle/gradle.iml" group="community/plugins/gradle" />
-      <module fileurl="file://$PROJECT_DIR$/plugins/gradle/tooling-extension/gradle-tooling-extension.iml" filepath="$PROJECT_DIR$/plugins/gradle/tooling-extension/gradle-tooling-extension.iml" group="community/plugins/gradle" />
-      <module fileurl="file://$PROJECT_DIR$/plugins/gradle/tooling-extension-v1.11/gradle-tooling-extension-v1.11.iml" filepath="$PROJECT_DIR$/plugins/gradle/tooling-extension-v1.11/gradle-tooling-extension-v1.11.iml" group="community/plugins/gradle" />
-      <module fileurl="file://$PROJECT_DIR$/plugins/gradle/tooling-extension-v1.12/gradle-tooling-extension-v1.12.iml" filepath="$PROJECT_DIR$/plugins/gradle/tooling-extension-v1.12/gradle-tooling-extension-v1.12.iml" group="community/plugins/gradle" />
-      <module fileurl="file://$PROJECT_DIR$/plugins/gradle/tooling-extension-v1.9/gradle-tooling-extension-v1.9.iml" filepath="$PROJECT_DIR$/plugins/gradle/tooling-extension-v1.9/gradle-tooling-extension-v1.9.iml" group="community/plugins/gradle" />
+      <module fileurl="file://$PROJECT_DIR$/plugins/gradle/tooling-extension-api/gradle-tooling-extension-api.iml" filepath="$PROJECT_DIR$/plugins/gradle/tooling-extension-api/gradle-tooling-extension-api.iml" group="community/plugins/gradle" />
+      <module fileurl="file://$PROJECT_DIR$/plugins/gradle/tooling-extension-impl/gradle-tooling-extension-impl.iml" filepath="$PROJECT_DIR$/plugins/gradle/tooling-extension-impl/gradle-tooling-extension-impl.iml" group="community/plugins/gradle" />
       <module fileurl="file://$PROJECT_DIR$/plugins/groovy/jps-plugin/groovy-jps-plugin.iml" filepath="$PROJECT_DIR$/plugins/groovy/jps-plugin/groovy-jps-plugin.iml" group="plugins/Groovy" />
       <module fileurl="file://$PROJECT_DIR$/plugins/groovy/rt-constants/groovy-rt-constants.iml" filepath="$PROJECT_DIR$/plugins/groovy/rt-constants/groovy-rt-constants.iml" group="plugins/Groovy" />
       <module fileurl="file://$PROJECT_DIR$/plugins/groovy/rt/groovy_rt.iml" filepath="$PROJECT_DIR$/plugins/groovy/rt/groovy_rt.iml" group="plugins/Groovy" />
diff --git a/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpCharImpl.java b/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpCharImpl.java
index 5ebee1d..9594a37 100644
--- a/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpCharImpl.java
+++ b/RegExpSupport/src/org/intellij/lang/regexp/psi/impl/RegExpCharImpl.java
@@ -72,6 +72,14 @@
           catch (NumberFormatException e) {
             // do nothing
           }
+        } else {
+          char nextChar = s.charAt(1);
+          if (Character.isDigit(nextChar) && nextChar != '0') {
+            Character character = parseNumber(0, s, 10, s.length() - 1, true);
+            if (character != null) {
+              return character;
+            }
+          }
         }
       }
       return unescapeChar(s);
diff --git a/build/conf/mac/Contents/Info.plist b/build/conf/mac/Contents/Info.plist
index d7a1a70..0345101 100644
--- a/build/conf/mac/Contents/Info.plist
+++ b/build/conf/mac/Contents/Info.plist
@@ -57,7 +57,11 @@
     @@archs@@
     <key>LSRequiresNativeExecution</key>
     <string>YES</string>
+    <key>LSMinimumSystemVersion</key>
+    <string>@@min_osx@@</string>
+
     @@url_schemes@@
+
     <key>JVMOptions</key>
     <dict>
       <key>ClassPath</key>
diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant
index 9e1e134..9f0485e 100644
--- a/build/scripts/layouts.gant
+++ b/build/scripts/layouts.gant
@@ -336,14 +336,13 @@
       jar("gradle.jar") {
         module("gradle")
       }
-      jar("gradle-tooling-extension.jar") {
-        module("gradle-tooling-extension")
+
+      jar("gradle-tooling-extension-api.jar") {
+        module("gradle-tooling-extension-api")
       }
-      def gradleToolingVersions = ["1.9", "1.11", "1.12"]
-      gradleToolingVersions.each { ver ->
-        jar("gradle-tooling-extension-v" + ver + ".jar") {
-          module("gradle-tooling-extension-v" + ver)
-        }
+
+      jar("gradle-tooling-extension-impl.jar") {
+        module("gradle-tooling-extension-impl")
       }
       fileset(dir: "$home/plugins/gradle/lib") { include(name: "*.jar") }
     }
diff --git a/build/scripts/utils.gant b/build/scripts/utils.gant
index 9bbe94e..8ae9cfe 100644
--- a/build/scripts/utils.gant
+++ b/build/scripts/utils.gant
@@ -403,6 +403,7 @@
     replacefilter(token: "@@help_id@@", value: helpId)
     replacefilter(token: "@@url_schemes@@", value: urlSchemes)
     replacefilter(token: "@@archs@@", value: archs)
+    replacefilter(token: "@@min_osx@@", value: ifNull(args.min_osx, "10.6"))
   }
 
   if (executable != "idea") {
diff --git a/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java b/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java
index 22ab2a7..b33256d 100644
--- a/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java
+++ b/java/compiler/forms-compiler/src/com/intellij/uiDesigner/compiler/AsmCodeGenerator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -852,20 +852,20 @@
         else {
           generator.push((String) null);
         }
-        pushBorderProperties(container, generator, borderTitle, componentLocal);
 
-
-        Type borderFactoryType = ourBorderFactoryType;
-        StringDescriptor borderFactoryValue = (StringDescriptor)container.getDelegeeClientProperties().get(ourBorderFactoryClientProperty);
-        if (borderFactoryValue == null && borderTitle != null && Boolean.valueOf(System.getProperty("idea.is.internal")).booleanValue()) {
-          borderFactoryValue = StringDescriptor.create("com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent");
-          container.getDelegeeClientProperties().put(ourBorderFactoryClientProperty, borderFactoryValue);
+        if (borderTitle != null) {
+          pushBorderProperties(container, generator, borderTitle, componentLocal);
+          Type borderFactoryType = ourBorderFactoryType;
+          StringDescriptor borderFactoryValue = (StringDescriptor)container.getDelegeeClientProperties().get(ourBorderFactoryClientProperty);
+          if (borderFactoryValue == null && Boolean.valueOf(System.getProperty("idea.is.internal")).booleanValue()) {
+            borderFactoryValue = StringDescriptor.create("com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent");
+            container.getDelegeeClientProperties().put(ourBorderFactoryClientProperty, borderFactoryValue);
+          }
+          if (borderFactoryValue != null && borderFactoryValue.getValue().length() != 0) {
+            borderFactoryType = typeFromClassName(borderFactoryValue.getValue());
+          }
+          generator.invokeStatic(borderFactoryType, ourCreateTitledBorderMethod);
         }
-        if (borderFactoryValue != null && borderFactoryValue.getValue().length() != 0) {
-          borderFactoryType = typeFromClassName(borderFactoryValue.getValue());
-        }
-
-        generator.invokeStatic(borderFactoryType, ourCreateTitledBorderMethod);
 
         // set border
         generator.invokeVirtual(Type.getType(JComponent.class),
diff --git a/java/compiler/impl/src/com/intellij/compiler/impl/ModuleCompileScope.java b/java/compiler/impl/src/com/intellij/compiler/impl/ModuleCompileScope.java
index 3be5efc..b2485e8 100644
--- a/java/compiler/impl/src/com/intellij/compiler/impl/ModuleCompileScope.java
+++ b/java/compiler/impl/src/com/intellij/compiler/impl/ModuleCompileScope.java
@@ -33,6 +33,7 @@
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.VirtualFileManager;
+import com.intellij.util.CommonProcessors;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.HashMap;
@@ -75,13 +76,7 @@
   }
 
   private void buildScopeModulesSet(Module module) {
-    myScopeModules.add(module);
-    final Module[] dependencies = ModuleRootManager.getInstance(module).getDependencies();
-    for (Module dependency : dependencies) {
-      if (!myScopeModules.contains(dependency)) { // may be in case of module circular dependencies
-        buildScopeModulesSet(dependency);
-      }
-    }
+    ModuleRootManager.getInstance(module).orderEntries().recursively().compileOnly().forEachModule(new CommonProcessors.CollectProcessor<Module>(myScopeModules));
   }
 
   @NotNull
diff --git a/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java b/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java
index b772853..85ca916 100644
--- a/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java
+++ b/java/compiler/impl/src/com/intellij/compiler/options/CompilerUIConfigurable.java
@@ -39,7 +39,9 @@
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
+import java.awt.*;
 import java.util.*;
+import java.util.List;
 
 import static com.intellij.compiler.options.CompilerOptionsFilter.Setting;
 
@@ -169,10 +171,14 @@
     configuration.convertPatterns();
 
     myResourcePatternsField.setText(patternsToString(configuration.getResourceFilePatterns()));
-    
-    myEnableAutomakeLegendLabel.setText("(only works while not running / debugging" + 
-                                        (PowerSaveMode.isEnabled() ? ", disabled in Power Save mode" : "") + 
-                                        ")");
+
+    if (PowerSaveMode.isEnabled()) {
+      myEnableAutomakeLegendLabel.setText("(disabled in Power Save mode)");
+      myEnableAutomakeLegendLabel.setFont(myEnableAutomakeLegendLabel.getFont().deriveFont(Font.BOLD));
+    } else {
+      myEnableAutomakeLegendLabel.setText("(only works while not running / debugging)");
+      myEnableAutomakeLegendLabel.setFont(myEnableAutomakeLegendLabel.getFont().deriveFont(Font.PLAIN));
+    }
   }
 
   private static String patternsToString(final String[] patterns) {
diff --git a/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java b/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java
index 40170c9..5900ea2 100644
--- a/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java
+++ b/java/compiler/impl/testSrc/com/intellij/compiler/BaseCompilerTestCase.java
@@ -171,7 +171,15 @@
   }
 
   protected CompilationLog make(Module... modules) {
-    return make(getCompilerManager().createModulesCompileScope(modules, false), CompilerFilter.ALL);
+    return make(false, modules);
+  }
+
+  protected CompilationLog makeWithDependencies(Module... modules) {
+    return make(true, modules);
+  }
+
+  private CompilationLog make(boolean includeDependentModules, Module... modules) {
+    return make(getCompilerManager().createModulesCompileScope(modules, includeDependentModules), CompilerFilter.ALL);
   }
 
   protected CompilationLog recompile(Module... modules) {
diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java
index 3c6d456..57918b1 100644
--- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java
+++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTemplateList.java
@@ -25,8 +25,8 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.platform.ProjectTemplate;
 import com.intellij.platform.templates.ArchivedProjectTemplate;
-import com.intellij.ui.*;
-import com.intellij.ui.SingleSelectionModel;
+import com.intellij.ui.CollectionListModel;
+import com.intellij.ui.IdeBorderFactory;
 import com.intellij.ui.components.JBList;
 import com.intellij.ui.popup.list.GroupedItemsListRenderer;
 import com.intellij.util.containers.ContainerUtil;
@@ -100,7 +100,6 @@
       }
     };
     myList.setCellRenderer(renderer);
-    myList.setSelectionModel(new SingleSelectionModel());
     myList.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
       @Override
       public void valueChanged(ListSelectionEvent e) {
@@ -136,7 +135,9 @@
     int index = preserveSelection ? myList.getSelectedIndex() : -1;
     //noinspection unchecked
     myList.setModel(new CollectionListModel(list));
-    myList.setSelectedIndex(index == -1 ? 0 : index);
+    if (myList.isEnabled()) {
+      myList.setSelectedIndex(index == -1 ? 0 : index);
+    }
     updateSelection();
   }
 
@@ -149,6 +150,12 @@
   public void setEnabled(boolean enabled) {
     super.setEnabled(enabled);
     myList.setEnabled(enabled);
+    if (!enabled) {
+      myList.clearSelection();
+    }
+    else {
+      myList.setSelectedIndex(0);
+    }
     myDescriptionPane.setEnabled(enabled);
   }
 
diff --git a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java
index 3047d40..a64ba2d 100644
--- a/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java
+++ b/java/idea-ui/src/com/intellij/ide/projectWizard/ProjectTypeStep.java
@@ -194,7 +194,7 @@
 
     myModulesProvider = modulesProvider;
     Project project = context.getProject();
-    final LibrariesContainer container = LibrariesContainerFactory.createContainer(project);
+    final LibrariesContainer container = LibrariesContainerFactory.createContainer(context, modulesProvider);
     FrameworkSupportModelBase model = new FrameworkSupportModelBase(project, null, container) {
       @NotNull
       @Override
diff --git a/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java b/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java
index 8bbc756..c72c5fc 100644
--- a/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java
+++ b/java/java-analysis-api/src/com/intellij/codeInsight/intention/QuickFixFactory.java
@@ -206,7 +206,7 @@
 
   @NotNull public abstract IntentionAction createDeferFinalAssignmentFix(@NotNull PsiVariable variable, @NotNull PsiReferenceExpression expression);
 
-  @NotNull public abstract IntentionAction createVariableAccessFromInnerClassFix(@NotNull PsiVariable variable, @NotNull PsiClass aClass);
+  @NotNull public abstract IntentionAction createVariableAccessFromInnerClassFix(@NotNull PsiVariable variable, @NotNull PsiElement scope);
 
   @NotNull public abstract IntentionAction createCreateConstructorParameterFromFieldFix(@NotNull PsiField field);
 
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
index 14c3217..e6de88e 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/GenericsHighlightUtil.java
@@ -42,6 +42,7 @@
 import com.intellij.util.containers.HashMap;
 import com.intellij.util.containers.HashSet;
 import gnu.trove.THashMap;
+import gnu.trove.THashSet;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -326,7 +327,8 @@
     if (errorResult == null && languageLevel.isAtLeast(LanguageLevel.JDK_1_7) &&
         referenceElements.length > 1) {
       //todo suppress erased methods which come from the same class
-      return checkOverrideEquivalentMethods(languageLevel, aClass);
+      final Collection<HighlightInfo> result = checkOverrideEquivalentMethods(languageLevel, aClass);
+      return result != null && result.size() > 0 ? result.iterator().next() : null;
     }
     return errorResult;
   }
@@ -380,23 +382,29 @@
     return null;
   }
 
-  public static HighlightInfo checkOverrideEquivalentMethods(@NotNull LanguageLevel languageLevel,
-                                                             @NotNull PsiClass aClass) {
+  public static Collection<HighlightInfo> checkOverrideEquivalentMethods(@NotNull LanguageLevel languageLevel,
+                                                                         @NotNull PsiClass aClass) {
+    List<HighlightInfo> result = new ArrayList<HighlightInfo>();
     final Collection<HierarchicalMethodSignature> signaturesWithSupers = aClass.getVisibleSignatures();
     PsiManager manager = aClass.getManager();
     Map<MethodSignature, MethodSignatureBackedByPsiMethod> sameErasureMethods =
       new THashMap<MethodSignature, MethodSignatureBackedByPsiMethod>(MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY);
 
+    final Set<MethodSignature> foundProblems = new THashSet<MethodSignature>(MethodSignatureUtil.METHOD_PARAMETERS_ERASURE_EQUALITY);
     for (HierarchicalMethodSignature signature : signaturesWithSupers) {
       HighlightInfo info = checkSameErasureNotSubSignatureInner(signature, manager, aClass, sameErasureMethods);
-      if (info != null) return info;
+      if (info != null && foundProblems.add(signature)) {
+        result.add(info);
+      }
       if (aClass instanceof PsiTypeParameter) {
         info = HighlightMethodUtil.checkMethodIncompatibleReturnType(signature, signature.getSuperSignatures(), true, HighlightNamesUtil.getClassDeclarationTextRange(aClass));
-        if (info != null) return info;
+        if (info != null) {
+          result.add(info);
+        }
       }
     }
 
-    return null;
+    return result.isEmpty() ? null : result;
   }
 
   static HighlightInfo checkDefaultMethodOverrideEquivalentToObjectNonPrivate(@NotNull LanguageLevel languageLevel,
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
index 9642390..40463be 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightControlFlowUtil.java
@@ -590,7 +590,7 @@
                            JavaErrorMessages.message("assignment.to.final.variable", name);
       final HighlightInfo highlightInfo =
         HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(reference.getTextRange()).descriptionAndTooltip(description).create();
-      final PsiClass innerClass = getInnerClassVariableReferencedFrom(variable, expression);
+      final PsiElement innerClass = getInnerClassVariableReferencedFrom(variable, expression);
       if (innerClass == null || variable instanceof PsiField) {
         QuickFixAction.registerQuickFixAction(highlightInfo,
                                               QUICK_FIX_FACTORY.createModifierListFix(variable, PsiModifier.FINAL, false, false));
@@ -607,7 +607,7 @@
   private static boolean canWriteToFinal(PsiVariable variable, PsiExpression expression, final PsiReferenceExpression reference, @NotNull PsiFile containingFile) {
     if (variable.hasInitializer()) return false;
     if (variable instanceof PsiParameter) return false;
-    PsiClass innerClass = getInnerClassVariableReferencedFrom(variable, expression);
+    PsiElement innerClass = getInnerClassVariableReferencedFrom(variable, expression);
     if (variable instanceof PsiField) {
       // if inside some field initializer
       if (HighlightUtil.findEnclosingFieldInitializer(expression) != null) return true;
@@ -642,8 +642,8 @@
                                                 @NotNull PsiJavaCodeReferenceElement context,
                                                 @NotNull LanguageLevel languageLevel) {
     if (variable.hasModifierProperty(PsiModifier.FINAL)) return null;
-    final PsiClass innerClass = getInnerClassVariableReferencedFrom(variable, context);
-    if (innerClass != null) {
+    final PsiElement innerClass = getInnerClassVariableReferencedFrom(variable, context);
+    if (innerClass instanceof PsiClass) {
       if (variable instanceof PsiParameter) {
         final PsiElement parent = variable.getParent();
         if (parent instanceof PsiParameterList && parent.getParent() instanceof PsiLambdaExpression &&
@@ -672,8 +672,12 @@
         return null;
       }
       if (!isEffectivelyFinal(variable, lambdaExpression, context)) {
-        return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(context).descriptionAndTooltip(
-          "Variable used in lambda expression should be effectively final").create();
+        final HighlightInfo highlightInfo = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
+          .range(context)
+          .descriptionAndTooltip("Variable used in lambda expression should be effectively final")
+          .create();
+        QuickFixAction.registerQuickFixAction(highlightInfo, QUICK_FIX_FACTORY.createVariableAccessFromInnerClassFix(variable, lambdaExpression));
+        return highlightInfo;
       }
     }
     return null;
@@ -716,7 +720,7 @@
   }
 
   @Nullable
-  public static PsiClass getInnerClassVariableReferencedFrom(PsiVariable variable, PsiElement context) {
+  public static PsiElement getInnerClassVariableReferencedFrom(@NotNull PsiVariable variable, @NotNull PsiElement context) {
     final PsiElement[] scope;
     if (variable instanceof PsiResourceVariable) {
       scope = ((PsiResourceVariable)variable).getDeclarationScope();
@@ -741,7 +745,10 @@
         if (parent.equals(scopeElement)) break outer;
       }
       if (parent instanceof PsiClass && !(prevParent instanceof PsiExpressionList && parent instanceof PsiAnonymousClass)) {
-        return (PsiClass)parent;
+        return parent;
+      }
+      if (parent instanceof PsiLambdaExpression) {
+        return parent;
       }
       prevParent = parent;
       parent = parent.getParent();
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
index 975794d..007fbdc 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightMethodUtil.java
@@ -1181,7 +1181,7 @@
             continue;
           }
         }
-        if (JavaGenericsUtil.isRawToGeneric(currentType, otherSuperReturnType)) continue;
+        if (currentMethod.getTypeParameters().length > 0 && JavaGenericsUtil.isRawToGeneric(currentType, otherSuperReturnType)) continue;
       }
       return createIncompatibleReturnTypeMessage(currentMethod, otherSuperMethod, otherSuperReturnType,
                                                  currentType, JavaErrorMessages.message("unrelated.overriding.methods.return.types"),
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
index 66dfd93..db56e8b 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightUtil.java
@@ -684,10 +684,6 @@
         String message = JavaErrorMessages.message("underscore.lambda.identifier");
         return HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR).range(identifier).descriptionAndTooltip(message).create();
       }
-      else {
-        String message = JavaErrorMessages.message("underscore.identifier");
-        return HighlightInfo.newHighlightInfo(HighlightInfoType.WARNING).range(identifier).descriptionAndTooltip(message).create();
-      }
     }
 
     return null;
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
index aa735a1..e390d43 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/HighlightVisitorImpl.java
@@ -552,7 +552,9 @@
         PsiElement resolved = result.getElement();
 
         if ((!result.isAccessible() || !result.isStaticsScopeCorrect()) &&
-            !HighlightMethodUtil.isDummyConstructorCall(expression, myResolveHelper, list, referenceExpression)) {
+            !HighlightMethodUtil.isDummyConstructorCall(expression, myResolveHelper, list, referenceExpression) &&
+            // this check is for fake expression from JspMethodCallImpl
+            referenceExpression.getParent() == expression) {
           try {
             myHolder.add(HighlightMethodUtil.checkAmbiguousMethodCallArguments(referenceExpression, results, list, resolved, result, expression, myResolveHelper));
           }
@@ -886,8 +888,7 @@
           myHolder.add(HighlightClassUtil.checkClassDoesNotCallSuperConstructorOrHandleExceptions(aClass, myRefCountHolder, myResolveHelper));
         }
         if (!myHolder.hasErrorResults()) myHolder.add(HighlightMethodUtil.checkOverrideEquivalentInheritedMethods(aClass, myFile));
-        if (!myHolder.hasErrorResults()) myHolder.add(GenericsHighlightUtil.checkOverrideEquivalentMethods(myLanguageLevel, aClass
-        ));
+        if (!myHolder.hasErrorResults()) myHolder.addAll(GenericsHighlightUtil.checkOverrideEquivalentMethods(myLanguageLevel, aClass));
         if (!myHolder.hasErrorResults()) myHolder.add(HighlightClassUtil.checkCyclicInheritance(aClass));
       }
       catch (IndexNotReadyException ignored) {
@@ -1043,7 +1044,7 @@
 
     if (parent instanceof PsiAnonymousClass && ref.equals(((PsiAnonymousClass)parent).getBaseClassReference())) {
       PsiClass aClass = (PsiClass)parent;
-      myHolder.add(GenericsHighlightUtil.checkOverrideEquivalentMethods(myLanguageLevel, aClass));
+      myHolder.addAll(GenericsHighlightUtil.checkOverrideEquivalentMethods(myLanguageLevel, aClass));
     }
 
     if (resolved instanceof PsiVariable) {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavaGenericsUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavaGenericsUtil.java
index 3a5df04..fc39dde 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavaGenericsUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/JavaGenericsUtil.java
@@ -281,7 +281,7 @@
       if (typeParameter == null) return null;
       PsiClass owner = (PsiClass)typeParameter.getOwner();
       if (owner == null) return null;
-      PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getClassSubstitutor(owner, aClass, PsiSubstitutor.EMPTY);
+      PsiSubstitutor superClassSubstitutor = TypeConversionUtil.getClassSubstitutor(owner, aClass, substitutor);
       if (superClassSubstitutor == null) return null;
       PsiType itemType = superClassSubstitutor.substitute(typeParameter);
       itemType = substitutor.substitute(itemType);
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java
index e066685..4f680b3 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/StreamApiMigrationInspection.java
@@ -76,7 +76,7 @@
           final PsiStatement body = statement.getBody();
           if (iteratedValue != null && body != null) {
             final PsiType iteratedValueType = iteratedValue.getType();
-            if (InheritanceUtil.isInheritor(iteratedValueType, CommonClassNames.JAVA_LANG_ITERABLE)) {
+            if (InheritanceUtil.isInheritor(iteratedValueType, CommonClassNames.JAVA_UTIL_COLLECTION)) {
               final PsiClass iteratorClass = PsiUtil.resolveClassInType(iteratedValueType);
               LOG.assertTrue(iteratorClass != null);
               try {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/compiler/JavacQuirksInspectionVisitor.java b/java/java-analysis-impl/src/com/intellij/codeInspection/compiler/JavacQuirksInspectionVisitor.java
index 740a410..63d4c89 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/compiler/JavacQuirksInspectionVisitor.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/compiler/JavacQuirksInspectionVisitor.java
@@ -15,9 +15,11 @@
  */
 package com.intellij.codeInspection.compiler;
 
+import com.intellij.codeInsight.daemon.JavaErrorMessages;
 import com.intellij.codeInspection.InspectionsBundle;
 import com.intellij.codeInspection.ProblemsHolder;
 import com.intellij.patterns.ElementPattern;
+import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
@@ -63,4 +65,14 @@
       });
     }
   }
+
+  @Override
+  public void visitIdentifier(PsiIdentifier identifier) {
+    super.visitIdentifier(identifier);
+    if (PsiUtil.getLanguageLevel(identifier).isAtLeast(LanguageLevel.JDK_1_8)) {
+      if ("_".equals(identifier.getText())) {
+        myHolder.registerProblem(identifier, JavaErrorMessages.message("underscore.identifier"));
+      }
+    }
+  }
 }
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
index 1be69b5..4dd7965 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/ControlFlowAnalyzer.java
@@ -22,6 +22,7 @@
 import com.intellij.codeInspection.dataFlow.value.*;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.search.GlobalSearchScope;
@@ -38,6 +39,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
+import java.util.regex.Pattern;
 
 import static com.intellij.codeInsight.ConditionChecker.Type.*;
 import static com.intellij.codeInspection.dataFlow.MethodContract.ValueConstraint;
@@ -45,6 +47,24 @@
 
 public class ControlFlowAnalyzer extends JavaElementVisitor {
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.dataFlow.ControlFlowAnalyzer");
+  private static final Condition<String> FALSE_GETTERS = parseFalseGetters();
+
+  private static Condition<String> parseFalseGetters() {
+    try {
+      final Pattern pattern = Pattern.compile(Registry.stringValue("ide.dfa.getters.with.side.effects"));
+      return new Condition<String>() {
+        @Override
+        public boolean value(String s) {
+          return pattern.matcher(s).matches();
+        }
+      };
+    }
+    catch (Exception e) {
+      LOG.error(e);
+      return Condition.FALSE;
+    }
+  }
+
   public static final String ORG_JETBRAINS_ANNOTATIONS_CONTRACT = Contract.class.getName();
   private boolean myIgnoreAssertions;
 
@@ -1891,7 +1911,10 @@
     }
     if (target instanceof PsiMethod) {
       if (PropertyUtil.isSimplePropertyGetter((PsiMethod)target)) {
-        return (PsiMethod)target;
+        String qName = PsiUtil.getMemberQualifiedName((PsiMethod)target);
+        if (qName == null || !FALSE_GETTERS.value(qName)) {
+          return (PsiMethod)target;
+        }
       }
     }
     return null;
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardInstructionVisitor.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardInstructionVisitor.java
index be70ba0..954896e 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardInstructionVisitor.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardInstructionVisitor.java
@@ -310,7 +310,7 @@
 
     final IElementType opSign = instruction.getOperationSign();
     if (opSign != null) {
-      DfaInstructionState[] states = handleConstantComparison(instruction, runner, memState, dfaRight, dfaLeft);
+      DfaInstructionState[] states = handleConstantComparison(instruction, runner, memState, dfaRight, dfaLeft, opSign);
       if (states == null) {
         states = handleRelationBinop(instruction, runner, memState, dfaRight, dfaLeft);
       }
@@ -422,8 +422,21 @@
                                                                 DataFlowRunner runner,
                                                                 DfaMemoryState memState,
                                                                 DfaValue dfaRight,
-                                                                DfaValue dfaLeft) {
-    final IElementType opSign = instruction.getOperationSign();
+                                                                DfaValue dfaLeft, IElementType opSign) {
+    if (dfaRight instanceof DfaConstValue && dfaLeft instanceof DfaVariableValue) {
+      PsiType varType = ((DfaVariableValue)dfaLeft).getVariableType();
+      Object value = ((DfaConstValue)dfaRight).getValue();
+      if (varType instanceof PsiPrimitiveType && value instanceof Number) {
+        DfaInstructionState[] result = checkTypeRanges(instruction, runner, memState, opSign, varType, ((Number)value).longValue());
+        if (result != null) {
+          return result;
+        }
+      }
+    }
+    if (dfaRight instanceof DfaVariableValue && dfaLeft instanceof DfaConstValue) {
+      return handleConstantComparison(instruction, runner, memState, dfaLeft, dfaRight, DfaRelationValue.getSymmetricOperation(opSign));
+    }
+
     if (EQEQ != opSign && NE != opSign ||
         !(dfaLeft instanceof DfaConstValue) || !(dfaRight instanceof DfaConstValue)) {
       return null;
@@ -431,13 +444,51 @@
 
     boolean negated = (NE == opSign) ^ (DfaMemoryStateImpl.isNaN(dfaLeft) || DfaMemoryStateImpl.isNaN(dfaRight));
     if (dfaLeft == dfaRight ^ negated) {
-      memState.push(runner.getFactory().getConstFactory().getTrue());
-      instruction.setTrueReachable();
+      return alwaysTrue(instruction, runner, memState);
     }
-    else {
-      memState.push(runner.getFactory().getConstFactory().getFalse());
-      instruction.setFalseReachable();
+    return alwaysFalse(instruction, runner, memState);
+  }
+
+  private static DfaInstructionState[] checkTypeRanges(BinopInstruction instruction,
+                                                       DataFlowRunner runner,
+                                                       DfaMemoryState memState,
+                                                       IElementType opSign, PsiType varType, long constantValue) {
+    long minValue = varType == PsiType.BYTE ? Byte.MIN_VALUE :
+                    varType == PsiType.SHORT ? Short.MIN_VALUE :
+                    varType == PsiType.INT ? Integer.MIN_VALUE :
+                    varType == PsiType.CHAR ? Character.MIN_VALUE :
+                    Long.MIN_VALUE;
+    long maxValue = varType == PsiType.BYTE ? Byte.MAX_VALUE :
+                    varType == PsiType.SHORT ? Short.MAX_VALUE :
+                    varType == PsiType.INT ? Integer.MAX_VALUE :
+                    varType == PsiType.CHAR ? Character.MAX_VALUE :
+                    Long.MAX_VALUE;
+
+    if (constantValue < minValue || constantValue > maxValue) {
+      if (opSign == EQEQ) return alwaysFalse(instruction, runner, memState);
+      if (opSign == NE) return alwaysTrue(instruction, runner, memState);
     }
+
+    if (opSign == LT && constantValue <= minValue) return alwaysFalse(instruction, runner, memState);
+    if (opSign == LT && constantValue > maxValue) return alwaysTrue(instruction, runner, memState);
+    if (opSign == LE && constantValue >= maxValue) return alwaysTrue(instruction, runner, memState);
+
+    if (opSign == GT && constantValue >= maxValue) return alwaysFalse(instruction, runner, memState);
+    if (opSign == GT && constantValue < minValue) return alwaysTrue(instruction, runner, memState);
+    if (opSign == GE && constantValue <= minValue) return alwaysTrue(instruction, runner, memState);
+
+    return null;
+  }
+
+  private static DfaInstructionState[] alwaysFalse(BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
+    memState.push(runner.getFactory().getConstFactory().getFalse());
+    instruction.setFalseReachable();
+    return nextInstruction(instruction, runner, memState);
+  }
+
+  private static DfaInstructionState[] alwaysTrue(BinopInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
+    memState.push(runner.getFactory().getConstFactory().getTrue());
+    instruction.setTrueReachable();
     return nextInstruction(instruction, runner, memState);
   }
 
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaRelationValue.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaRelationValue.java
index c3593f6..8343fc9 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaRelationValue.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaRelationValue.java
@@ -114,13 +114,14 @@
       return result;
     }
 
-    private static IElementType getSymmetricOperation(IElementType sign) {
-      if (LT == sign) return GT;
-      if (GE == sign) return LE;
-      if (GT == sign) return LT;
-      if (LE == sign) return GE;
-      return sign;
-    }
+  }
+
+  public static IElementType getSymmetricOperation(IElementType sign) {
+    if (LT == sign) return GT;
+    if (GE == sign) return LE;
+    if (GT == sign) return LT;
+    if (LE == sign) return GE;
+    return sign;
   }
 
   private DfaRelationValue(DfaValueFactory factory) {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java
index 5ec56b9..63be252 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/value/DfaVariableValue.java
@@ -25,6 +25,7 @@
 package com.intellij.codeInspection.dataFlow.value;
 
 import com.intellij.codeInsight.NullableNotNullManager;
+import com.intellij.codeInsight.daemon.impl.analysis.JavaGenericsUtil;
 import com.intellij.codeInspection.dataFlow.DfaPsiUtil;
 import com.intellij.codeInspection.dataFlow.Nullness;
 import com.intellij.openapi.util.Comparing;
@@ -160,6 +161,16 @@
       return nullability;
     }
 
+    if (var instanceof PsiParameter && var.getParent() instanceof PsiForeachStatement) {
+      PsiExpression iteratedValue = ((PsiForeachStatement)var.getParent()).getIteratedValue();
+      if (iteratedValue != null) {
+        PsiType itemType = JavaGenericsUtil.getCollectionItemType(iteratedValue);
+        if (itemType != null) {
+          return DfaPsiUtil.getElementNullability(itemType, var);
+        }
+      }
+    }
+
     if (var instanceof PsiField && DfaPsiUtil.isFinalField((PsiVariable)var) && myFactory.isHonorFieldInitializers()) {
       List<PsiExpression> initializers = DfaPsiUtil.findAllConstructorInitializers((PsiField)var);
       if (initializers.isEmpty()) {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java
index 83fd6c5..fa27898 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/uncheckedWarnings/UncheckedWarningLocalInspectionBase.java
@@ -199,6 +199,18 @@
     }
 
     @Override
+    public void visitMethodReferenceExpression(PsiMethodReferenceExpression expression) {
+      super.visitMethodReferenceExpression(expression);
+      if (IGNORE_UNCHECKED_CALL) return;
+      final JavaResolveResult result = expression.advancedResolve(false);
+      final String description = getUncheckedCallDescription(result);
+      if (description != null) {
+        final PsiElement referenceNameElement = expression.getReferenceNameElement();
+        registerProblem(description, referenceNameElement != null ? referenceNameElement : expression, myGenerifyFixes);
+      }
+    }
+
+    @Override
     public void visitCallExpression(PsiCallExpression callExpression) {
       super.visitCallExpression(callExpression);
       final JavaResolveResult result = callExpression.resolveMethodGenerics();
@@ -383,8 +395,9 @@
 
     @Nullable
     private String getUncheckedCallDescription(JavaResolveResult resolveResult) {
-      final PsiMethod method = (PsiMethod)resolveResult.getElement();
-      if (method == null) return null;
+      final PsiElement element = resolveResult.getElement();
+      if (!(element instanceof PsiMethod)) return null;
+      final PsiMethod method = (PsiMethod)element;
       final PsiSubstitutor substitutor = resolveResult.getSubstitutor();
       if (!PsiUtil.isRawSubstitutor(method, substitutor)) return null;
       final PsiParameter[] parameters = method.getParameterList().getParameters();
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java
index a5431b5..270d6f9 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java
@@ -22,20 +22,20 @@
 import com.intellij.openapi.editor.RangeMarker;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
+import com.intellij.psi.impl.search.AllClassesSearchExecutor;
 import com.intellij.psi.impl.source.PostprocessReformattingAspect;
 import com.intellij.psi.impl.source.tree.java.PsiReferenceExpressionImpl;
 import com.intellij.psi.search.GlobalSearchScope;
-import com.intellij.psi.search.searches.AllClassesSearch;
 import com.intellij.util.Consumer;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.Processor;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.NotNull;
 
+import java.util.LinkedHashSet;
 import java.util.Set;
 
 /**
@@ -184,18 +184,17 @@
                                         @NotNull Project project,
                                         @NotNull GlobalSearchScope scope,
                                         @NotNull Processor<PsiClass> processor) {
-    AllClassesSearch.search(scope, project, new Condition<String>() {
+    final Set<String> names = new THashSet<String>(10000);
+    AllClassesSearchExecutor.processClassNames(project, scope, new Consumer<String>() {
       @Override
-      public boolean value(String s) {
-        return prefixMatcher.isStartMatch(s);
+      public void consume(String s) {
+        if (prefixMatcher.prefixMatches(s)) {
+          names.add(s);
+        }
       }
-    }).forEach(processor);
-    AllClassesSearch.search(scope, project, new Condition<String>() {
-      @Override
-      public boolean value(String s) {
-        return prefixMatcher.prefixMatches(s);
-      }
-    }).forEach(processor);
+    });
+    LinkedHashSet<String> sorted = CompletionUtil.sortMatching(prefixMatcher, names);
+    AllClassesSearchExecutor.processClassesByNames(project, scope, sorted, processor);
   }
 
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java
index d645290..28767e6 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionContributor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -400,7 +400,7 @@
     if (((PsiJavaCodeReferenceElement)parent).getQualifier() != null) return isSecondCompletion;
 
     if (parent instanceof PsiJavaCodeReferenceElementImpl &&
-        ((PsiJavaCodeReferenceElementImpl)parent).getKind() == PsiJavaCodeReferenceElementImpl.PACKAGE_NAME_KIND) {
+        ((PsiJavaCodeReferenceElementImpl)parent).getKind(parent.getContainingFile()) == PsiJavaCodeReferenceElementImpl.PACKAGE_NAME_KIND) {
       return false;
     }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java
index b66073e..d144a67 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionSorting.java
@@ -34,6 +34,7 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.psi.util.TypeConversionUtil;
 import com.intellij.util.Function;
+import com.intellij.util.SmartList;
 import com.intellij.util.containers.ContainerUtil;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.NotNull;
@@ -425,20 +426,35 @@
   }
 
   private static class PreferExpected extends LookupElementWeigher {
-    private final boolean myAcceptClasses;
+    private final boolean myConstructorPossible;
     private final ExpectedTypeInfo[] myExpectedTypes;
+    private final List<PsiType> myExpectedClasses = new SmartList<PsiType>();
 
-    public PreferExpected(boolean acceptClasses, ExpectedTypeInfo[] expectedTypes) {
+    public PreferExpected(boolean constructorPossible, ExpectedTypeInfo[] expectedTypes) {
       super("expectedType");
-      myAcceptClasses = acceptClasses;
+      myConstructorPossible = constructorPossible;
       myExpectedTypes = expectedTypes;
+      for (ExpectedTypeInfo info : expectedTypes) {
+        ContainerUtil.addIfNotNull(myExpectedClasses, PsiUtil.substituteTypeParameter(info.getDefaultType(), CommonClassNames.JAVA_LANG_CLASS, 0, false));
+      }
     }
 
     @NotNull
     @Override
-    public Comparable weigh(@NotNull LookupElement item) {
-      return item.getObject() instanceof PsiClass && !myAcceptClasses
-             ? ExpectedTypeMatching.normal : getExpectedTypeMatching(item, myExpectedTypes);
+    public ExpectedTypeMatching weigh(@NotNull LookupElement item) {
+      if (item.getObject() instanceof PsiClass && !myConstructorPossible) {
+        PsiType itemType = JavaCompletionUtil.getLookupElementType(item);
+        if (itemType != null) {
+          for (PsiType expectedClass : myExpectedClasses) {
+            if (expectedClass.isAssignableFrom(itemType)) {
+              return ExpectedTypeMatching.expected;
+            }
+          }
+        }
+        return ExpectedTypeMatching.normal;
+      }
+
+      return getExpectedTypeMatching(item, myExpectedTypes);
     }
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java
index fd0de03..bb0d339 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaCompletionUtil.java
@@ -330,7 +330,9 @@
 
     PsiScopesUtil.processTypeDeclarations(qualifierType, member, new MyProcessor());
 
-    PsiType rawType = member instanceof PsiField ? ((PsiField) member).getType() : ((PsiMethod) member).getReturnType();
+    PsiType rawType = member instanceof PsiField ? ((PsiField) member).getType() :
+                      member instanceof PsiMethod ? ((PsiMethod) member).getReturnType() :
+                      JavaPsiFacade.getElementFactory(member.getProject()).createType((PsiClass)member);
     return subst.get().substitute(rawType);
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/PreferByKindWeigher.java b/java/java-impl/src/com/intellij/codeInsight/completion/PreferByKindWeigher.java
index e8c828a..2960bd7 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/PreferByKindWeigher.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/PreferByKindWeigher.java
@@ -144,10 +144,8 @@
       }
     }
 
-    if (myCompletionType == CompletionType.SMART) {
-      if (object instanceof PsiLocalVariable || object instanceof PsiParameter || object instanceof PsiThisExpression) {
-        return MyResult.localOrParameter;
-      }
+    if (object instanceof PsiLocalVariable || object instanceof PsiParameter || object instanceof PsiThisExpression) {
+      return MyResult.localOrParameter;
     }
 
     if (object instanceof String && item.getUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS) == Boolean.TRUE) {
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java b/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java
index d3f0b2e..d898bb7 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/SameSignatureCallParametersProvider.java
@@ -19,6 +19,7 @@
 import com.intellij.codeInsight.lookup.LookupElement;
 import com.intellij.codeInsight.lookup.LookupElementBuilder;
 import com.intellij.codeInsight.lookup.TailTypeDecorator;
+import com.intellij.codeInsight.lookup.VariableLookupItem;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.text.StringUtil;
@@ -72,8 +73,8 @@
     }
   }
 
-  private static LookupElement createParametersLookupElement(PsiMethod takeParametersFrom, PsiElement call, PsiMethod invoked) {
-    PsiParameter[] parameters = takeParametersFrom.getParameterList().getParameters();
+  private static LookupElement createParametersLookupElement(final PsiMethod takeParametersFrom, PsiElement call, PsiMethod invoked) {
+    final PsiParameter[] parameters = takeParametersFrom.getParameterList().getParameters();
     final String lookupString = StringUtil.join(parameters, new Function<PsiParameter, String>() {
       @Override
       public String fun(PsiParameter psiParameter) {
@@ -86,7 +87,18 @@
     icon.setIcon(PlatformIcons.PARAMETER_ICON, 0, 2*w/5, 0);
     icon.setIcon(PlatformIcons.PARAMETER_ICON, 1);
 
-    final LookupElement element = LookupElementBuilder.create(lookupString).withIcon(icon);
+    LookupElementBuilder element = LookupElementBuilder.create(lookupString).withIcon(icon);
+    if (PsiTreeUtil.isAncestor(takeParametersFrom, call, true)) {
+      element = element.withInsertHandler(new InsertHandler<LookupElement>() {
+        @Override
+        public void handleInsert(InsertionContext context, LookupElement item) {
+          context.commitDocument();
+          for (PsiParameter parameter : CompletionUtil.getOriginalOrSelf(takeParametersFrom).getParameterList().getParameters()) {
+            VariableLookupItem.makeFinalIfNeeded(context, parameter);
+          }
+        }
+      });
+    }
     element.putUserData(JavaCompletionUtil.SUPER_METHOD_PARAMETERS, Boolean.TRUE);
 
     return TailTypeDecorator.withTail(element, ExpectedTypesProvider.getFinalCallParameterTailType(call, invoked.getReturnType(), invoked));
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/SmartCompletionDecorator.java b/java/java-impl/src/com/intellij/codeInsight/completion/SmartCompletionDecorator.java
index e5a9ee43..e2cc133 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/SmartCompletionDecorator.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/SmartCompletionDecorator.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.codeInsight.completion;
 
+import com.intellij.codeInsight.AutoPopupController;
 import com.intellij.codeInsight.CodeInsightSettings;
 import com.intellij.codeInsight.ExpectedTypeInfo;
 import com.intellij.codeInsight.TailType;
@@ -117,8 +118,14 @@
       context.commitDocument();
     }
     myPosition = getPosition(context, this);
-    
+
+    TailType tailType = computeTailType(context);
+
     super.handleInsert(context);
+
+    if (tailType == TailType.COMMA) {
+      AutoPopupController.getInstance(context.getProject()).autoPopupParameterInfo(context.getEditor(), null);
+    }
   }
 
   public static boolean hasUnboundTypeParams(final PsiMethod method, PsiType expectedType) {
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java b/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java
index fb7878d..4e13baf 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/scope/JavaCompletionProcessor.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.filters.ElementFilter;
+import com.intellij.psi.impl.light.LightMethodBuilder;
 import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
 import com.intellij.psi.infos.CandidateInfo;
 import com.intellij.psi.scope.BaseScopeProcessor;
@@ -100,14 +101,11 @@
       if (qualifier instanceof PsiSuperExpression) {
         final PsiJavaCodeReferenceElement qSuper = ((PsiSuperExpression)qualifier).getQualifier();
         if (qSuper == null) {
-          myQualifierClass = JavaResolveUtil.getContextClass( myElement);
+          myQualifierClass = JavaResolveUtil.getContextClass(myElement);
         } else {
           final PsiElement target = qSuper.resolve();
           myQualifierClass = target instanceof PsiClass ? (PsiClass)target : null;
         }
-        if (myQualifierClass != null) {
-          myQualifierType = JavaPsiFacade.getInstance(element.getProject()).getElementFactory().createType(myQualifierClass);
-        }
       }
       else if (qualifier != null) {
         setQualifierType(qualifier.getType());
@@ -117,8 +115,13 @@
             myQualifierClass = (PsiClass)target;
           }
         }
+      } else {
+        myQualifierClass = JavaResolveUtil.getContextClass(myElement);
       }
     }
+    if (myQualifierClass != null && myQualifierType == null) {
+      myQualifierType = JavaPsiFacade.getElementFactory(element.getProject()).createType(myQualifierClass);
+    }
 
     if (myOptions.checkInitialized) {
       myNonInitializedFields.addAll(getNonInitializedFields(element));
@@ -219,6 +222,19 @@
       return true;
     }
 
+    if (element instanceof PsiMethod) {
+      PsiMethod method = (PsiMethod)element;
+      if (PsiTypesUtil.isGetClass(method) && PsiUtil.isLanguageLevel5OrHigher(myElement)) {
+        PsiType patchedType = PsiTypesUtil.createJavaLangClassType(myElement, myQualifierType, false);
+        if (patchedType != null) {
+          element = new LightMethodBuilder(element.getManager(), method.getName()).
+            addModifier(PsiModifier.PUBLIC).
+            setMethodReturnType(patchedType).
+            setContainingClass(method.getContainingClass());
+        }
+      }
+    }
+
     if (satisfies(element, state) && isAccessible(element)) {
       CompletionElement element1 = new CompletionElement(element, state.get(PsiSubstitutor.KEY));
       if (myResultNames.add(element1.getUniqueId())) {
@@ -288,7 +304,9 @@
     if (!(element instanceof PsiMember)) return true;
 
     PsiMember member = (PsiMember)element;
-    return JavaPsiFacade.getInstance(element.getProject()).getResolveHelper().isAccessible(member, member.getModifierList(), myElement, myQualifierClass, myDeclarationHolder);
+    PsiClass accessObjectClass = member instanceof PsiClass ? null : myQualifierClass;
+    return JavaPsiFacade.getInstance(element.getProject()).getResolveHelper().isAccessible(member, member.getModifierList(), myElement,
+                                                                                           accessObjectClass, myDeclarationHolder);
   }
 
   public void setCompletionElements(@NotNull Object[] elements) {
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java
index b0c29bf..74df483 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromMethodReferenceFix.java
@@ -124,15 +124,16 @@
     final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(functionalInterfaceType);
     LOG.assertTrue(interfaceReturnType != null);
 
+    final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, classResolveResult);
     final ExpectedTypeInfo[] expectedTypes = {new ExpectedTypeInfoImpl(interfaceReturnType, ExpectedTypeInfo.TYPE_OR_SUBTYPE, interfaceReturnType, TailType.NONE, null, ExpectedTypeInfoImpl.NULL)};
     CreateMethodFromUsageFix.doCreate(targetClass, method, false,
                                       ContainerUtil.map2List(interfaceMethod.getParameterList().getParameters(), new Function<PsiParameter, Pair<PsiExpression, PsiType>>() {
                                         @Override
                                         public Pair<PsiExpression, PsiType> fun(PsiParameter parameter) {
-                                          return Pair.create(null, parameter.getType());
+                                          return Pair.create(null, substitutor.substitute(parameter.getType()));
                                         }
                                       }),
-                                      LambdaUtil.getSubstitutor(interfaceMethod, classResolveResult),
+                                      PsiSubstitutor.EMPTY,
                                       expectedTypes, context);
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java
index 3ce0127..b7cd8af 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/CreateMethodFromUsageFix.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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,14 +17,14 @@
 
 import com.intellij.codeInsight.CodeInsightUtilCore;
 import com.intellij.codeInsight.ExpectedTypeInfo;
-import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx;
 import com.intellij.codeInsight.daemon.QuickFixBundle;
+import com.intellij.codeInsight.daemon.impl.DaemonCodeAnalyzerEx;
 import com.intellij.codeInsight.daemon.impl.HighlightInfo;
 import com.intellij.codeInsight.template.Template;
 import com.intellij.codeInsight.template.TemplateBuilderImpl;
 import com.intellij.codeInsight.template.TemplateEditingAdapter;
 import com.intellij.lang.annotation.HighlightSeverity;
-import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
@@ -259,7 +259,7 @@
       startTemplate(newEditor, template, project, new TemplateEditingAdapter() {
         @Override
         public void templateFinished(Template template, boolean brokenOff) {
-          ApplicationManager.getApplication().runWriteAction(new Runnable() {
+          WriteCommandAction.runWriteCommandAction(project, new Runnable() {
             @Override
             public void run() {
               PsiDocumentManager.getInstance(project).commitDocument(newEditor.getDocument());
diff --git a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java
index 98a2716..47ed78e 100644
--- a/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java
+++ b/java/java-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/VariableAccessFromInnerClassFix.java
@@ -42,16 +42,16 @@
 public class VariableAccessFromInnerClassFix implements IntentionAction {
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.daemon.impl.quickfix.VariableAccessFromInnerClassFix");
   private final PsiVariable myVariable;
-  private final PsiClass myClass;
+  private final PsiElement myContext;
   private final int myFixType;
   private static final int MAKE_FINAL = 0;
   private static final int MAKE_ARRAY = 1;
   private static final int COPY_TO_FINAL = 2;
   private static final Key<Map<PsiVariable,Boolean>>[] VARS = new Key[] {Key.create("VARS_TO_MAKE_FINAL"), Key.create("VARS_TO_TRANSFORM"), Key.create("???")};
 
-  public VariableAccessFromInnerClassFix(@NotNull PsiVariable variable, @NotNull PsiClass aClass) {
+  public VariableAccessFromInnerClassFix(@NotNull PsiVariable variable, @NotNull PsiElement element) {
     myVariable = variable;
-    myClass = aClass;
+    myContext = element;
     myFixType = getQuickFixType(variable);
     if (myFixType == -1) return;
 
@@ -87,21 +87,21 @@
 
   @Override
   public boolean isAvailable(@NotNull Project project, Editor editor, PsiFile file) {
-    return myClass.isValid() &&
-           myClass.getManager().isInProject(myClass) &&
+    return myContext.isValid() &&
+           myContext.getManager().isInProject(myContext) &&
            myVariable.isValid() &&
            myFixType != -1 &&
            !getVariablesToFix().isEmpty() &&
-           !inOwnInitializer(myVariable, myClass);
+           !inOwnInitializer(myVariable, myContext);
   }
 
-  private static boolean inOwnInitializer(PsiVariable variable, PsiClass aClass) {
-    return PsiTreeUtil.isAncestor(variable, aClass, false);
+  private static boolean inOwnInitializer(PsiVariable variable, PsiElement context) {
+    return PsiTreeUtil.isAncestor(variable, context, false);
   }
 
   @Override
   public void invoke(@NotNull Project project, Editor editor, PsiFile file) {
-    if (!FileModificationService.getInstance().preparePsiElementsForWrite(myClass, myVariable)) return;
+    if (!FileModificationService.getInstance().preparePsiElementsForWrite(myContext, myVariable)) return;
     try {
       switch (myFixType) {
         case MAKE_FINAL:
@@ -131,8 +131,8 @@
 
   @NotNull
   private Collection<PsiVariable> getVariablesToFix() {
-    Map<PsiVariable, Boolean> vars = myClass.getUserData(VARS[myFixType]);
-    if (vars == null) myClass.putUserData(VARS[myFixType], vars = new ConcurrentWeakHashMap<PsiVariable, Boolean>(1));
+    Map<PsiVariable, Boolean> vars = myContext.getUserData(VARS[myFixType]);
+    if (vars == null) myContext.putUserData(VARS[myFixType], vars = new ConcurrentWeakHashMap<PsiVariable, Boolean>(1));
     final Map<PsiVariable, Boolean> finalVars = vars;
     return new AbstractCollection<PsiVariable>() {
       @Override
@@ -164,7 +164,7 @@
   private void makeArray(PsiVariable variable) throws IncorrectOperationException {
     PsiType type = variable.getType();
 
-    PsiElementFactory factory = JavaPsiFacade.getInstance(myClass.getProject()).getElementFactory();
+    PsiElementFactory factory = JavaPsiFacade.getInstance(myContext.getProject()).getElementFactory();
     PsiType newType = type.createArrayType();
 
     PsiDeclarationStatement variableDeclarationStatement;
@@ -195,9 +195,9 @@
   }
 
   private void copyToFinal() throws IncorrectOperationException {
-    PsiManager psiManager = myClass.getManager();
+    PsiManager psiManager = myContext.getManager();
     PsiElementFactory factory = JavaPsiFacade.getInstance(psiManager.getProject()).getElementFactory();
-    PsiExpression initializer = factory.createExpressionFromText(myVariable.getName(), myClass);
+    PsiExpression initializer = factory.createExpressionFromText(myVariable.getName(), myContext);
     String newName = suggestNewName(psiManager.getProject(), myVariable);
     PsiType type = myVariable.getType();
     PsiDeclarationStatement copyDecl = factory.createVariableDeclarationStatement(newName, type, initializer);
@@ -206,7 +206,7 @@
     PsiElement statement = getStatementToInsertBefore();
     if (statement == null) return;
     PsiExpression newExpression = factory.createExpressionFromText(newName, myVariable);
-    replaceReferences(myClass, myVariable, newExpression);
+    replaceReferences(myContext, myVariable, newExpression);
     if (RefactoringUtil.isLoopOrIf(statement.getParent())) {
       RefactoringUtil.putStatementInLoopBody(copyDecl, statement.getParent(), statement);
     } else {
@@ -219,7 +219,7 @@
                                   ? ((PsiParameter)myVariable).getDeclarationScope() : PsiUtil.getVariableCodeBlock(myVariable, null);
     if (declarationScope == null) return null;
 
-    PsiElement statement = myClass;
+    PsiElement statement = myContext;
     nextInnerClass:
     do {
       statement = RefactoringUtil.getParentStatement(statement, false);
@@ -291,11 +291,11 @@
     int type = MAKE_FINAL;
     for (PsiReferenceExpression expression : outerReferences) {
       // if it happens that variable referenced from another inner class, make sure it can be make final from there
-      PsiClass innerClass = HighlightControlFlowUtil.getInnerClassVariableReferencedFrom(variable, expression);
+      PsiElement innerScope = HighlightControlFlowUtil.getInnerClassVariableReferencedFrom(variable, expression);
 
-      if (innerClass != null) {
+      if (innerScope != null) {
         int thisType = MAKE_FINAL;
-        if (writtenInside(variable, innerClass)) {
+        if (writtenInside(variable, innerScope)) {
           // cannot make parameter array
           if (variable instanceof PsiParameter) return -1;
           thisType = MAKE_ARRAY;
diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/CaseColonFixer.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/CaseColonFixer.java
new file mode 100644
index 0000000..de32027
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/CaseColonFixer.java
@@ -0,0 +1,35 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.editorActions.smartEnter;
+
+import com.intellij.openapi.editor.Editor;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiSwitchLabelStatement;
+import com.intellij.util.IncorrectOperationException;
+
+/**
+ * @author peter
+ */
+public class CaseColonFixer implements Fixer {
+  @Override
+  public void apply(Editor editor, JavaSmartEnterProcessor processor, PsiElement psiElement) throws IncorrectOperationException {
+    if (psiElement instanceof PsiSwitchLabelStatement &&
+        ((PsiSwitchLabelStatement)psiElement).getCaseValue() != null &&
+        !psiElement.getText().endsWith(":")) {
+      editor.getDocument().insertString(psiElement.getTextRange().getEndOffset(), ":");
+    }
+  }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/JavaSmartEnterProcessor.java b/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/JavaSmartEnterProcessor.java
index 4df807f..cea0711 100644
--- a/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/JavaSmartEnterProcessor.java
+++ b/java/java-impl/src/com/intellij/codeInsight/editorActions/smartEnter/JavaSmartEnterProcessor.java
@@ -58,6 +58,7 @@
     fixers.add(new WhileConditionFixer());
     fixers.add(new CatchDeclarationFixer());
     fixers.add(new SwitchExpressionFixer());
+    fixers.add(new CaseColonFixer());
     fixers.add(new DoWhileConditionFixer());
     fixers.add(new BlockBraceFixer());
     fixers.add(new MissingIfBranchesFixer());
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 5f95da05..c8a6cfa 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
@@ -547,8 +547,8 @@
 
   @NotNull
   @Override
-  public IntentionAction createVariableAccessFromInnerClassFix(@NotNull PsiVariable variable, @NotNull PsiClass aClass) {
-    return new VariableAccessFromInnerClassFix(variable, aClass);
+  public IntentionAction createVariableAccessFromInnerClassFix(@NotNull PsiVariable variable, @NotNull PsiElement scope) {
+    return new VariableAccessFromInnerClassFix(variable, scope);
   }
 
   @NotNull
diff --git a/java/java-impl/src/com/intellij/codeInsight/lookup/VariableLookupItem.java b/java/java-impl/src/com/intellij/codeInsight/lookup/VariableLookupItem.java
index 9f23dba0..21e32a3 100644
--- a/java/java-impl/src/com/intellij/codeInsight/lookup/VariableLookupItem.java
+++ b/java/java-impl/src/com/intellij/codeInsight/lookup/VariableLookupItem.java
@@ -123,7 +123,10 @@
     }
 
     ref = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset() - 1, PsiReferenceExpression.class, false);
-    makeVariableFinalIfNeeded(context, ref);
+    PsiElement target = ref == null ? null : ref.resolve();
+    if (target instanceof PsiLocalVariable || target instanceof PsiParameter) {
+      makeFinalIfNeeded(context, (PsiVariable)target);
+    }
 
     final char completionChar = context.getCompletionChar();
     if (completionChar == '=') {
@@ -151,22 +154,16 @@
     }
   }
 
-  private static void makeVariableFinalIfNeeded(InsertionContext context, @Nullable PsiReferenceExpression ref) {
+  public static void makeFinalIfNeeded(@NotNull InsertionContext context, @NotNull PsiVariable variable) {
+    PsiElement place = context.getFile().findElementAt(context.getTailOffset() - 1);
     if (!Registry.is("java.completion.make.outer.variables.final") ||
-        ref == null || PsiUtil.isLanguageLevel8OrHigher(ref) || JspPsiUtil.isInJspFile(ref)) {
+        place == null || PsiUtil.isLanguageLevel8OrHigher(place) || JspPsiUtil.isInJspFile(place)) {
       return;
     }
 
-    PsiElement target = ref.resolve();
-    if (target instanceof PsiLocalVariable || target instanceof PsiParameter) {
-      PsiClass placeClass = PsiTreeUtil.findElementOfClassAtOffset(context.getFile(), context.getTailOffset() - 1, PsiClass.class, false);
-      if (placeClass != null && !PsiTreeUtil.isAncestor(placeClass, target, true) &&
-          !HighlightControlFlowUtil.isReassigned((PsiVariable)target, new HashMap<PsiElement, Collection<ControlFlowUtil.VariableInfo>>())) {
-        PsiModifierList modifierList = ((PsiVariable)target).getModifierList();
-        if (modifierList != null) {
-          modifierList.setModifierProperty(PsiModifier.FINAL, true);
-        }
-      }
+    if (HighlightControlFlowUtil.getInnerClassVariableReferencedFrom(variable, place) != null &&
+        !HighlightControlFlowUtil.isReassigned(variable, new HashMap<PsiElement, Collection<ControlFlowUtil.VariableInfo>>())) {
+      PsiUtil.setModifierProperty(variable, PsiModifier.FINAL, true);
     }
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateCompletionContributor.java
index b6a7b5f..eb6b585 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateCompletionContributor.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateCompletionContributor.java
@@ -21,34 +21,19 @@
 import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
 import com.intellij.codeInsight.template.postfix.templates.PostfixLiveTemplate;
 import com.intellij.openapi.editor.Editor;
-import com.intellij.patterns.ElementPattern;
-import com.intellij.psi.JavaTokenType;
-import com.intellij.psi.PsiElement;
+import com.intellij.patterns.PlatformPatterns;
 import com.intellij.psi.PsiFile;
-import com.intellij.psi.impl.source.tree.ElementType;
-import com.intellij.psi.tree.TokenSet;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import static com.intellij.patterns.PsiJavaPatterns.psiElement;
-import static com.intellij.patterns.StandardPatterns.string;
-
 public class PostfixTemplateCompletionContributor extends CompletionContributor {
-  private static final TokenSet SUITABLE_ELEMENTS = TokenSet.orSet(ElementType.KEYWORD_BIT_SET,
-                                                                   ElementType.LITERAL_BIT_SET,
-                                                                   TokenSet.create(JavaTokenType.IDENTIFIER));
-
   public PostfixTemplateCompletionContributor() {
-    extend(CompletionType.BASIC, identifierAfterDot(), new PostfixTemplatesCompletionProvider());
+    extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new PostfixTemplatesCompletionProvider());
   }
 
   @Nullable
-  public static PostfixLiveTemplate getPostfixLiveTemplate(@NotNull PsiFile file,  @NotNull Editor editor) {
+  public static PostfixLiveTemplate getPostfixLiveTemplate(@NotNull PsiFile file, @NotNull Editor editor) {
     PostfixLiveTemplate postfixLiveTemplate = CustomLiveTemplate.EP_NAME.findExtension(PostfixLiveTemplate.class);
     return postfixLiveTemplate != null && TemplateManagerImpl.isApplicable(postfixLiveTemplate, editor, file) ? postfixLiveTemplate : null;
   }
-
-  private static ElementPattern<? extends PsiElement> identifierAfterDot() {
-    return psiElement().withElementType(SUITABLE_ELEMENTS).afterLeaf(psiElement().withText(string().contains(".")));
-  }
 }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupElement.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupElement.java
index 0aeba2b..c01f607 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupElement.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplateLookupElement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -19,7 +19,8 @@
 import com.intellij.codeInsight.template.impl.CustomLiveTemplateLookupElement;
 import com.intellij.codeInsight.template.postfix.templates.PostfixLiveTemplate;
 import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate;
-import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 
 public class PostfixTemplateLookupElement extends CustomLiveTemplateLookupElement {
@@ -30,7 +31,7 @@
                                       @NotNull PostfixTemplate postfixTemplate,
                                       @NotNull String templateKey,
                                       boolean sudden) {
-    super(liveTemplate, templateKey, postfixTemplate.getPresentableName(), postfixTemplate.getDescription(), sudden, true);
+    super(liveTemplate, templateKey, StringUtil.trimStart(templateKey, "."), postfixTemplate.getDescription(), sudden, true);
     myTemplate = postfixTemplate;
   }
 
@@ -43,15 +44,11 @@
   public void renderElement(LookupElementPresentation presentation) {
     super.renderElement(presentation);
     if (sudden) {
-      presentation.setTailText(" " + arrow() + " " + myTemplate.getExample());
+      presentation.setTailText(" " + UIUtil.rightArrow() + " " + myTemplate.getExample());
     }
     else {
       presentation.setTypeText(myTemplate.getExample());
       presentation.setTypeGrayed(true);
     }
   }
-
-  private static String arrow() {
-    return SystemInfo.isMac ? "→" : "->";
-  }
 }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java
index db253a6..ec0aead 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/completion/PostfixTemplatesCompletionProvider.java
@@ -19,6 +19,7 @@
 import com.intellij.codeInsight.completion.CompletionProvider;
 import com.intellij.codeInsight.completion.CompletionResultSet;
 import com.intellij.codeInsight.completion.PrefixMatcher;
+import com.intellij.codeInsight.template.CustomTemplateCallback;
 import com.intellij.codeInsight.template.impl.LiveTemplateCompletionContributor;
 import com.intellij.codeInsight.template.postfix.settings.PostfixTemplatesSettings;
 import com.intellij.codeInsight.template.postfix.templates.PostfixLiveTemplate;
@@ -42,11 +43,12 @@
     PostfixLiveTemplate postfixLiveTemplate = getPostfixLiveTemplate(parameters.getOriginalFile(), parameters.getEditor());
     if (postfixLiveTemplate != null) {
       postfixLiveTemplate.addCompletions(parameters, result.withPrefixMatcher(new MyPrefixMatcher(result.getPrefixMatcher().getPrefix())));
-      CharSequence documentContent = parameters.getEditor().getDocument().getCharsSequence();
-      String possibleKey = postfixLiveTemplate.computeTemplateKeyWithoutContextChecking(documentContent, parameters.getOffset());
+      String possibleKey = postfixLiveTemplate.computeTemplateKeyWithoutContextChecking(
+        new CustomTemplateCallback(parameters.getEditor(), parameters.getOriginalFile(), false));
       if (possibleKey != null) {
         result = result.withPrefixMatcher(possibleKey);
-        result.restartCompletionOnPrefixChange(StandardPatterns.string().oneOf(postfixLiveTemplate.getAllTemplateKeys()));
+        result.restartCompletionOnPrefixChange(
+          StandardPatterns.string().oneOf(postfixLiveTemplate.getAllTemplateKeys(parameters.getOriginalFile(), parameters.getOffset())));
       }
     }
   }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java
index 75c7d93..90d4eed 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesConfigurable.java
@@ -19,7 +19,11 @@
 import com.intellij.codeInsight.CodeInsightBundle;
 import com.intellij.codeInsight.template.impl.LiveTemplateCompletionContributor;
 import com.intellij.codeInsight.template.impl.TemplateSettings;
+import com.intellij.codeInsight.template.postfix.templates.LanguagePostfixTemplate;
 import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate;
+import com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider;
+import com.intellij.lang.LanguageExtensionPoint;
+import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.openapi.options.Configurable;
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SearchableConfigurable;
@@ -34,8 +38,9 @@
 import javax.swing.event.ChangeEvent;
 import javax.swing.event.ChangeListener;
 import java.awt.*;
-import java.util.*;
+import java.util.Comparator;
 import java.util.List;
+import java.util.Map;
 
 public class PostfixTemplatesConfigurable implements SearchableConfigurable, EditorOptionsProvider, Configurable.NoScroll {
   @Nullable
@@ -61,7 +66,14 @@
     }
 
     myTemplatesSettings = settings;
-    List<PostfixTemplate> templates = Arrays.asList(PostfixTemplate.EP_NAME.getExtensions());
+
+    LanguageExtensionPoint[] extensions = new ExtensionPointName<LanguageExtensionPoint>(LanguagePostfixTemplate.EP_NAME).getExtensions();
+
+    List<PostfixTemplate> templates = ContainerUtil.newArrayList();
+    for (LanguageExtensionPoint extension : extensions) {
+      templates.addAll(((PostfixTemplateProvider)extension.getInstance()).getTemplates());
+    }
+
     ContainerUtil.sort(templates, new Comparator<PostfixTemplate>() {
       @Override
       public int compare(PostfixTemplate o1, PostfixTemplate o2) {
@@ -184,7 +196,7 @@
   private static String shortcutToString(char shortcut) {
     if (shortcut == TemplateSettings.SPACE_CHAR) {
       return SPACE;
-    } 
+    }
     if (shortcut == TemplateSettings.ENTER_CHAR) {
       return ENTER;
     }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesListPanel.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesListPanel.java
index 0c21e04b..4ecc8c0 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesListPanel.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/settings/PostfixTemplatesListPanel.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.settings;
 
 import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate;
@@ -29,7 +44,7 @@
       @NotNull
       @Override
       public String fun(@NotNull PostfixTemplate template) {
-        return template.getKey().replaceFirst(".", "");
+        return template.getKey().replaceFirst("\\.", "");
       }
     };
 
@@ -114,7 +129,9 @@
   public void setState(@NotNull Map<String, Boolean> templatesState) {
     myTemplatesState.clear();
     for (Map.Entry<String, Boolean> entry : templatesState.entrySet()) {
-      myTemplatesState.put(entry.getKey(), entry.getValue());
+      if (!entry.getValue()) {
+        myTemplatesState.put(entry.getKey(), entry.getValue());
+      }
     }
   }
 
@@ -172,7 +189,13 @@
 
     @Override
     public void setValue(@NotNull PostfixTemplate template, Boolean value) {
-      myTemplatesState.put(template.getKey(), value);
+      String key = template.getKey();
+      if (value) {
+        myTemplatesState.remove(key);
+      }
+      else {
+        myTemplatesState.put(key, value);
+      }
     }
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/BooleanPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/BooleanPostfixTemplate.java
index ab6f90e..f8700be 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/BooleanPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/BooleanPostfixTemplate.java
@@ -28,7 +28,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression topmostExpression = getTopmostExpression(context);
+    PsiExpression topmostExpression = PostfixTemplatesUtils.getTopmostExpression(context);
     return topmostExpression != null && PostfixTemplatesUtils.isBoolean(topmostExpression.getType());
   }
 }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ElseStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ElseStatementPostfixTemplate.java
index 3718745..a148a1b 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ElseStatementPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ElseStatementPostfixTemplate.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
 
 import com.intellij.codeInsight.CodeInsightServicesUtil;
@@ -15,7 +30,7 @@
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     assert expression != null;
     PsiExpression invertedExpression = (PsiExpression)expression.replace(CodeInsightServicesUtil.invertCondition(expression));
     TextRange range = PostfixTemplatesUtils.ifStatement(invertedExpression.getProject(), editor, invertedExpression);
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ExpressionPostfixTemplateWithChooser.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ExpressionPostfixTemplateWithChooser.java
index 8de5365..3bd7928 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ExpressionPostfixTemplateWithChooser.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ExpressionPostfixTemplateWithChooser.java
@@ -42,6 +42,13 @@
     super(name, description, example);
   }
 
+  protected ExpressionPostfixTemplateWithChooser(@NotNull String name,
+                                                 @NotNull String key,
+                                                 @NotNull String description,
+                                                 @NotNull String example) {
+    super(name, key, description, example);
+  }
+
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
     return !getExpressions(context, copyDocument, newOffset).isEmpty();
@@ -75,20 +82,22 @@
           }
         },
         new PsiExpressionTrimRenderer.RenderFunction(),
-        "Expressions", 0, ScopeHighlighter.NATURAL_RANGER);
+        "Expressions", 0, ScopeHighlighter.NATURAL_RANGER
+      );
     }
   }
 
   @NotNull
   protected List<PsiExpression> getExpressions(@NotNull PsiElement context, @NotNull Document document, final int offset) {
-    List<PsiExpression> expressions = ContainerUtil.filter(IntroduceVariableBase.collectExpressions(context.getContainingFile(), document, 
-                                                                                                    Math.max(offset - 1, 0), false), 
+    List<PsiExpression> expressions = ContainerUtil.filter(IntroduceVariableBase.collectExpressions(context.getContainingFile(), document,
+                                                                                                    Math.max(offset - 1, 0), false),
                                                            new Condition<PsiExpression>() {
                                                              @Override
                                                              public boolean value(PsiExpression expression) {
                                                                return expression.getTextRange().getEndOffset() == offset;
                                                              }
-                                                           });
+                                                           }
+    );
     return ContainerUtil.filter(expressions.isEmpty() ? maybeTopmostExpression(context) : expressions, getTypeCondition());
   }
 
@@ -100,7 +109,7 @@
 
   @NotNull
   private static List<PsiExpression> maybeTopmostExpression(@NotNull PsiElement context) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     PsiType type = expression != null ? expression.getType() : null;
     if (type == null || PsiType.VOID.equals(type)) return ContainerUtil.emptyList();
     return ContainerUtil.createMaybeSingletonList(expression);
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java
index c353c8d..bf025d1 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForIndexedPostfixTemplate.java
@@ -37,7 +37,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     return expr != null && (PostfixTemplatesUtils.isNumber(expr.getType()) ||
                             PostfixTemplatesUtils.isArray(expr.getType()) ||
                             PostfixTemplatesUtils.isIterable(expr.getType()));
@@ -45,7 +45,7 @@
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     if (expr == null) {
       PostfixTemplatesUtils.showErrorHint(context.getProject(), editor);
       return;
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java
index aabf47c..72bbb4f 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ForeachPostfixTemplate.java
@@ -37,13 +37,13 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     return expr != null && (PostfixTemplatesUtils.isArray(expr.getType()) || PostfixTemplatesUtils.isIterable(expr.getType()));
   }
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     if (expr == null) return;
     Project project = context.getProject();
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java
index 5d99745..a799f39 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/FormatPostfixTemplate.java
@@ -36,7 +36,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     PsiType type = expr != null ? expr.getType() : null;
     return expr != null && type != null && CommonClassNames.JAVA_LANG_STRING.equals(type.getCanonicalText());
   }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IfStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IfStatementPostfixTemplate.java
index 9610ec5..8122474 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IfStatementPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/IfStatementPostfixTemplate.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
 
 import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
@@ -14,7 +29,7 @@
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull final Editor editor) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     assert expression != null;
     TextRange range = PostfixTemplatesUtils.ifStatement(expression.getProject(), editor, expression);
     if (range != null) {
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/InstanceofExpressionPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/InstanceofExpressionPostfixTemplate.java
index 8c5b58e..1884d09 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/InstanceofExpressionPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/InstanceofExpressionPostfixTemplate.java
@@ -19,7 +19,6 @@
 import com.intellij.codeInsight.lookup.LookupElement;
 import com.intellij.codeInsight.lookup.PsiTypeLookupItem;
 import com.intellij.codeInsight.template.*;
-import com.intellij.codeInsight.template.postfix.util.Aliases;
 import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
@@ -35,25 +34,30 @@
 import java.util.LinkedHashSet;
 import java.util.Set;
 
-@Aliases(".inst")
 public class InstanceofExpressionPostfixTemplate extends PostfixTemplate {
+
   public InstanceofExpressionPostfixTemplate() {
-    super("instanceof", "Surrounds expression with instanceof", "expr instanceof SomeType ? ((SomeType) expr). : null");
+    this("instanceof");
+  }
+
+  public InstanceofExpressionPostfixTemplate(String alias) {
+    super(alias, "Surrounds expression with instanceof", "expr instanceof SomeType ? ((SomeType) expr). : null");
   }
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    return PostfixTemplatesUtils.isNotPrimitiveTypeExpression(getTopmostExpression(context));
+    return PostfixTemplatesUtils.isNotPrimitiveTypeExpression(PostfixTemplatesUtils.getTopmostExpression(context));
   }
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     if (!PostfixTemplatesUtils.isNotPrimitiveTypeExpression(expression)) return;
     surroundExpression(context.getProject(), editor, expression);
   }
 
-  private static void surroundExpression(@NotNull Project project, @NotNull Editor editor, @NotNull PsiExpression expr) throws IncorrectOperationException {
+  private static void surroundExpression(@NotNull Project project, @NotNull Editor editor, @NotNull PsiExpression expr)
+    throws IncorrectOperationException {
     assert expr.isValid();
     PsiType[] types = GuessManager.getInstance(project).guessTypeToCast(expr);
     final boolean parenthesesNeeded = expr instanceof PsiPolyadicExpression ||
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java
new file mode 100644
index 0000000..2ee071b
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/JavaPostfixTemplateProvider.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
+
+import com.intellij.codeInsight.completion.CompletionInitializationContext;
+import com.intellij.codeInsight.completion.JavaCompletionContributor;
+import com.intellij.codeInsight.template.CustomTemplateCallback;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.util.Ref;
+import com.intellij.psi.PsiDocumentManager;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import com.intellij.util.containers.ContainerUtil;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Set;
+
+
+public class JavaPostfixTemplateProvider implements PostfixTemplateProvider {
+  private final Set<PostfixTemplate> templates;
+
+
+  public JavaPostfixTemplateProvider() {
+    templates = ContainerUtil.newHashSet(new AssertStatementPostfixTemplate(),
+                                         new CastExpressionPostfixTemplate(),
+                                         new ElseStatementPostfixTemplate(),
+                                         new ForAscendingPostfixTemplate(),
+                                         new ForDescendingPostfixTemplate(),
+                                         new ForeachPostfixTemplate(),
+                                         new FormatPostfixTemplate(),
+                                         new IfStatementPostfixTemplate(),
+                                         new InstanceofExpressionPostfixTemplate(),
+                                         new InstanceofExpressionPostfixTemplate("inst"),
+                                         new IntroduceFieldPostfixTemplate(),
+                                         new IntroduceVariablePostfixTemplate(),
+                                         new IsNullCheckPostfixTemplate(),
+                                         new NotExpressionPostfixTemplate(),
+                                         new NotExpressionPostfixTemplate("!"),
+                                         new NotNullCheckPostfixTemplate(),
+                                         new NotNullCheckPostfixTemplate("nn"),
+                                         new ParenthesizedExpressionPostfixTemplate(),
+                                         new ReturnStatementPostfixTemplate(),
+                                         new SoutPostfixTemplate(),
+                                         new SwitchStatementPostfixTemplate(),
+                                         new SynchronizedStatementPostfixTemplate(),
+                                         new ThrowExceptionPostfixTemplate(),
+                                         new TryStatementPostfixTemplate(),
+                                         new TryWithResourcesPostfixTemplate(),
+                                         new WhileStatementPostfixTemplate());
+  }
+
+  @NotNull
+  @Override
+  public Set<PostfixTemplate> getTemplates() {
+    return templates;
+  }
+
+  @Override
+  public boolean isTerminalSymbol(char currentChar) {
+    return currentChar == '.' || currentChar == '!';
+  }
+
+  @NotNull
+  @Override
+  public PsiElement preExpand(@NotNull Editor editor, @NotNull PsiElement context, int offset, @NotNull final String key) {
+
+    return addSemicolonIfNeeded(editor, editor.getDocument(), context, offset - key.length());
+  }
+
+  @NotNull
+  @Override
+  public PsiFile preCheck(@NotNull Editor editor, @NotNull PsiFile copyFile, int currentOffset) {
+    Document document = copyFile.getViewProvider().getDocument();
+    assert document != null;
+    CharSequence sequence = document.getCharsSequence();
+    StringBuilder fileContentWithoutKey = new StringBuilder(sequence);
+    if (isSemicolonNeeded(copyFile, editor)) {
+      fileContentWithoutKey.insert(currentOffset, ';');
+      copyFile = PostfixLiveTemplate.copyFile(copyFile, fileContentWithoutKey);
+    }
+
+    return copyFile;
+  }
+
+  @NotNull
+  private static PsiElement addSemicolonIfNeeded(@NotNull final Editor editor,
+                                                 @NotNull final Document document,
+                                                 @NotNull final PsiElement context,
+                                                 final int offset) {
+    ApplicationManager.getApplication().assertIsDispatchThread();
+
+    final Ref<PsiElement> newContext = Ref.create(context);
+    final PsiFile file = context.getContainingFile();
+    if (isSemicolonNeeded(file, editor)) {
+      ApplicationManager.getApplication().runWriteAction(new Runnable() {
+        @Override
+        public void run() {
+          CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
+            public void run() {
+              document.insertString(offset, ";");
+              PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
+              newContext.set(CustomTemplateCallback.getContext(file, offset - 1));
+            }
+          });
+        }
+      });
+    }
+    return newContext.get();
+  }
+
+  private static boolean isSemicolonNeeded(@NotNull PsiFile file, @NotNull Editor editor) {
+    return JavaCompletionContributor.semicolonNeeded(editor, file, CompletionInitializationContext.calcStartOffset(editor));
+  }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/LanguagePostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/LanguagePostfixTemplate.java
new file mode 100644
index 0000000..2360d97
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/LanguagePostfixTemplate.java
@@ -0,0 +1,27 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
+
+import com.intellij.lang.LanguageExtension;
+
+public class LanguagePostfixTemplate extends LanguageExtension<PostfixTemplateProvider> {
+  public static final LanguagePostfixTemplate LANG_EP = new LanguagePostfixTemplate();
+  public static final String EP_NAME = "com.intellij.codeInsight.template.postfixTemplateProvider";
+
+  private LanguagePostfixTemplate() {
+    super(EP_NAME);
+  }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NonVoidPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NonVoidPostfixTemplate.java
index 906a943..09757e5 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NonVoidPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NonVoidPostfixTemplate.java
@@ -28,7 +28,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     return expr != null && PostfixTemplatesUtils.isNonVoid(expr.getType());
   }
 }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotExpressionPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotExpressionPostfixTemplate.java
index 9900c0a..e2e3db8 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotExpressionPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotExpressionPostfixTemplate.java
@@ -16,14 +16,12 @@
 package com.intellij.codeInsight.template.postfix.templates;
 
 import com.intellij.codeInsight.CodeInsightServicesUtil;
-import com.intellij.codeInsight.template.postfix.util.Aliases;
 import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.Condition;
 import com.intellij.psi.PsiExpression;
 import org.jetbrains.annotations.NotNull;
 
-@Aliases("!")
 public class NotExpressionPostfixTemplate extends ExpressionPostfixTemplateWithChooser {
   private static final Condition<PsiExpression> BOOLEAN_TYPE_CONDITION = new Condition<PsiExpression>() {
     @Override
@@ -36,6 +34,10 @@
     super("not", "Negates boolean expression", "!expr");
   }
 
+  public NotExpressionPostfixTemplate(String alias) {
+    super(alias, alias, "Negates boolean expression", "!expr");
+  }
+
   @Override
   protected void doIt(@NotNull Editor editor, @NotNull PsiExpression expression) {
     expression.replace(CodeInsightServicesUtil.invertCondition(expression));
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotNullCheckPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotNullCheckPostfixTemplate.java
index e4bde32..ea2480f 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotNullCheckPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NotNullCheckPostfixTemplate.java
@@ -1,12 +1,30 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
 
-import com.intellij.codeInsight.template.postfix.util.Aliases;
 import org.jetbrains.annotations.NotNull;
 
-@Aliases(".nn")
 public class NotNullCheckPostfixTemplate extends NullCheckPostfixTemplate {
+
   public NotNullCheckPostfixTemplate() {
-    super("notnull", "Checks expression to be not-null", "if (expr != null)");
+    this("notnull");
+  }
+
+  public NotNullCheckPostfixTemplate(String alias) {
+    super(alias, "Checks expression to be not-null", "if (expr != null)");
   }
 
   @NotNull
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NullCheckPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NullCheckPostfixTemplate.java
index 6a9b6769..c7ad21b 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NullCheckPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/NullCheckPostfixTemplate.java
@@ -39,12 +39,12 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    return PostfixTemplatesUtils.isNotPrimitiveTypeExpression(getTopmostExpression(context));
+    return PostfixTemplatesUtils.isNotPrimitiveTypeExpression(PostfixTemplatesUtils.getTopmostExpression(context));
   }
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     if (!PostfixTemplatesUtils.isNotPrimitiveTypeExpression(expr)) return;
 
     Project project = expr.getProject();
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java
index a165dcb..8fd2e72 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixLiveTemplate.java
@@ -15,17 +15,15 @@
  */
 package com.intellij.codeInsight.template.postfix.templates;
 
-import com.intellij.codeInsight.completion.CompletionInitializationContext;
-import com.intellij.codeInsight.completion.JavaCompletionContributor;
+import com.google.common.collect.Sets;
 import com.intellij.codeInsight.template.CustomLiveTemplateBase;
 import com.intellij.codeInsight.template.CustomTemplateCallback;
 import com.intellij.codeInsight.template.impl.CustomLiveTemplateLookupElement;
 import com.intellij.codeInsight.template.impl.TemplateSettings;
 import com.intellij.codeInsight.template.postfix.completion.PostfixTemplateLookupElement;
 import com.intellij.codeInsight.template.postfix.settings.PostfixTemplatesSettings;
-import com.intellij.codeInsight.template.postfix.util.Aliases;
 import com.intellij.featureStatistics.FeatureUsageTracker;
-import com.intellij.lang.java.JavaLanguage;
+import com.intellij.lang.Language;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.command.undo.UndoConstants;
@@ -33,7 +31,6 @@
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.util.Condition;
-import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiDocumentManager;
@@ -42,71 +39,41 @@
 import com.intellij.psi.PsiFileFactory;
 import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.util.containers.ContainerUtil;
-import org.jetbrains.annotations.Contract;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.util.Collection;
-import java.util.HashMap;
-import java.util.Map;
 import java.util.Set;
 
+import static com.intellij.codeInsight.template.postfix.templates.LanguagePostfixTemplate.LANG_EP;
+
 public class PostfixLiveTemplate extends CustomLiveTemplateBase {
   public static final String POSTFIX_TEMPLATE_ID = "POSTFIX_TEMPLATE_ID";
-
   private static final Logger LOG = Logger.getInstance(PostfixLiveTemplate.class);
-  private final HashMap<String, PostfixTemplate> myTemplates = ContainerUtil.newHashMap();
 
-  public PostfixLiveTemplate() {
-    for (PostfixTemplate template : PostfixTemplate.EP_NAME.getExtensions()) {
-      register(template.getKey(), template);
-      Aliases aliases = template.getClass().getAnnotation(Aliases.class);
-      if (aliases != null) {
-        for (String key : aliases.value()) {
-          register(key, template);
-        }
-      }
+  @NotNull
+  public Set<String> getAllTemplateKeys(PsiFile file, int offset) {
+    Set<String> keys = Sets.newHashSet();
+    Language language = PsiUtilCore.getLanguageAtOffset(file, offset);
+    for (PostfixTemplateProvider provider : LANG_EP.allForLanguage(language)) {
+      keys.addAll(getKeys(provider));
     }
-  }
-
-  private void register(@NotNull String key, @NotNull PostfixTemplate template) {
-    PostfixTemplate registered = myTemplates.put(key, template);
-    if (registered != null) {
-      LOG.error("Can't register postfix template. Duplicated key: " + template.getKey());
-    }
+    return keys;
   }
 
   @Nullable
-  @Override
-  public String computeTemplateKey(@NotNull CustomTemplateCallback callback) {
-    Editor editor = callback.getEditor();
-    String key = computeTemplateKeyWithoutContextChecking(editor.getDocument().getCharsSequence(), editor.getCaretModel().getOffset());
-    if (key == null) return null;
-    return isApplicableTemplate(getTemplateByKey(key), key, callback.getContext().getContainingFile(), editor) ? key : null;
-  }
-  
-  @Nullable
-  @Override
-  public String computeTemplateKeyWithoutContextChecking(@NotNull CustomTemplateCallback callback) {
-    Editor editor = callback.getEditor();
-    return computeTemplateKeyWithoutContextChecking(editor.getDocument().getCharsSequence(), editor.getCaretModel().getOffset());
-  }
-
-  @Override
-  public boolean supportsMultiCaret() {
-    return false;
-  }
-
-  @Nullable
-  public String computeTemplateKeyWithoutContextChecking(@NotNull CharSequence documentContent, int currentOffset) {
+  private static String computeTemplateKeyWithoutContextChecking(@NotNull PostfixTemplateProvider provider,
+                                                                 @NotNull CharSequence documentContent,
+                                                                 int currentOffset) {
     int startOffset = currentOffset;
     if (documentContent.length() < startOffset) {
       return null;
     }
+
     while (startOffset > 0) {
       char currentChar = documentContent.charAt(startOffset - 1);
       if (!Character.isJavaIdentifierPart(currentChar)) {
-        if (currentChar != '.' && currentChar != '!') {
+        if (!provider.isTerminalSymbol(currentChar)) {
           return null;
         }
         startOffset--;
@@ -117,23 +84,64 @@
     return String.valueOf(documentContent.subSequence(startOffset, currentOffset));
   }
 
+  @Nullable
+  @Override
+  public String computeTemplateKey(@NotNull CustomTemplateCallback callback) {
+    Editor editor = callback.getEditor();
+    CharSequence charsSequence = editor.getDocument().getCharsSequence();
+    int offset = editor.getCaretModel().getOffset();
+    for (PostfixTemplateProvider provider : LANG_EP.allForLanguage(getLanguage(callback))) {
+      String key = computeTemplateKeyWithoutContextChecking(provider, charsSequence, offset);
+      if (key != null && isApplicableTemplate(provider, key, callback.getFile(), editor)) {
+        return key;
+      }
+    }
+    return null;
+  }
+
+  @Nullable
+  @Override
+  public String computeTemplateKeyWithoutContextChecking(@NotNull CustomTemplateCallback callback) {
+    Editor editor = callback.getEditor();
+    int currentOffset = editor.getCaretModel().getOffset();
+    for (PostfixTemplateProvider provider : LANG_EP.allForLanguage(getLanguage(callback))) {
+      String key = computeTemplateKeyWithoutContextChecking(provider, editor.getDocument().getCharsSequence(), currentOffset);
+      if (key != null) return key;
+    }
+    return null;
+  }
+
+  @Override
+  public boolean supportsMultiCaret() {
+    return false;
+  }
+
   @Override
   public void expand(@NotNull final String key, @NotNull final CustomTemplateCallback callback) {
     ApplicationManager.getApplication().assertIsDispatchThread();
-
     FeatureUsageTracker.getInstance().triggerFeatureUsed("editing.completion.postfix");
 
-    final PostfixTemplate template = getTemplateByKey(key);
-    final Editor editor = callback.getEditor();
-    final PsiFile file = callback.getContext().getContainingFile();
-    if (isApplicableTemplate(template, key, file, editor)) {
-      int currentOffset = editor.getCaretModel().getOffset();
-      PsiElement newContext = deleteTemplateKey(file, editor.getDocument(), currentOffset, key);
-      newContext = addSemicolonIfNeeded(editor, editor.getDocument(), newContext, currentOffset - key.length());
-      expandTemplate(template, editor, newContext);
+    Editor editor = callback.getEditor();
+    for (PostfixTemplateProvider provider : LANG_EP.allForLanguage(getLanguage(callback))) {
+      PostfixTemplate postfixTemplate = getTemplate(provider, key);
+      if (postfixTemplate != null) {
+        final PsiFile file = callback.getContext().getContainingFile();
+        if (isApplicableTemplate(provider, key, file, editor)) {
+          int currentOffset = editor.getCaretModel().getOffset();
+          PsiElement newContext = deleteTemplateKey(file, editor.getDocument(), currentOffset, key);
+          newContext = provider.preExpand(editor, newContext, currentOffset, key);
+          expandTemplate(postfixTemplate, editor, newContext);
+        }
+        // don't care about errors in multiCaret mode
+        else if (editor.getCaretModel().getAllCarets().size() == 1) {
+          LOG.error("Template not found by key: " + key);
+        }
+        return;
+      }
     }
+
     // don't care about errors in multiCaret mode
-    else if (editor.getCaretModel().getAllCarets().size() == 1) {
+    if (editor.getCaretModel().getAllCarets().size() == 1) {
       LOG.error("Template not found by key: " + key);
     }
   }
@@ -141,11 +149,16 @@
   @Override
   public boolean isApplicable(PsiFile file, int offset, boolean wrapping) {
     PostfixTemplatesSettings settings = PostfixTemplatesSettings.getInstance();
-    if (wrapping  || file == null || settings == null || !settings.isPostfixTemplatesEnabled() ||
-        PsiUtilCore.getLanguageAtOffset(file, offset) != JavaLanguage.INSTANCE) {
+    if (wrapping || file == null || settings == null || !settings.isPostfixTemplatesEnabled()) {
       return false;
     }
-    return StringUtil.isNotEmpty(computeTemplateKeyWithoutContextChecking(file.getText(), offset + 1));
+    Language language = PsiUtilCore.getLanguageAtOffset(file, offset);
+    for (PostfixTemplateProvider provider : LANG_EP.allForLanguage(language)) {
+      if (StringUtil.isNotEmpty(computeTemplateKeyWithoutContextChecking(provider, file.getText(), offset + 1))) {
+        return true;
+      }
+    }
+    return false;
   }
 
   @Override
@@ -177,30 +190,24 @@
 
   @NotNull
   @Override
-  public Collection<? extends CustomLiveTemplateLookupElement> getLookupElements(@NotNull PsiFile file, @NotNull Editor editor, int offset) {
-    String key = computeTemplateKeyWithoutContextChecking(editor.getDocument().getCharsSequence(), offset);
-    if (key != null && editor.getCaretModel().getCaretCount() == 1) {
-      Map<String, CustomLiveTemplateLookupElement> result = ContainerUtil.newHashMap();
-      Condition<PostfixTemplate> isApplicationTemplateFunction = createIsApplicationTemplateFunction(key, file, editor);
-      for (Map.Entry<String, PostfixTemplate> entry : myTemplates.entrySet()) {
-        PostfixTemplate postfixTemplate = entry.getValue();
-        if (entry.getKey().startsWith(key) && isApplicationTemplateFunction.value(postfixTemplate)) {
-          result.put(postfixTemplate.getKey(), new PostfixTemplateLookupElement(this, postfixTemplate, entry.getKey(), false));
+  public Collection<? extends CustomLiveTemplateLookupElement> getLookupElements(@NotNull PsiFile file,
+                                                                                 @NotNull Editor editor,
+                                                                                 int offset) {
+    Collection<CustomLiveTemplateLookupElement> result = ContainerUtil.newHashSet();
+    CustomTemplateCallback callback = new CustomTemplateCallback(editor, file, false);
+    for (PostfixTemplateProvider provider : LANG_EP.allForLanguage(getLanguage(callback))) {
+      String key = computeTemplateKeyWithoutContextChecking(callback);
+      if (key != null && editor.getCaretModel().getCaretCount() == 1) {
+        Condition<PostfixTemplate> isApplicationTemplateFunction = createIsApplicationTemplateFunction(provider, key, file, editor);
+        for (PostfixTemplate postfixTemplate : provider.getTemplates()) {
+          if (isApplicationTemplateFunction.value(postfixTemplate)) {
+            result.add(new PostfixTemplateLookupElement(this, postfixTemplate, postfixTemplate.getKey(), false));
+          }
         }
       }
-      return result.values();
     }
-    return super.getLookupElements(file, editor, offset);
-  }
 
-  @NotNull
-  public Set<String> getAllTemplateKeys() {
-    return myTemplates.keySet();
-  }
-
-  @Nullable
-  public PostfixTemplate getTemplateByKey(@NotNull String key) {
-    return myTemplates.get(key);
+    return result;
   }
 
   private static void expandTemplate(@NotNull final PostfixTemplate template,
@@ -218,56 +225,6 @@
     });
   }
 
-  @Contract("null, _, _, _ -> false")
-  private static boolean isApplicableTemplate(@Nullable PostfixTemplate template, @NotNull String key, @NotNull PsiFile file, @NotNull Editor editor) {
-    return createIsApplicationTemplateFunction(key, file, editor).value(template);
-  }
-  
-  private static Condition<PostfixTemplate> createIsApplicationTemplateFunction(@NotNull String key, @NotNull PsiFile file, @NotNull Editor editor) {
-    int currentOffset = editor.getCaretModel().getOffset();
-    final int newOffset = currentOffset - key.length();
-    CharSequence fileContent = editor.getDocument().getCharsSequence();
-
-    StringBuilder fileContentWithoutKey = new StringBuilder();
-    fileContentWithoutKey.append(fileContent.subSequence(0, newOffset));
-    fileContentWithoutKey.append(fileContent.subSequence(currentOffset, fileContent.length()));
-    PsiFile copyFile = copyFile(file, fileContentWithoutKey);
-    Document copyDocument = copyFile.getViewProvider().getDocument();
-    if (copyDocument == null) {
-      //noinspection unchecked
-      return Condition.FALSE;
-    }
-
-    if (isSemicolonNeeded(copyFile, editor)) {
-      fileContentWithoutKey.insert(newOffset, ';');
-      copyFile = copyFile(file, fileContentWithoutKey);
-      copyDocument = copyFile.getViewProvider().getDocument();
-      if (copyDocument == null) {
-        //noinspection unchecked
-        return Condition.FALSE;
-      }
-    }
-
-    final PsiElement context = CustomTemplateCallback.getContext(copyFile, newOffset > 0 ? newOffset - 1 : newOffset);
-    final Document finalCopyDocument = copyDocument;
-    return new Condition<PostfixTemplate>() {
-      @Override
-      public boolean value(PostfixTemplate template) {
-        return template != null && template.isEnabled() && template.isApplicable(context, finalCopyDocument, newOffset);
-      }
-    };
-  }
-
-  @NotNull
-  private static PsiFile copyFile(@NotNull PsiFile file, @NotNull StringBuilder fileContentWithoutKey) {
-    final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(file.getProject());
-    PsiFile copy = psiFileFactory.createFileFromText(file.getName(), file.getFileType(), fileContentWithoutKey);
-    VirtualFile vFile = copy.getVirtualFile();
-    if (vFile != null) {
-      vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
-    }
-    return copy;
-  }
 
   @NotNull
   private static PsiElement deleteTemplateKey(@NotNull final PsiFile file,
@@ -291,33 +248,81 @@
     return CustomTemplateCallback.getContext(file, startOffset > 0 ? startOffset - 1 : startOffset);
   }
 
-  @NotNull
-  private static PsiElement addSemicolonIfNeeded(@NotNull final Editor editor,
-                                                 @NotNull final Document document,
-                                                 @NotNull final PsiElement context,
-                                                 final int offset) {
-    ApplicationManager.getApplication().assertIsDispatchThread();
-
-    final Ref<PsiElement> newContext = Ref.create(context);
-    final PsiFile file = context.getContainingFile();
-    if (isSemicolonNeeded(file, editor)) {
-      ApplicationManager.getApplication().runWriteAction(new Runnable() {
-        @Override
-        public void run() {
-          CommandProcessor.getInstance().runUndoTransparentAction(new Runnable() {
-            public void run() {
-              document.insertString(offset, ";");
-              PsiDocumentManager.getInstance(context.getProject()).commitDocument(document);
-              newContext.set(CustomTemplateCallback.getContext(file, offset - 1));
-            }
-          });
-        }
-      });
+  private static Condition<PostfixTemplate> createIsApplicationTemplateFunction(@NotNull PostfixTemplateProvider provider,
+                                                                                @NotNull String key,
+                                                                                @NotNull PsiFile file,
+                                                                                @NotNull Editor editor) {
+    int currentOffset = editor.getCaretModel().getOffset();
+    final int newOffset = currentOffset - key.length();
+    CharSequence fileContent = editor.getDocument().getCharsSequence();
+    StringBuilder fileContentWithoutKey = new StringBuilder();
+    fileContentWithoutKey.append(fileContent.subSequence(0, newOffset));
+    fileContentWithoutKey.append(fileContent.subSequence(currentOffset, fileContent.length()));
+    PsiFile copyFile = copyFile(file, fileContentWithoutKey);
+    Document copyDocument = copyFile.getViewProvider().getDocument();
+    if (copyDocument == null) {
+      //noinspection unchecked
+      return Condition.FALSE;
     }
-    return newContext.get();
+
+    copyFile = provider.preCheck(editor, copyFile, newOffset);
+    copyDocument = copyFile.getViewProvider().getDocument();
+    if (copyDocument == null) {
+      //noinspection unchecked
+      return Condition.FALSE;
+    }
+
+    final PsiElement context = CustomTemplateCallback.getContext(copyFile, newOffset > 0 ? newOffset - 1 : newOffset);
+    final Document finalCopyDocument = copyDocument;
+    return new Condition<PostfixTemplate>() {
+      @Override
+      public boolean value(PostfixTemplate template) {
+        return template != null && template.isEnabled() && template.isApplicable(context, finalCopyDocument, newOffset);
+      }
+    };
   }
 
-  private static boolean isSemicolonNeeded(@NotNull PsiFile file, @NotNull Editor editor) {
-    return JavaCompletionContributor.semicolonNeeded(editor, file, CompletionInitializationContext.calcStartOffset(editor));
+
+  @NotNull
+  public static PsiFile copyFile(@NotNull PsiFile file, @NotNull StringBuilder fileContentWithoutKey) {
+    final PsiFileFactory psiFileFactory = PsiFileFactory.getInstance(file.getProject());
+    PsiFile copy = psiFileFactory.createFileFromText(file.getName(), file.getFileType(), fileContentWithoutKey);
+    VirtualFile vFile = copy.getVirtualFile();
+    if (vFile != null) {
+      vFile.putUserData(UndoConstants.DONT_RECORD_UNDO, Boolean.TRUE);
+    }
+    return copy;
+  }
+
+  public static boolean isApplicableTemplate(@NotNull PostfixTemplateProvider provider,
+                                             @NotNull String key,
+                                             @NotNull PsiFile file,
+                                             @NotNull Editor editor) {
+    return createIsApplicationTemplateFunction(provider, key, file, editor).value(getTemplate(provider, key));
+  }
+
+
+  @NotNull
+  private static Set<String> getKeys(@NotNull PostfixTemplateProvider provider) {
+    Set<String> result = ContainerUtil.newHashSet();
+    for (PostfixTemplate template : provider.getTemplates()) {
+      result.add(template.getKey());
+    }
+
+    return result;
+  }
+
+  @Nullable
+  private static PostfixTemplate getTemplate(@NotNull PostfixTemplateProvider provider, @Nullable String key) {
+    for (PostfixTemplate template : provider.getTemplates()) {
+      if (template.getKey().equals(key)) {
+        return template;
+      }
+    }
+    return null;
+  }
+
+  private static Language getLanguage(@NotNull CustomTemplateCallback callback) {
+    return callback.getContext().getLanguage();
   }
 }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplate.java
index 80a68ab..747366d 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplate.java
@@ -18,13 +18,8 @@
 import com.intellij.codeInsight.template.postfix.settings.PostfixTemplatesSettings;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiExpression;
-import com.intellij.psi.PsiExpressionStatement;
-import com.intellij.psi.util.PsiTreeUtil;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 public abstract class PostfixTemplate {
   @NotNull private final String myPresentableName;
@@ -32,9 +27,6 @@
   @NotNull private final String myDescription;
   @NotNull private final String myExample;
 
-  @NotNull
-  public static final ExtensionPointName<PostfixTemplate> EP_NAME = ExtensionPointName.create("com.intellij.postfixTemplate");
-
   protected PostfixTemplate(@NotNull String name, @NotNull String description, @NotNull String example) {
     this(name, "." + name, description, example);
   }
@@ -71,12 +63,6 @@
     return settings != null && settings.isPostfixTemplatesEnabled() && settings.isTemplateEnabled(this);
   }
 
-  @Nullable
-  public static PsiExpression getTopmostExpression(PsiElement context) {
-    PsiExpressionStatement statement = PsiTreeUtil.getNonStrictParentOfType(context, PsiExpressionStatement.class);
-    return statement != null ? PsiTreeUtil.getChildOfType(statement, PsiExpression.class) : null;
-  }
-
   public abstract boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset);
 
   public abstract void expand(@NotNull PsiElement context, @NotNull Editor editor);
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateProvider.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateProvider.java
new file mode 100644
index 0000000..eeea9a1
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateProvider.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
+
+
+import com.intellij.openapi.editor.Editor;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Set;
+
+public interface PostfixTemplateProvider {
+
+  /**
+   * Return all templates registered in the provider
+   */
+  @NotNull
+  Set<PostfixTemplate> getTemplates();
+
+  /**
+   * Check symbol can separate template keys
+   */
+  boolean isTerminalSymbol(char currentChar);
+
+  /**
+   * Prepare original file content for template expanding
+   * Return context after transformation
+   */
+  @NotNull
+  PsiElement preExpand(@NotNull Editor editor, @NotNull PsiElement context, int offset, @NotNull String key);
+
+  /**
+   * Do some actions with the file content before check applicable.
+   * Return copyFile or another copy of file after processing
+   */
+  @NotNull
+  PsiFile preCheck(@NotNull Editor editor, @NotNull PsiFile copyFile, int currentOffset);
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java
index 277a6f2..afc3236b 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ReturnStatementPostfixTemplate.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.codeInsight.template.postfix.templates;
 
+import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.psi.*;
 import org.jetbrains.annotations.NotNull;
@@ -26,7 +27,7 @@
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     PsiElement parent = expr != null ? expr.getParent() : null;
     if (!(parent instanceof PsiExpressionStatement)) return;
     PsiElementFactory factory = JavaPsiFacade.getInstance(expr.getProject()).getElementFactory();
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StatementPostfixTemplateBase.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StatementPostfixTemplateBase.java
index 4449c55..8f26ec0 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StatementPostfixTemplateBase.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/StatementPostfixTemplateBase.java
@@ -1,6 +1,22 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
 
 import com.intellij.codeInsight.CodeInsightUtilCore;
+import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.TextRange;
@@ -17,7 +33,7 @@
   }
 
   protected void surroundWith(PsiElement context, Editor editor, String text) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     PsiElement parent = expr != null ? expr.getParent() : null;
     if (!(parent instanceof PsiExpressionStatement)) return;
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java
index 880c045..20a7299 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SwitchStatementPostfixTemplate.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.codeInsight.template.postfix.templates;
 
+import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
@@ -51,7 +52,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expr = getTopmostExpression(context);
+    PsiExpression expr = PostfixTemplatesUtils.getTopmostExpression(context);
     return expr != null && isSwitchCompatibleType(expr.getType(), context);
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java
index 044dadc81c..eb46ba9 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/SynchronizedStatementPostfixTemplate.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.codeInsight.template.postfix.templates;
 
+import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.psi.PsiElement;
@@ -30,7 +31,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     PsiType type = expression != null ? expression.getType() : null;
     return type != null && !(type instanceof PsiPrimitiveType);
   }
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java
index b1bb654..7b0aaa0 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/ThrowExceptionPostfixTemplate.java
@@ -29,7 +29,7 @@
 
   @Override
   public boolean isApplicable(@NotNull PsiElement context, @NotNull Document copyDocument, int newOffset) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     return expression != null && PostfixTemplatesUtils.isThrowable(expression.getType());
   }
 
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java
new file mode 100644
index 0000000..843c19e
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplate.java
@@ -0,0 +1,110 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
+
+import com.intellij.codeInsight.ExceptionUtil;
+import com.intellij.codeInsight.intention.impl.TypeExpression;
+import com.intellij.codeInsight.template.Template;
+import com.intellij.codeInsight.template.TemplateManager;
+import com.intellij.codeInsight.template.impl.MacroCallNode;
+import com.intellij.codeInsight.template.impl.TextExpression;
+import com.intellij.codeInsight.template.macro.SuggestVariableNameMacro;
+import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.*;
+import com.intellij.psi.search.ProjectScope;
+import com.intellij.psi.util.InheritanceUtil;
+import com.intellij.psi.util.PsiUtil;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Collection;
+import java.util.Collections;
+
+
+public class TryWithResourcesPostfixTemplate extends PostfixTemplate {
+  protected TryWithResourcesPostfixTemplate() {
+    super("twr", "Description", "Example");
+  }
+
+  @Override
+  public boolean isApplicable(@NotNull PsiElement element, @NotNull Document copyDocument, int newOffset) {
+    if (!PsiUtil.isLanguageLevel7OrHigher(element)) return false;
+
+    PsiExpression initializer = PostfixTemplatesUtils.getTopmostExpression(element);
+
+    if (initializer == null) return false;
+
+    final PsiType type = initializer.getType();
+    if (!(type instanceof PsiClassType)) return false;
+    final PsiClass aClass = ((PsiClassType)type).resolve();
+    Project project = element.getProject();
+    final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
+    final PsiClass autoCloseable = facade.findClass(CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE, ProjectScope.getLibrariesScope(project));
+    if (!InheritanceUtil.isInheritorOrSelf(aClass, autoCloseable, true)) return false;
+
+    return true;
+  }
+
+  @Override
+  public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
+    assert expression != null;
+
+    Project project = context.getProject();
+
+    editor.getDocument().deleteString(expression.getTextRange().getStartOffset(), expression.getTextRange().getEndOffset());
+
+    TemplateManager manager = TemplateManager.getInstance(project);
+    Template template = manager.createTemplate("", "");
+    template.setToReformat(true);
+    template.addTextSegment("try (");
+    MacroCallNode name = new MacroCallNode(new SuggestVariableNameMacro());
+
+    template.addVariable("type", new TypeExpression(project, new PsiType[]{expression.getType()}), false);
+    template.addTextSegment(" ");
+    template.addVariable("name", name, name, true);
+    template.addTextSegment(" = ");
+    template.addVariable("variable", new TextExpression(expression.getText()), false);
+    template.addTextSegment(") {\n");
+    template.addEndVariable();
+    template.addTextSegment("\n}");
+
+    Collection<PsiClassType> unhandled = getUnhandled(expression);
+    for (PsiClassType exception : unhandled) {
+      MacroCallNode variable = new MacroCallNode(new SuggestVariableNameMacro());
+      template.addTextSegment("catch(");
+      template.addVariable("type " + exception.getClassName(), new TypeExpression(project, new PsiType[]{exception}), false);
+      template.addTextSegment(" ");
+      template.addVariable("name " + exception.getClassName(), variable, variable, false);
+      template.addTextSegment(") {}");
+    }
+
+    manager.startTemplate(editor, template);
+  }
+
+  @NotNull
+  private static Collection<PsiClassType> getUnhandled(@NotNull PsiExpression expression) {
+    assert expression.getType() != null;
+    PsiMethod methodCloser = PsiUtil.getResourceCloserMethodForType((PsiClassType)expression.getType(), expression.getProject());
+    PsiSubstitutor substitutor = PsiUtil.resolveGenericsClassInType(expression.getType()).getSubstitutor();
+
+    return methodCloser != null
+           ? ExceptionUtil.getUnhandledExceptions(methodCloser, expression, null, substitutor)
+           : Collections.<PsiClassType>emptyList();
+  }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java
index 03d91b2..4c856f7 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/templates/WhileStatementPostfixTemplate.java
@@ -1,5 +1,21 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
 
+import com.intellij.codeInsight.template.postfix.util.PostfixTemplatesUtils;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.psi.*;
 import org.jetbrains.annotations.NotNull;
@@ -11,7 +27,7 @@
 
   @Override
   public void expand(@NotNull PsiElement context, @NotNull Editor editor) {
-    PsiExpression expression = getTopmostExpression(context);
+    PsiExpression expression = PostfixTemplatesUtils.getTopmostExpression(context);
     assert expression != null;
 
     PsiElementFactory factory = JavaPsiFacade.getElementFactory(context.getProject());
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/Aliases.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/Aliases.java
deleted file mode 100644
index 3de07c3..0000000
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/Aliases.java
+++ /dev/null
@@ -1,15 +0,0 @@
-package com.intellij.codeInsight.template.postfix.util;
-
-import java.lang.annotation.ElementType;
-import java.lang.annotation.Retention;
-import java.lang.annotation.RetentionPolicy;
-import java.lang.annotation.Target;
-
-/**
- * @author ignatov
- */
-@Target(value = ElementType.TYPE)
-@Retention(value = RetentionPolicy.RUNTIME)
-public @interface Aliases {
-  String[] value();
-}
diff --git a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/PostfixTemplatesUtils.java b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/PostfixTemplatesUtils.java
index 370c986..7b92ffd 100644
--- a/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/PostfixTemplatesUtils.java
+++ b/java/java-impl/src/com/intellij/codeInsight/template/postfix/util/PostfixTemplatesUtils.java
@@ -17,12 +17,12 @@
 
 import com.intellij.codeInsight.generation.surroundWith.JavaExpressionSurrounder;
 import com.intellij.codeInsight.generation.surroundWith.JavaWithIfExpressionSurrounder;
-import com.intellij.codeInsight.template.postfix.templates.PostfixTemplate;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
 import com.intellij.psi.util.InheritanceUtil;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import org.jetbrains.annotations.Contract;
 import org.jetbrains.annotations.NotNull;
@@ -45,7 +45,7 @@
   }
 
   public static void createStatement(@NotNull PsiElement context, @NotNull Editor editor, @NotNull String prefix, @NotNull String suffix, int offset) {
-    PsiExpression expr = PostfixTemplate.getTopmostExpression(context);
+    PsiExpression expr = getTopmostExpression(context);
     PsiElement parent = expr != null ? expr.getParent() : null;
     assert parent instanceof PsiStatement;
     PsiElementFactory factory = JavaPsiFacade.getInstance(context.getProject()).getElementFactory();
@@ -121,5 +121,11 @@
     }
     return null;
   }
+
+  @Nullable
+  public static PsiExpression getTopmostExpression(PsiElement context) {
+    PsiExpressionStatement statement = PsiTreeUtil.getNonStrictParentOfType(context, PsiExpressionStatement.class);
+    return statement != null ? PsiTreeUtil.getChildOfType(statement, PsiExpression.class) : null;
+  }
 }
 
diff --git a/java/java-impl/src/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java b/java/java-impl/src/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java
index 26e4adf..f511eac 100644
--- a/java/java-impl/src/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java
+++ b/java/java-impl/src/com/intellij/ide/fileTemplates/JavaCreateFromTemplateHandler.java
@@ -26,6 +26,7 @@
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.psi.impl.file.JavaDirectoryServiceImpl;
 import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
 
 import java.util.Map;
 
@@ -100,8 +101,9 @@
     return fileType.equals(StdFileTypes.JAVA) && !FileTemplateUtil.INTERNAL_PACKAGE_INFO_TEMPLATE_NAME.equals(template.getName());
   }
 
+  @NotNull
   public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, final String fileName, FileTemplate template,
-                                       String templateText, Map<String, Object> props) throws IncorrectOperationException {
+                                       String templateText, @NotNull Map<String, Object> props) throws IncorrectOperationException {
     String extension = template.getExtension();
     PsiElement result = createClassOrInterface(project, directory, templateText, template.isReformatCode(), extension);
     hackAwayEmptyPackage((PsiJavaFile)result.getContainingFile(), template, props);
diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java b/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
index 61e5303..dbdcff0 100644
--- a/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
+++ b/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyNodeDescriptor.java
@@ -52,7 +52,7 @@
     myTreeStructure = treeStructure;
   }
 
-  private PsiMethod getMethod(final PsiClass aClass, final boolean checkBases) {
+  PsiMethod getMethod(final PsiClass aClass, final boolean checkBases) {
     return MethodHierarchyUtil.findBaseMethodInClass(myTreeStructure.getBaseMethod(), aClass, checkBases);
   }
 
diff --git a/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java b/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java
index 7a5e869..922fc2d 100644
--- a/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java
+++ b/java/java-impl/src/com/intellij/ide/hierarchy/method/MethodHierarchyTreeStructure.java
@@ -172,13 +172,16 @@
       descriptors.add(d);
     }
 
-    FunctionalExpressionSearch.search(getBaseMethod()).forEach(new Processor<PsiFunctionalExpression>() {
-      @Override
-      public boolean process(PsiFunctionalExpression expression) {
-        descriptors.add(new MethodHierarchyNodeDescriptor(myProject, descriptor, expression, false, MethodHierarchyTreeStructure.this));
-        return true;
-      }
-    });
+    final PsiMethod existingMethod = ((MethodHierarchyNodeDescriptor)descriptor).getMethod(psiClass, false);
+    if (existingMethod != null) {
+      FunctionalExpressionSearch.search(existingMethod).forEach(new Processor<PsiFunctionalExpression>() {
+        @Override
+        public boolean process(PsiFunctionalExpression expression) {
+          descriptors.add(new MethodHierarchyNodeDescriptor(myProject, descriptor, expression, false, MethodHierarchyTreeStructure.this));
+          return true;
+        }
+      });
+    }
 
     return descriptors.toArray(new HierarchyNodeDescriptor[descriptors.size()]);
   }
diff --git a/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java b/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java
index 6a267f6..56f376f 100644
--- a/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java
+++ b/java/java-impl/src/com/intellij/lang/java/JavaDocumentationProvider.java
@@ -34,7 +34,6 @@
 import com.intellij.openapi.project.IndexNotReadyException;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.*;
-import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.text.StringUtil;
@@ -56,8 +55,10 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.LinkedHashSet;
 import java.util.List;
 import java.util.Map;
+import java.util.Set;
 
 /**
  * @author Maxim.Mossienko
@@ -591,13 +592,16 @@
         if (classUrls != null) {
           urls = ContainerUtil.newSmartList();
 
-          String rawSignature = formatMethodSignature(method, true);
-          for (String classUrl : classUrls) {
-            urls.add(classUrl + "#" + rawSignature);
-          }
+          final boolean useJava8Format = PsiUtil.isLanguageLevel8OrHigher(method);
 
-          String signature = formatMethodSignature(method, false);
-          if (Comparing.compare(rawSignature, signature) != 0) {
+          final Set<String> signatures = new LinkedHashSet<String>();
+          signatures.add(formatMethodSignature(method, true, useJava8Format));
+          signatures.add(formatMethodSignature(method, false, useJava8Format));
+
+          signatures.add(formatMethodSignature(method, true, !useJava8Format));
+          signatures.add(formatMethodSignature(method, false, !useJava8Format));
+
+          for (String signature : signatures) {
             for (String classUrl : classUrls) {
               urls.add(classUrl + "#" + signature);
             }
@@ -626,7 +630,7 @@
     }
   }
 
-  private static String formatMethodSignature(PsiMethod method, boolean raw) {
+  private static String formatMethodSignature(PsiMethod method, boolean raw, boolean java8Format) {
     int options = PsiFormatUtilBase.SHOW_NAME | PsiFormatUtilBase.SHOW_PARAMETERS;
     int parameterOptions = PsiFormatUtilBase.SHOW_TYPE | PsiFormatUtilBase.SHOW_FQ_CLASS_NAMES;
     if (raw) {
@@ -636,7 +640,7 @@
 
     String signature = PsiFormatUtil.formatMethod(method, PsiSubstitutor.EMPTY, options, parameterOptions, 999);
 
-    if (PsiUtil.isLanguageLevel8OrHigher(method)) {
+    if (java8Format) {
       signature = signature.replaceAll("\\(|\\)|, ", "-").replaceAll("\\[\\]", ":A");
     }
 
diff --git a/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java b/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java
index 2aa495c..f3d6575 100644
--- a/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java
+++ b/java/java-impl/src/com/intellij/openapi/projectRoots/impl/JavaSdkImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -98,7 +98,7 @@
       return "http://docs.oracle.com/javase/7/docs/api/";
     }
     if (version == JavaSdkVersion.JDK_1_8) {
-      return "http://download.java.net/jdk8/docs/api/";
+      return "http://docs.oracle.com/javase/8/docs/api";
     }
     return null;
   }
@@ -416,19 +416,6 @@
   }
 
   @Override
-  @NotNull
-  public String getComponentName() {
-    return getName();
-  }
-
-  @Override
-  public void initComponent() { }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   public int compareTo(@NotNull String versionString, @NotNull String versionNumber) {
     return getVersionNumber(versionString).compareTo(versionNumber);
   }
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java
index 9ade1c2..0770a04 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/ImportHelper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -766,7 +766,7 @@
             continue;
           }
           if (reference instanceof PsiJavaCodeReferenceElementImpl
-              && ((PsiJavaCodeReferenceElementImpl)reference).getKind() == PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND) {
+              && ((PsiJavaCodeReferenceElementImpl)reference).getKind(((PsiJavaCodeReferenceElementImpl)reference).getContainingFile()) == PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND) {
             continue;
           }
         }
@@ -774,7 +774,7 @@
         final JavaResolveResult resolveResult = javaReference.advancedResolve(true);
         PsiElement refElement = resolveResult.getElement();
         if (refElement == null && referenceElement != null) {
-          refElement = ResolveClassUtil.resolveClass(referenceElement); // might be uncomplete code
+          refElement = ResolveClassUtil.resolveClass(referenceElement, referenceElement.getContainingFile()); // might be uncomplete code
         }
         if (refElement == null) continue;
 
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 b151628..844ef00 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
@@ -27,14 +27,11 @@
 import com.intellij.psi.impl.source.SourceTreeToPsiMap;
 import com.intellij.psi.impl.source.jsp.jspJava.JspxImportStatement;
 import com.intellij.psi.statistics.JavaStatisticsManager;
-import com.intellij.psi.util.PsiElementFilter;
-import com.intellij.psi.util.PsiTreeUtil;
-import com.intellij.psi.util.PsiUtil;
-import com.intellij.psi.util.TypeConversionUtil;
+import com.intellij.psi.util.*;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
+import com.intellij.util.Processor;
 import com.intellij.util.containers.ContainerUtil;
-import com.intellij.psi.util.FileTypeUtils;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -309,7 +306,7 @@
     return suggestVariableNameByType(type, variableKind, correctKeywords, false);
   }
 
-  private String[] suggestVariableNameByType(PsiType type, final VariableKind variableKind, boolean correctKeywords, boolean skipIndices) {
+  private String[] suggestVariableNameByType(final PsiType type, final VariableKind variableKind, final boolean correctKeywords, boolean skipIndices) {
     String longTypeName = skipIndices ? type.getCanonicalText():getLongTypeName(type);
     CodeStyleSettings.TypeToNameMap map = getMapByVariableKind(variableKind);
     if (map != null && longTypeName != null) {
@@ -322,7 +319,7 @@
       }
     }
 
-    Collection<String> suggestions = new LinkedHashSet<String>();
+    final Collection<String> suggestions = new LinkedHashSet<String>();
 
     if (!skipIndices) {
       suggestNamesForCollectionInheritors(type, variableKind, suggestions, correctKeywords);
@@ -336,6 +333,21 @@
       ContainerUtil.addAll(suggestions, getSuggestionsByName(typeName, variableKind, type instanceof PsiArrayType, correctKeywords));
     }
 
+    if (!skipIndices && type instanceof PsiClassType) {
+      final PsiClass psiClass = ((PsiClassType)type).resolve();
+      if (psiClass != null && psiClass.getContainingClass() != null) {
+        InheritanceUtil.processSupers(psiClass, false, new Processor<PsiClass>() {
+          @Override
+          public boolean process(PsiClass superClass) {
+            if (PsiTreeUtil.isAncestor(superClass, psiClass, true)) {
+              ContainerUtil.addAll(suggestions, getSuggestionsByName(superClass.getName(), variableKind, false, correctKeywords));
+            }
+            return false;
+          }
+        });
+      }
+    }
+
     return ArrayUtil.toStringArray(suggestions);
   }
 
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java
index 42d3098..3d1e1c0 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/codeStyle/JavaReferenceAdjuster.java
@@ -55,7 +55,8 @@
 
         boolean rightKind = true;
         if (elementType == JavaElementType.JAVA_CODE_REFERENCE) {
-          int kind = ((PsiJavaCodeReferenceElementImpl)element).getKind();
+          PsiJavaCodeReferenceElementImpl impl = (PsiJavaCodeReferenceElementImpl)element;
+          int kind = impl.getKind(impl.getContainingFile());
           rightKind = kind == PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND || kind == PsiJavaCodeReferenceElementImpl.CLASS_OR_PACKAGE_NAME_KIND;
         }
 
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java
index 71e40e5..a0243df 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/JavaClassReference.java
@@ -268,10 +268,11 @@
     return JavaClassReferenceProvider.EXTEND_CLASS_NAMES.getValue(getOptions());
   }
 
-  private LookupElement[] processPackage(final PsiPackage aPackage) {
+  @NotNull
+  private LookupElement[] processPackage(@NotNull PsiPackage aPackage) {
     final ArrayList<LookupElement> list = ContainerUtil.newArrayList();
     final int startOffset = StringUtil.isEmpty(aPackage.getName()) ? 0 : aPackage.getQualifiedName().length() + 1;
-    final GlobalSearchScope scope = getScope();
+    final GlobalSearchScope scope = getScope(getElement().getContainingFile());
     for (final PsiPackage subPackage : aPackage.getSubPackages(scope)) {
       final String shortName = subPackage.getQualifiedName().substring(startOffset);
       if (JavaPsiFacade.getInstance(subPackage.getProject()).getNameHelper().isIdentifier(shortName)) {
@@ -355,7 +356,8 @@
     return (JavaResolveResult) resolveCache.resolveWithCaching(this, MyResolver.INSTANCE, false, false,file)[0];
   }
 
-  private JavaResolveResult doAdvancedResolve() {
+  @NotNull
+  private JavaResolveResult doAdvancedResolve(@NotNull PsiFile containingFile) {
     final PsiElement psiElement = getElement();
 
     if (!psiElement.isValid()) return JavaResolveResult.EMPTY;
@@ -366,7 +368,9 @@
     if (context instanceof PsiClass) {
       if (isStaticClassReference(elementText, false)) {
         final PsiClass psiClass = ((PsiClass)context).findInnerClassByName(getCanonicalText(), false);
-        if (psiClass != null) return new ClassCandidateInfo(psiClass, PsiSubstitutor.EMPTY, false, psiElement);
+        if (psiClass != null) {
+          return new ClassCandidateInfo(psiClass, PsiSubstitutor.EMPTY, false, psiElement);
+        }
         PsiElement member = doResolveMember((PsiClass)context, myText);
         return member == null ? JavaResolveResult.EMPTY : new CandidateInfo(member, PsiSubstitutor.EMPTY, false, false, psiElement);
       }
@@ -382,18 +386,18 @@
     if (!qName.contains(".")) {
       final String defaultPackage = JavaClassReferenceProvider.DEFAULT_PACKAGE.getValue(getOptions());
       if (StringUtil.isNotEmpty(defaultPackage)) {
-        final JavaResolveResult resolveResult = advancedResolveInner(psiElement, defaultPackage + "." + qName);
+        final JavaResolveResult resolveResult = advancedResolveInner(psiElement, defaultPackage + "." + qName, containingFile);
         if (resolveResult != JavaResolveResult.EMPTY) {
           return resolveResult;
         }
       }
     }
-    return advancedResolveInner(psiElement, qName);
+    return advancedResolveInner(psiElement, qName, containingFile);
   }
 
-  private JavaResolveResult advancedResolveInner(final PsiElement psiElement, final String qName) {
-    final PsiManager manager = psiElement.getManager();
-    final GlobalSearchScope scope = getScope();
+  private JavaResolveResult advancedResolveInner(@NotNull PsiElement psiElement, @NotNull String qName, @NotNull PsiFile containingFile) {
+    final PsiManager manager = containingFile.getManager();
+    final GlobalSearchScope scope = getScope(containingFile);
     if (myIndex == myJavaClassReferenceSet.getReferences().length - 1) {
       final PsiClass aClass = JavaPsiFacade.getInstance(manager.getProject()).findClass(qName, scope);
       if (aClass != null) {
@@ -413,8 +417,6 @@
       resolveResult = resolveMember(qName, manager, getElement().getResolveScope());
     }
     if (resolveResult == null) {
-      PsiFile containingFile = psiElement.getContainingFile();
-
       if (containingFile instanceof PsiJavaFile) {
         if (containingFile instanceof ServerPageFile) {
           containingFile = containingFile.getViewProvider().getPsi(JavaLanguage.INSTANCE);
@@ -448,12 +450,12 @@
            : JavaResolveResult.EMPTY;
   }
 
-  private GlobalSearchScope getScope() {
-    Project project = getElement().getProject();
+  private GlobalSearchScope getScope(@NotNull PsiFile containingFile) {
+    Project project = containingFile.getProject();
     GlobalSearchScope scope = myJavaClassReferenceSet.getProvider().getScope(project);
     if (scope == null) {
-      Module module = ModuleUtilCore.findModuleForPsiElement(getElement());
-      return module != null ? module.getModuleWithDependenciesAndLibrariesScope(true) : GlobalSearchScope.allScope(project);
+      Module module = ModuleUtilCore.findModuleForPsiElement(containingFile);
+      return module == null ? GlobalSearchScope.allScope(project) : module.getModuleWithDependenciesAndLibrariesScope(true);
     }
     return scope;
   }
@@ -472,7 +474,7 @@
   }
 
   @Nullable
-  private List<? extends LocalQuickFix> registerFixes(final HighlightInfo info) {
+  private List<? extends LocalQuickFix> registerFixes(HighlightInfo info) {
 
     final List<LocalQuickFix> list = OrderEntryFix.registerFixes(new QuickFixActionRegistrarImpl(info), this);
 
@@ -498,7 +500,7 @@
     final TextRange range = new TextRange(references[0].getRangeInElement().getStartOffset(),
                                           getRangeInElement().getEndOffset());
     final String qualifiedName = range.substring(getElement().getText());
-    final CreateClassOrPackageFix action = CreateClassOrPackageFix.createFix(qualifiedName, getScope(), getElement(), contextPackage,
+    final CreateClassOrPackageFix action = CreateClassOrPackageFix.createFix(qualifiedName, getScope(getElement().getContainingFile()), getElement(), contextPackage,
                                                                              kind, extendClass, templateName);
     if (action != null) {
       QuickFixAction.registerQuickFixAction(info, action);
@@ -591,13 +593,13 @@
     return myJavaClassReferenceSet.getUnresolvedMessagePattern(myIndex);
   }
 
-  private static class MyResolver implements ResolveCache.PolyVariantResolver<JavaClassReference> {
+  private static class MyResolver implements ResolveCache.PolyVariantContextResolver<JavaClassReference> {
     private static final MyResolver INSTANCE = new MyResolver();
 
     @NotNull
     @Override
-    public JavaResolveResult[] resolve(@NotNull JavaClassReference javaClassReference, boolean incompleteCode) {
-      return new JavaResolveResult[]{javaClassReference.doAdvancedResolve()};
+    public ResolveResult[] resolve(@NotNull JavaClassReference ref, @NotNull PsiFile containingFile, boolean incompleteCode) {
+      return new JavaResolveResult[]{ref.doAdvancedResolve(containingFile)};
     }
   }
 
diff --git a/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaTreeCopyHandler.java b/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaTreeCopyHandler.java
index 283e857..a023477 100644
--- a/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaTreeCopyHandler.java
+++ b/java/java-impl/src/com/intellij/psi/impl/source/tree/JavaTreeCopyHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -200,7 +200,7 @@
       }
     }
     else if (original.getElementType() == JavaElementType.JAVA_CODE_REFERENCE) {
-      switch (((PsiJavaCodeReferenceElementImpl)original).getKind()) {
+      switch (((PsiJavaCodeReferenceElementImpl)original).getKind(((PsiJavaCodeReferenceElementImpl)original).getContainingFile())) {
       case PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND:
       case PsiJavaCodeReferenceElementImpl.CLASS_OR_PACKAGE_NAME_KIND:
       case PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND:
diff --git a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java
index 09b60c1..293d335 100644
--- a/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java
+++ b/java/java-indexing-impl/src/com/intellij/psi/impl/search/AllClassesSearchExecutor.java
@@ -30,6 +30,7 @@
 import com.intellij.psi.search.PsiShortNamesCache;
 import com.intellij.psi.search.SearchScope;
 import com.intellij.psi.search.searches.AllClassesSearch;
+import com.intellij.util.Consumer;
 import com.intellij.util.Processor;
 import com.intellij.util.QueryExecutor;
 import com.intellij.util.indexing.IdFilter;
@@ -57,39 +58,28 @@
   private static boolean processAllClassesInGlobalScope(@NotNull final GlobalSearchScope scope,
                                                         @NotNull final AllClassesSearch.SearchParameters parameters,
                                                         @NotNull Processor<PsiClass> processor) {
-    Project project = parameters.getProject();
-    final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
-    final ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
-    
     final Set<String> names = new THashSet<String>(10000);
-    cache.processAllClassNames(new Processor<String>() {
-      int i = 0;
-
+    processClassNames(parameters.getProject(), scope, new Consumer<String>() {
       @Override
-      public boolean process(String s) {
-        if (indicator != null && i++ % 512 == 0) {
-          indicator.checkCanceled();
-        }
+      public void consume(String s) {
         if (parameters.nameMatches(s)) {
           names.add(s);
         }
-        return true;
-      }
-    }, scope, IdFilter.getProjectIdFilter(project, true));
-
-    if (indicator != null) {
-      indicator.checkCanceled();
-    }
-
-    List<String> sorted = new ArrayList<String>(names);
-    Collections.sort(sorted, new Comparator<String>() {
-      @Override
-      public int compare(final String o1, final String o2) {
-        return o1.compareToIgnoreCase(o2);
       }
     });
 
-    for (final String name : sorted) {
+    List<String> sorted = new ArrayList<String>(names);
+    Collections.sort(sorted, String.CASE_INSENSITIVE_ORDER);
+
+    return processClassesByNames(parameters.getProject(), scope, sorted, processor);
+  }
+
+  public static boolean processClassesByNames(Project project,
+                                              final GlobalSearchScope scope,
+                                              Collection<String> names,
+                                              Processor<PsiClass> processor) {
+    final PsiShortNamesCache cache = PsiShortNamesCache.getInstance(project);
+    for (final String name : names) {
       ProgressIndicatorProvider.checkCanceled();
       final PsiClass[] classes = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass[]>() {
         @Override
@@ -107,6 +97,28 @@
     return true;
   }
 
+  public static Project processClassNames(Project project, GlobalSearchScope scope, final Consumer<String> consumer) {
+    final ProgressIndicator indicator = ProgressIndicatorProvider.getGlobalProgressIndicator();
+
+    PsiShortNamesCache.getInstance(project).processAllClassNames(new Processor<String>() {
+      int i = 0;
+
+      @Override
+      public boolean process(String s) {
+        if (indicator != null && i++ % 512 == 0) {
+          indicator.checkCanceled();
+        }
+        consumer.consume(s);
+        return true;
+      }
+    }, scope, IdFilter.getProjectIdFilter(project, true));
+
+    if (indicator != null) {
+      indicator.checkCanceled();
+    }
+    return project;
+  }
+
   private static boolean processScopeRootForAllClasses(@NotNull final PsiElement scopeRoot, @NotNull final Processor<PsiClass> processor) {
     final boolean[] stopped = {false};
 
diff --git a/java/java-psi-api/src/com/intellij/openapi/projectRoots/JavaSdkVersion.java b/java/java-psi-api/src/com/intellij/openapi/projectRoots/JavaSdkVersion.java
index 9a469ab2..b185b48 100644
--- a/java/java-psi-api/src/com/intellij/openapi/projectRoots/JavaSdkVersion.java
+++ b/java/java-psi-api/src/com/intellij/openapi/projectRoots/JavaSdkVersion.java
@@ -31,7 +31,9 @@
   JDK_1_5(LanguageLevel.JDK_1_5, "1.5"),
   JDK_1_6(LanguageLevel.JDK_1_6, "1.6"),
   JDK_1_7(LanguageLevel.JDK_1_7, "1.7"),
-  JDK_1_8(LanguageLevel.JDK_1_8, "1.8");
+  JDK_1_8(LanguageLevel.JDK_1_8, "1.8"),
+  JDK_1_9(LanguageLevel.JDK_1_9, "1.9");
+  
   private final LanguageLevel myMaxLanguageLevel;
   private final String myDescription;
 
diff --git a/java/java-psi-api/src/com/intellij/openapi/projectRoots/JdkVersionUtil.java b/java/java-psi-api/src/com/intellij/openapi/projectRoots/JdkVersionUtil.java
index d26b1ca..98893c1 100644
--- a/java/java-psi-api/src/com/intellij/openapi/projectRoots/JdkVersionUtil.java
+++ b/java/java-psi-api/src/com/intellij/openapi/projectRoots/JdkVersionUtil.java
@@ -33,6 +33,7 @@
     VERSION_STRINGS.put(JavaSdkVersion.JDK_1_6, new String[]{"1.6", "6.0"});
     VERSION_STRINGS.put(JavaSdkVersion.JDK_1_7, new String[]{"1.7", "7.0"});
     VERSION_STRINGS.put(JavaSdkVersion.JDK_1_8, new String[]{"1.8", "8.0"});
+    VERSION_STRINGS.put(JavaSdkVersion.JDK_1_9, new String[]{"1.9", "9.0"});
   }
 
   public static JavaSdkVersion getVersion(@NotNull String versionString) {
diff --git a/java/java-psi-api/src/com/intellij/pom/java/LanguageLevel.java b/java/java-psi-api/src/com/intellij/pom/java/LanguageLevel.java
index e980c0a..6dc8cfb 100644
--- a/java/java-psi-api/src/com/intellij/pom/java/LanguageLevel.java
+++ b/java/java-psi-api/src/com/intellij/pom/java/LanguageLevel.java
@@ -30,9 +30,10 @@
   JDK_1_5(JavaCoreBundle.message("jdk.1.5.language.level.description")),
   JDK_1_6(JavaCoreBundle.message("jdk.1.6.language.level.description")),
   JDK_1_7(JavaCoreBundle.message("jdk.1.7.language.level.description")),
-  JDK_1_8(JavaCoreBundle.message("jdk.1.8.language.level.description"));
+  JDK_1_8(JavaCoreBundle.message("jdk.1.8.language.level.description")),
+  JDK_1_9(JavaCoreBundle.message("jdk.1.9.language.level.description"));
 
-  public static final LanguageLevel HIGHEST = JDK_1_8;
+  public static final LanguageLevel HIGHEST = JDK_1_8; // TODO! when language level 9 is really supported, update this field
   public static final Key<LanguageLevel> KEY = Key.create("LANGUAGE_LEVEL");
 
   private final String myPresentableText;
@@ -59,6 +60,7 @@
     if ("1.6".equals(value)) return JDK_1_6;
     if ("1.7".equals(value)) return JDK_1_7;
     if ("1.8".equals(value)) return JDK_1_8;
+    if ("1.9".equals(value)) return JDK_1_9;
 
     return null;
   }
diff --git a/java/java-psi-api/src/com/intellij/psi/LambdaHighlightingUtil.java b/java/java-psi-api/src/com/intellij/psi/LambdaHighlightingUtil.java
index 178001bc..503328a 100644
--- a/java/java-psi-api/src/com/intellij/psi/LambdaHighlightingUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/LambdaHighlightingUtil.java
@@ -36,7 +36,7 @@
   @Nullable
   public static String checkInterfaceFunctional(@NotNull PsiClass psiClass, String interfaceNonFunctionalMessage) {
     if (psiClass instanceof PsiTypeParameter) return null; //should be logged as cyclic inference
-    final List<MethodSignature> signatures = LambdaUtil.findFunctionCandidates(psiClass);
+    final List<HierarchicalMethodSignature> signatures = LambdaUtil.findFunctionCandidates(psiClass);
     if (signatures == null) return interfaceNonFunctionalMessage;
     if (signatures.isEmpty()) return "No target method found";
     if (signatures.size() == 1) {
@@ -97,15 +97,23 @@
   @Nullable
   public static String checkInterfaceFunctional(PsiType functionalInterfaceType) {
     if (functionalInterfaceType instanceof PsiIntersectionType) {
+      int count = 0;
       for (PsiType type : ((PsiIntersectionType)functionalInterfaceType).getConjuncts()) {
-        if (checkInterfaceFunctional(type) == null) return null;
+        if (checkInterfaceFunctional(type) == null) {
+          count++;
+        }
       }
+
+      if (count > 1) {
+        return "Multiple non-overriding abstract methods found in " + functionalInterfaceType.getPresentableText();
+      }
+      return null;
     }
     final PsiClassType.ClassResolveResult resolveResult = PsiUtil.resolveGenericsClassInType(functionalInterfaceType);
     final PsiClass aClass = resolveResult.getElement();
     if (aClass != null) {
       if (aClass instanceof PsiTypeParameter) return null; //should be logged as cyclic inference
-      final List<MethodSignature> signatures = LambdaUtil.findFunctionCandidates(aClass);
+      final List<HierarchicalMethodSignature> signatures = LambdaUtil.findFunctionCandidates(aClass);
       if (signatures != null && signatures.size() == 1) {
         final MethodSignature functionalMethod = signatures.get(0);
         if (functionalMethod.getTypeParameters().length > 0) return "Target method is generic";
diff --git a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
index e561140..fcf5e89 100644
--- a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
@@ -103,9 +103,7 @@
 
   public static boolean isFunctionalType(PsiType type) {
     if (type instanceof PsiIntersectionType) {
-      for (PsiType type1 : ((PsiIntersectionType)type).getConjuncts()) {
-        if (isFunctionalType(type1)) return true;
-      }
+      return extractFunctionalConjunct((PsiIntersectionType)type) != null;
     }
     return isFunctionalClass(PsiUtil.resolveGenericsClassInType(type).getElement());
   }
@@ -114,7 +112,7 @@
   public static boolean isFunctionalClass(PsiClass aClass) {
     if (aClass != null) {
       if (aClass instanceof PsiTypeParameter) return false;
-      final List<MethodSignature> signatures = findFunctionCandidates(aClass);
+      final List<HierarchicalMethodSignature> signatures = findFunctionCandidates(aClass);
       return signatures != null && signatures.size() == 1;
     }
     return false;
@@ -144,7 +142,7 @@
   @Nullable
   static MethodSignature getFunction(PsiClass psiClass) {
     if (psiClass == null) return null;
-    final List<MethodSignature> functions = findFunctionCandidates(psiClass);
+    final List<HierarchicalMethodSignature> functions = findFunctionCandidates(psiClass);
     if (functions != null && functions.size() == 1) {
       return functions.get(0);
     }
@@ -178,12 +176,13 @@
   }
 
   @Nullable
-  private static List<MethodSignature> hasSubsignature(List<MethodSignature> signatures) {
-    for (MethodSignature signature : signatures) {
+  private static List<HierarchicalMethodSignature> hasSubsignature(List<HierarchicalMethodSignature> signatures) {
+    for (HierarchicalMethodSignature signature : signatures) {
       boolean subsignature = true;
-      for (MethodSignature methodSignature : signatures) {
+      for (HierarchicalMethodSignature methodSignature : signatures) {
         if (!signature.equals(methodSignature)) {
-          if (!MethodSignatureUtil.isSubsignature(signature, methodSignature)) {
+          if (!MethodSignatureUtil.isSubsignature(signature, methodSignature) &&
+              !skipMethod(signature, methodSignature)) {
             subsignature = false;
             break;
           }
@@ -194,10 +193,20 @@
     return signatures;
   }
 
+  private static boolean skipMethod(HierarchicalMethodSignature signature,
+                                    HierarchicalMethodSignature methodSignature) {
+    //not generic
+    if (methodSignature.getTypeParameters().length == 0) {
+      return false;
+    }
+    //foreign class
+    return signature.getMethod().getContainingClass() != methodSignature.getMethod().getContainingClass();
+  }
+
   @Nullable
-  public static List<MethodSignature> findFunctionCandidates(PsiClass psiClass) {
+  public static List<HierarchicalMethodSignature> findFunctionCandidates(PsiClass psiClass) {
     if (psiClass != null && psiClass.isInterface() && !psiClass.isAnnotationType()) {
-      final List<MethodSignature> methods = new ArrayList<MethodSignature>();
+      final List<HierarchicalMethodSignature> methods = new ArrayList<HierarchicalMethodSignature>();
       final Collection<HierarchicalMethodSignature> visibleSignatures = psiClass.getVisibleSignatures();
       for (HierarchicalMethodSignature signature : visibleSignatures) {
         final PsiMethod psiMethod = signature.getMethod();
@@ -286,9 +295,8 @@
     } else if (parent instanceof PsiTypeCastExpression) {
       final PsiType castType = ((PsiTypeCastExpression)parent).getType();
       if (castType instanceof PsiIntersectionType) {
-        for (PsiType conjunctType : ((PsiIntersectionType)castType).getConjuncts()) {
-          if (getFunctionalInterfaceMethod(conjunctType) != null) return conjunctType;
-        }
+        final PsiType conjunct = extractFunctionalConjunct((PsiIntersectionType)castType);
+        if (conjunct != null) return conjunct;
       }
       return castType;
     }
@@ -363,6 +371,19 @@
     return null;
   }
 
+  @Nullable
+  private static PsiType extractFunctionalConjunct(PsiIntersectionType type) {
+    PsiType conjunct = null;
+    for (PsiType conjunctType : type.getConjuncts()) {
+      final PsiMethod interfaceMethod = getFunctionalInterfaceMethod(conjunctType);
+      if (interfaceMethod != null) {
+        if (conjunct != null && !conjunct.equals(conjunctType)) return null;
+        conjunct = conjunctType;
+      }
+    }
+    return conjunct;
+  }
+  
   private static PsiType getFunctionalInterfaceTypeByContainingLambda(@NotNull PsiLambdaExpression parentLambda) {
     final PsiType parentInterfaceType = parentLambda.getFunctionalInterfaceType();
     return parentInterfaceType != null ? getFunctionalInterfaceReturnType(parentInterfaceType) : null;
diff --git a/java/java-psi-api/src/com/intellij/psi/PsiFunctionalExpression.java b/java/java-psi-api/src/com/intellij/psi/PsiFunctionalExpression.java
index e038065..2afbe46 100644
--- a/java/java-psi-api/src/com/intellij/psi/PsiFunctionalExpression.java
+++ b/java/java-psi-api/src/com/intellij/psi/PsiFunctionalExpression.java
@@ -18,7 +18,7 @@
 import com.intellij.openapi.util.Iconable;
 import org.jetbrains.annotations.Nullable;
 
-public interface PsiFunctionalExpression extends PsiExpression, Iconable {
+public interface PsiFunctionalExpression extends PsiExpression, Iconable, NavigatablePsiElement {
   /**
    * @return SAM type the lambda expression corresponds to
    *         null when no SAM type could be found
diff --git a/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java b/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java
index c448926..0330fd9 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/PsiTypesUtil.java
@@ -22,7 +22,6 @@
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
 import com.intellij.psi.tree.IElementType;
-import com.intellij.util.containers.HashMap;
 import gnu.trove.THashMap;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -151,9 +150,7 @@
                                                       @Nullable Condition<IElementType> condition,
                                                       @NotNull LanguageLevel languageLevel) {
     //JLS3 15.8.2
-    if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5) &&
-        GET_CLASS_METHOD.equals(method.getName()) &&
-        CommonClassNames.JAVA_LANG_OBJECT.equals(method.getContainingClass().getQualifiedName())) {
+    if (languageLevel.isAtLeast(LanguageLevel.JDK_1_5) && isGetClass(method)) {
       PsiExpression qualifier = methodExpression.getQualifierExpression();
       PsiType qualifierType = null;
       final Project project = call.getProject();
@@ -169,18 +166,28 @@
           qualifierType = JavaPsiFacade.getInstance(project).getElementFactory().createType((PsiClass)parent.getPsi());
         }
       }
-      if (qualifierType != null) {
-        PsiClass javaLangClass = JavaPsiFacade.getInstance(project).findClass(CommonClassNames.JAVA_LANG_CLASS, call.getResolveScope());
-        if (javaLangClass != null && javaLangClass.getTypeParameters().length == 1) {
-          Map<PsiTypeParameter, PsiType> map = new HashMap<PsiTypeParameter, PsiType>();
-          map.put(javaLangClass.getTypeParameters()[0], PsiWildcardType.createExtends(call.getManager(), qualifierType));
-          PsiSubstitutor substitutor = JavaPsiFacade.getInstance(project).getElementFactory().createSubstitutor(map);
-          final PsiClassType classType = JavaPsiFacade.getInstance(project).getElementFactory()
-            .createType(javaLangClass, substitutor, languageLevel);
-          final PsiElement parent = call.getParent();
-          return parent instanceof PsiReferenceExpression && parent.getParent() instanceof PsiMethodCallExpression || parent instanceof PsiExpressionList
-                 ? PsiUtil.captureToplevelWildcards(classType, methodExpression) : classType;
-        }
+      PsiElement parent = call.getParent();
+      boolean captureTopLevelWildcards = parent instanceof PsiReferenceExpression && parent.getParent() instanceof PsiMethodCallExpression ||
+                                         parent instanceof PsiExpressionList;
+      return createJavaLangClassType(methodExpression, qualifierType, captureTopLevelWildcards);
+    }
+    return null;
+  }
+
+  public static boolean isGetClass(PsiMethod method) {
+    return GET_CLASS_METHOD.equals(method.getName()) && CommonClassNames.JAVA_LANG_OBJECT.equals(method.getContainingClass().getQualifiedName());
+  }
+
+  @Nullable
+  public static PsiType createJavaLangClassType(@NotNull PsiElement context, @Nullable PsiType qualifierType, boolean captureTopLevelWildcards) {
+    if (qualifierType != null) {
+      JavaPsiFacade facade = JavaPsiFacade.getInstance(context.getProject());
+      PsiClass javaLangClass = facade.findClass(CommonClassNames.JAVA_LANG_CLASS, context.getResolveScope());
+      if (javaLangClass != null && javaLangClass.getTypeParameters().length == 1) {
+        PsiSubstitutor substitutor = PsiSubstitutor.EMPTY.
+          put(javaLangClass.getTypeParameters()[0], PsiWildcardType.createExtends(context.getManager(), qualifierType));
+        final PsiClassType classType = facade.getElementFactory().createType(javaLangClass, substitutor, PsiUtil.getLanguageLevel(context));
+        return captureTopLevelWildcards ? PsiUtil.captureToplevelWildcards(classType, context) : classType;
       }
     }
     return null;
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 2fd2f9b..f6b2bbe 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
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -998,10 +998,14 @@
   public static PsiMethod getResourceCloserMethod(@NotNull final PsiResourceVariable resource) {
     final PsiType resourceType = resource.getType();
     if (!(resourceType instanceof PsiClassType)) return null;
-    final PsiClass resourceClass = ((PsiClassType)resourceType).resolve();
+    return getResourceCloserMethodForType((PsiClassType)resourceType, resource.getProject());
+  }
+
+  @Nullable
+  public static PsiMethod getResourceCloserMethodForType(@NotNull final PsiClassType resourceType, Project project) {
+    final PsiClass resourceClass = resourceType.resolve();
     if (resourceClass == null) return null;
 
-    final Project project = resource.getProject();
     final JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
     final PsiClass autoCloseable = facade.findClass(CommonClassNames.JAVA_LANG_AUTO_CLOSEABLE, ProjectScope.getLibrariesScope(project));
     if (autoCloseable == null) return null;
diff --git a/java/java-psi-api/src/messages/JavaCoreBundle.properties b/java/java-psi-api/src/messages/JavaCoreBundle.properties
index 31dc1a7..5ea4ebc 100644
--- a/java/java-psi-api/src/messages/JavaCoreBundle.properties
+++ b/java/java-psi-api/src/messages/JavaCoreBundle.properties
@@ -6,3 +6,4 @@
 jdk.1.6.language.level.description=6.0 - @Override in interfaces
 jdk.1.7.language.level.description=7.0 - Diamonds, ARM, multi-catch etc.
 jdk.1.8.language.level.description=8.0 - Lambdas, type annotations etc.
+jdk.1.9.language.level.description=9.0 - Jigsaw project etc.
diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java b/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java
index ada64c0..b989c30 100644
--- a/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java
+++ b/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java
@@ -537,7 +537,7 @@
   }
 
   @NotNull
-  private static List<PsiClassType> getUnhandledExceptions(@Nullable PsiMethod method,
+  public static List<PsiClassType> getUnhandledExceptions(@Nullable PsiMethod method,
                                                            PsiElement element,
                                                            PsiElement topElement,
                                                            @NotNull PsiSubstitutor substitutor) {
diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java
index c30aef7..a2f1dc9c 100644
--- a/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java
+++ b/java/java-psi-impl/src/com/intellij/codeInsight/javadoc/JavaDocInfoGenerator.java
@@ -42,7 +42,9 @@
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.ArrayUtilRt;
+import com.intellij.util.Function;
 import com.intellij.util.IncorrectOperationException;
+import com.intellij.xml.util.XmlStringUtil;
 import org.jdom.Document;
 import org.jdom.Element;
 import org.jdom.JDOMException;
@@ -260,7 +262,12 @@
         buffer.append("<html><body></body></html>");
       }
       String errorSection = "<p id=\"error\">Following external urls were checked:<br>&nbsp;&nbsp;&nbsp;<i>" +
-                   StringUtil.join(docURLs, "</i><br>&nbsp;&nbsp;&nbsp;<i>") +
+                   StringUtil.join(docURLs, new Function<String, String>() {
+                     @Override
+                     public String fun(String url) {
+                       return XmlStringUtil.escapeString(url);
+                     }
+                   }, "</i><br>&nbsp;&nbsp;&nbsp;<i>") +
                    "</i><br>The documentation for this element is not found. Please add all the needed paths to API docs in " +
                    "<a href=\"open://Project Settings\">Project Settings.</a></p>";
       buffer.insert(buffer.indexOf("<body>"), errorSection);
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java
index 7b44a49..a4fc56e 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsJavaCodeReferenceElementImpl.java
@@ -15,18 +15,21 @@
  */
 package com.intellij.psi.impl.compiled;
 
+import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.PsiSubstitutorImpl;
+import com.intellij.psi.impl.ResolveScopeManager;
 import com.intellij.psi.impl.cache.TypeInfo;
 import com.intellij.psi.impl.source.resolve.ResolveCache;
 import com.intellij.psi.impl.source.tree.JavaElementType;
 import com.intellij.psi.impl.source.tree.TreeElement;
 import com.intellij.psi.infos.CandidateInfo;
 import com.intellij.psi.scope.PsiScopeProcessor;
+import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.psi.util.TypeConversionUtil;
@@ -44,7 +47,7 @@
   private final String myQualifiedName;
   private final PsiReferenceParameterList myRefParameterList;
 
-  public ClsJavaCodeReferenceElementImpl(PsiElement parent, String canonicalText) {
+  public ClsJavaCodeReferenceElementImpl(PsiElement parent, @NotNull String canonicalText) {
     myParent = parent;
 
     String canonical = TypeInfo.internFrequentType(canonicalText);
@@ -88,20 +91,20 @@
     return myCanonicalText;
   }
 
-  private static class Resolver implements ResolveCache.PolyVariantResolver<ClsJavaCodeReferenceElementImpl> {
+  private static class Resolver implements ResolveCache.PolyVariantContextResolver<ClsJavaCodeReferenceElementImpl> {
     public static final Resolver INSTANCE = new Resolver();
 
     @NotNull
     @Override
-    public JavaResolveResult[] resolve(@NotNull ClsJavaCodeReferenceElementImpl ref, boolean incompleteCode) {
-      final JavaResolveResult resolveResult = ref.advancedResolveImpl();
+    public JavaResolveResult[] resolve(@NotNull ClsJavaCodeReferenceElementImpl ref, @NotNull PsiFile containingFile, boolean incompleteCode) {
+      final JavaResolveResult resolveResult = ref.advancedResolveImpl(containingFile);
       return resolveResult == null ? JavaResolveResult.EMPTY_ARRAY : new JavaResolveResult[] {resolveResult};
     }
   }
 
-  private JavaResolveResult advancedResolveImpl() {
+  private JavaResolveResult advancedResolveImpl(@NotNull PsiFile containingFile) {
     PsiTypeElement[] typeElements = myRefParameterList == null ? PsiTypeElement.EMPTY_ARRAY : myRefParameterList.getTypeParameterElements();
-    PsiElement resolve = resolveElement();
+    PsiElement resolve = resolveElement(containingFile);
     if (resolve == null) return null;
     if (resolve instanceof PsiClass) {
       Map<PsiTypeParameter, PsiType> substitutionMap = new HashMap<PsiTypeParameter, PsiType>();
@@ -137,7 +140,7 @@
     }
   }
 
-  private void collectOuterClassTypeArgs(final PsiClass psiClass,
+  private void collectOuterClassTypeArgs(@NotNull PsiClass psiClass,
                                          final String canonicalText,
                                          final Map<PsiTypeParameter, PsiType> substitutionMap) {
     final PsiClass containingClass = psiClass.getContainingClass();
@@ -179,7 +182,7 @@
   }
 
   @Nullable
-  private PsiElement resolveElement() {
+  private PsiElement resolveElement(@NotNull PsiFile containingFile) {
     PsiElement element = getParent();
     while(element != null && (!(element instanceof PsiClass) || element instanceof PsiTypeParameter)) {
       if(element instanceof PsiMethod){
@@ -199,16 +202,18 @@
     for (PsiTypeParameter parameter : PsiUtil.typeParametersIterable((PsiTypeParameterListOwner)element)) {
       if (myQualifiedName.equals(parameter.getName())) return parameter;
     }
-    return resolveClassPreferringMyJar();
+    return resolveClassPreferringMyJar(containingFile);
   }
 
   @Nullable
-  private PsiClass resolveClassPreferringMyJar() {
-    PsiClass[] classes = JavaPsiFacade.getInstance(getProject()).findClasses(myQualifiedName, getResolveScope());
+  private PsiClass resolveClassPreferringMyJar(@NotNull PsiFile containingFile) {
+    Project project = containingFile.getProject();
+    GlobalSearchScope scope = ResolveScopeManager.getInstance(project).getResolveScope(this);
+    PsiClass[] classes = JavaPsiFacade.getInstance(project).findClasses(myQualifiedName, scope);
     if (classes.length == 0) return null;
 
     if (classes.length > 1) {
-      VirtualFile jarFile = PsiUtil.getJarFile(this);
+      VirtualFile jarFile = PsiUtil.getJarFile(containingFile);
       if (jarFile != null) {
         for (PsiClass aClass : classes) {
           if (Comparing.equal(PsiUtil.getJarFile(aClass), jarFile)) return aClass;
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java
index 361f237..3508873 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiClassReferenceType.java
@@ -208,11 +208,10 @@
     if (myReference instanceof PsiJavaCodeReferenceElementImpl) {
       PsiAnnotation[] annotations = getAnnotations();
       if (!annotated || annotations.length == 0) annotations = null;
-      return ((PsiJavaCodeReferenceElementImpl)myReference).getCanonicalText(annotated, annotations);
+      PsiJavaCodeReferenceElementImpl impl = (PsiJavaCodeReferenceElementImpl)myReference;
+      return impl.getCanonicalText(annotated, annotations, impl.getContainingFile());
     }
-    else {
-      return myReference.getCanonicalText();
-    }
+    return myReference.getCanonicalText();
   }
 
   @NotNull
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java
index 5ee1243..1b60c15 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/PsiJavaCodeReferenceElementImpl.java
@@ -57,7 +57,7 @@
 
   private volatile String myCachedQName = null;
   private volatile String myCachedNormalizedText;
-  private int myKindWhenDummy = CLASS_NAME_KIND;
+  private volatile int myKindWhenDummy = CLASS_NAME_KIND;
 
   public static final int CLASS_NAME_KIND = 1;
   public static final int PACKAGE_NAME_KIND = 2;
@@ -92,8 +92,8 @@
     return type == TokenType.DUMMY_HOLDER || type == JavaElementType.DUMMY_ELEMENT;
   }
 
-  public int getKind() {
-    PsiUtilCore.ensureValid(this);
+  public int getKind(@NotNull PsiFile containingFile) {
+    PsiUtilCore.ensureValid(containingFile);
     CompositeElement treeParent = getTreeParent();
     IElementType i = treeParent.getElementType();
     if (isDummy(i)) {
@@ -142,7 +142,7 @@
       return CLASS_FQ_OR_PACKAGE_NAME_KIND;
     }
     if (i == JavaElementType.JAVA_CODE_REFERENCE) {
-      int parentKind = ((PsiJavaCodeReferenceElementImpl)treeParent).getKind();
+      int parentKind = ((PsiJavaCodeReferenceElementImpl)treeParent).getKind(containingFile);
       if (parentKind == CLASS_NAME_KIND) {
         return CLASS_OR_PACKAGE_NAME_KIND;
       }
@@ -256,16 +256,17 @@
   @Override
   @NotNull
   public String getCanonicalText() {
-    return getCanonicalText(false, null);
+    return getCanonicalText(false, null, getContainingFile());
   }
 
   @NotNull
-  public String getCanonicalText(boolean annotated, @Nullable PsiAnnotation[] annotations) {
-    switch (getKind()) {
+  public String getCanonicalText(boolean annotated, @Nullable PsiAnnotation[] annotations, @NotNull PsiFile containingFile) {
+    switch (getKind(containingFile)) {
       case CLASS_NAME_KIND:
       case CLASS_OR_PACKAGE_NAME_KIND:
       case CLASS_IN_QUALIFIED_NEW_KIND:
-        final PsiElement target = resolve();
+        JavaResolveResult[] results = multiResolve(false, containingFile, containingFile.getProject());
+        final PsiElement target = results.length == 1 ? results[0].getElement() : null;
         if (target instanceof PsiClass) {
           PsiClass aClass = (PsiClass)target;
           StringBuilder buffer = new StringBuilder();
@@ -273,7 +274,7 @@
           PsiElement qualifier = getQualifier();
           String prefix = null;
           if (qualifier instanceof PsiJavaCodeReferenceElementImpl) {
-            prefix = ((PsiJavaCodeReferenceElementImpl)qualifier).getCanonicalText(annotated, null);
+            prefix = ((PsiJavaCodeReferenceElementImpl)qualifier).getCanonicalText(annotated, null, containingFile);
           }
           else {
             String fqn = aClass.getQualifiedName();
@@ -327,15 +328,14 @@
     return advancedResolve(false).getElement();
   }
 
-  private static final class OurGenericsResolver implements ResolveCache.PolyVariantResolver<PsiJavaReference> {
+  private static final class OurGenericsResolver implements ResolveCache.PolyVariantContextResolver<PsiJavaReference> {
     private static final OurGenericsResolver INSTANCE = new OurGenericsResolver();
 
     @NotNull
     @Override
-    public JavaResolveResult[] resolve(@NotNull PsiJavaReference ref, boolean incompleteCode) {
+    public ResolveResult[] resolve(@NotNull PsiJavaReference ref, @NotNull PsiFile containingFile, boolean incompleteCode) {
       PsiJavaCodeReferenceElementImpl referenceElement = (PsiJavaCodeReferenceElementImpl)ref;
-      int kind = referenceElement.getKind();
-      PsiFile containingFile = referenceElement.getContainingFile();
+      int kind = referenceElement.getKind(containingFile);
       JavaResolveResult[] result = referenceElement.resolve(kind, containingFile);
 
       if (incompleteCode && result.length == 0 && kind != CLASS_FQ_NAME_KIND && kind != CLASS_FQ_OR_PACKAGE_NAME_KIND) {
@@ -347,7 +347,7 @@
         }
       }
 
-      JavaResolveUtil.substituteResults((PsiJavaCodeReferenceElement)ref, result);
+      JavaResolveUtil.substituteResults(referenceElement, result);
 
       return result;
     }
@@ -373,16 +373,21 @@
       LOG.error("getManager() == null!");
       return JavaResolveResult.EMPTY_ARRAY;
     }
-    PsiFile file = SharedImplUtil.getContainingFile(fileElement);
-    boolean valid = file != null && file.isValid();
+    PsiFile containingFile = SharedImplUtil.getContainingFile(fileElement);
+    boolean valid = containingFile != null && containingFile.isValid();
     if (!valid) {
       LOG.error("invalid!");
       return JavaResolveResult.EMPTY_ARRAY;
     }
     Project project = manager.getProject();
 
+    return multiResolve(incompleteCode, containingFile, project);
+  }
+
+  @NotNull
+  private JavaResolveResult[] multiResolve(boolean incompleteCode, @NotNull PsiFile containingFile, @NotNull Project project) {
     final ResolveCache resolveCache = ResolveCache.getInstance(project);
-    final ResolveResult[] results = resolveCache.resolveWithCaching(this, OurGenericsResolver.INSTANCE, true, incompleteCode, file);
+    final ResolveResult[] results = resolveCache.resolveWithCaching(this, OurGenericsResolver.INSTANCE, true, incompleteCode, containingFile);
     return results.length == 0 ? JavaResolveResult.EMPTY_ARRAY : (JavaResolveResult[])results;
   }
 
@@ -394,14 +399,15 @@
     return subst;
   }
 
-  private JavaResolveResult[] resolve(final int kind, PsiFile containingFile) {
+  @NotNull
+  private JavaResolveResult[] resolve(final int kind, @NotNull PsiFile containingFile) {
     switch (kind) {
       case CLASS_FQ_NAME_KIND: {
         // TODO: support type parameters in FQ names
         String text = getNormalizedText();
         if (StringUtil.isEmptyOrSpaces(text)) return JavaResolveResult.EMPTY_ARRAY;
 
-        PsiClass aClass = JavaPsiFacade.getInstance(getProject()).findClass(text, getResolveScope());
+        PsiClass aClass = JavaPsiFacade.getInstance(containingFile.getProject()).findClass(text, getResolveScope());
         if (aClass == null) return JavaResolveResult.EMPTY_ARRAY;
 
         if (!isQualified() && text.equals(aClass.getQualifiedName())) {
@@ -503,16 +509,17 @@
 
   @Override
   public PsiElement bindToElement(@NotNull final PsiElement element) throws IncorrectOperationException {
-    CheckUtil.checkWritable(this);
+    PsiFile containingFile = getContainingFile();
+    CheckUtil.checkWritable(containingFile);
     if (isReferenceTo(element)) return this;
 
-    switch (getKind()) {
+    switch (getKind(containingFile)) {
       case CLASS_NAME_KIND:
       case CLASS_FQ_NAME_KIND:
         if (!(element instanceof PsiClass)) {
           throw cannotBindError(element);
         }
-        return bindToClass((PsiClass)element);
+        return bindToClass((PsiClass)element, containingFile);
 
       case PACKAGE_NAME_KIND:
         if (!(element instanceof PsiPackage)) {
@@ -523,7 +530,7 @@
       case CLASS_OR_PACKAGE_NAME_KIND:
       case CLASS_FQ_OR_PACKAGE_NAME_KIND:
         if (element instanceof PsiClass) {
-          return bindToClass((PsiClass)element);
+          return bindToClass((PsiClass)element, containingFile);
         }
         else if (element instanceof PsiPackage) {
           return bindToPackage((PsiPackage)element);
@@ -538,7 +545,7 @@
           if (name == null) {
             throw new IncorrectOperationException(aClass.toString());
           }
-          final PsiJavaParserFacade parserFacade = JavaPsiFacade.getInstance(getProject()).getParserFacade();
+          final PsiJavaParserFacade parserFacade = JavaPsiFacade.getInstance(containingFile.getProject()).getParserFacade();
           final PsiJavaCodeReferenceElement ref = parserFacade.createReferenceFromText(name, getParent());
           getTreeParent().replaceChildInternal(this, (TreeElement)ref.getNode());
           return ref;
@@ -557,10 +564,11 @@
     return new IncorrectOperationException("Cannot bind to " + element);
   }
 
-  private PsiElement bindToClass(PsiClass aClass) throws IncorrectOperationException {
+  private PsiElement bindToClass(@NotNull PsiClass aClass, @NotNull PsiFile containingFile) throws IncorrectOperationException {
     String qName = aClass.getQualifiedName();
-    boolean preserveQualification = JavaCodeStyleSettingsFacade.getInstance(getProject()).useFQClassNames() && isFullyQualified();
-    JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
+    Project project = containingFile.getProject();
+    boolean preserveQualification = JavaCodeStyleSettingsFacade.getInstance(project).useFQClassNames() && isFullyQualified(containingFile);
+    JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
     if (qName == null) {
       qName = aClass.getName();
       PsiClass psiClass = facade.getResolveHelper().resolveReferencedClass(qName, this);
@@ -583,7 +591,7 @@
     ((PsiJavaCodeReferenceElementImpl)ref).setAnnotations(annotations);
 
     if (!preserveQualification) {
-      JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(aClass.getProject());
+      JavaCodeStyleManager codeStyleManager = JavaCodeStyleManager.getInstance(project);
       ref = (PsiJavaCodeReferenceElement)codeStyleManager.shortenClassReferences(ref, JavaCodeStyleManager.UNCOMPLETE_CODE);
     }
 
@@ -631,8 +639,8 @@
     }
   }
 
-  private boolean isFullyQualified() {
-    switch (getKind()) {
+  private boolean isFullyQualified(@NotNull PsiFile containingFile) {
+    switch (getKind(containingFile)) {
       case CLASS_OR_PACKAGE_NAME_KIND:
         if (resolve() instanceof PsiPackage) return true;
         //noinspection fallthrough
@@ -656,10 +664,10 @@
     final PsiElement refElement = SourceTreeToPsiMap.<PsiJavaCodeReferenceElement>treeToPsiNotNull(qualifier).resolve();
     if (refElement instanceof PsiPackage) return true;
 
-    return SourceTreeToPsiMap.<PsiJavaCodeReferenceElementImpl>treeToPsiNotNull(qualifier).isFullyQualified();
+    return SourceTreeToPsiMap.<PsiJavaCodeReferenceElementImpl>treeToPsiNotNull(qualifier).isFullyQualified(containingFile);
   }
 
-  private PsiElement bindToPackage(final PsiPackage aPackage) throws IncorrectOperationException {
+  private PsiElement bindToPackage(@NotNull PsiPackage aPackage) throws IncorrectOperationException {
     final String qName = aPackage.getQualifiedName();
     if (qName.isEmpty()) {
       throw new IncorrectOperationException("Cannot bind to default package: "+aPackage);
@@ -672,7 +680,12 @@
 
   @Override
   public boolean isReferenceTo(final PsiElement element) {
-    switch (getKind()) {
+    PsiFile containingFile = getContainingFile();
+    return isReferenceTo(element, containingFile);
+  }
+
+  private boolean isReferenceTo(PsiElement element, @NotNull PsiFile containingFile) {
+    switch (getKind(containingFile)) {
       case CLASS_NAME_KIND:
       case CLASS_IN_QUALIFIED_NEW_KIND:
         if (!(element instanceof PsiClass)) return false;
@@ -681,44 +694,40 @@
       case CLASS_FQ_NAME_KIND: {
         if (!(element instanceof PsiClass)) return false;
         final String qName = ((PsiClass)element).getQualifiedName();
-        return qName != null && qName.equals(getCanonicalText());
+        return qName != null && qName.equals(getCanonicalText(false, null, containingFile));
       }
 
       case PACKAGE_NAME_KIND: {
         if (!(element instanceof PsiPackage)) return false;
         final String qName = ((PsiPackage)element).getQualifiedName();
-        return qName.equals(getCanonicalText());
+        return qName.equals(getCanonicalText(false, null, containingFile));
       }
 
       case CLASS_OR_PACKAGE_NAME_KIND:
         //        if (lastChild.type != IDENTIFIER) return false;
         if (element instanceof PsiPackage) {
           final String qName = ((PsiPackage)element).getQualifiedName();
-          return qName.equals(getCanonicalText());
+          return qName.equals(getCanonicalText(false, null, containingFile));
         }
-        else if (element instanceof PsiClass) {
+        if (element instanceof PsiClass) {
           final PsiIdentifier nameIdentifier = ((PsiClass)element).getNameIdentifier();
           if (nameIdentifier == null) return false;
           PsiElement nameElement = getReferenceNameElement();
           return nameElement != null && nameElement.textMatches(nameIdentifier) &&
-                 element.getManager().areElementsEquivalent(resolve(), element);
+                 containingFile.getManager().areElementsEquivalent(resolve(), element);
         }
-        else {
-          return false;
-        }
+        return false;
 
       case CLASS_FQ_OR_PACKAGE_NAME_KIND:
         if (element instanceof PsiClass) {
           final String qName = ((PsiClass)element).getQualifiedName();
-          return qName != null && qName.equals(getCanonicalText());
+          return qName != null && qName.equals(getCanonicalText(false, null, containingFile));
         }
-        else if (element instanceof PsiPackage) {
+        if (element instanceof PsiPackage) {
           final String qName = ((PsiPackage)element).getQualifiedName();
-          return qName.equals(getCanonicalText());
+          return qName.equals(getCanonicalText(false, null, containingFile));
         }
-        else {
-          return false;
-        }
+        return false;
       default:
         LOG.assertTrue(false);
         return true;
@@ -727,7 +736,7 @@
     final ASTNode referenceNameElement = getReferenceNameNode();
     if (referenceNameElement == null || referenceNameElement.getElementType() != JavaTokenType.IDENTIFIER) return false;
     final String name = ((PsiClass)element).getName();
-    return name != null && referenceNameElement.getText().equals(name) && element.getManager().areElementsEquivalent(resolve(), element);
+    return name != null && referenceNameElement.getText().equals(name) && containingFile.getManager().areElementsEquivalent(resolve(), element);
   }
 
   private String getNormalizedText() {
@@ -748,8 +757,8 @@
   }
 
   @Override
-  public void fullyQualify(final PsiClass targetClass) {
-    final int kind = getKind();
+  public void fullyQualify(@NotNull final PsiClass targetClass) {
+    final int kind = getKind(getContainingFile());
     if (kind != CLASS_NAME_KIND && kind != CLASS_OR_PACKAGE_NAME_KIND && kind != CLASS_IN_QUALIFIED_NEW_KIND) {
       LOG.error("Wrong kind " + kind);
       return;
@@ -778,32 +787,31 @@
   @NotNull
   public Object[] getVariants() {
     final ElementFilter filter;
-    switch (getKind()) {
-
-    case CLASS_OR_PACKAGE_NAME_KIND:
-           filter = new OrFilter();
-             ((OrFilter)filter).addFilter(ElementClassFilter.CLASS);
-             ((OrFilter)filter).addFilter(ElementClassFilter.PACKAGE_FILTER);
-           break;
-    case CLASS_NAME_KIND:
-           filter = ElementClassFilter.CLASS;
-           break;
-    case PACKAGE_NAME_KIND:
-           filter = ElementClassFilter.PACKAGE_FILTER;
-           break;
-    case CLASS_FQ_NAME_KIND:
-    case CLASS_FQ_OR_PACKAGE_NAME_KIND:
-           filter = new OrFilter();
-             ((OrFilter)filter).addFilter(ElementClassFilter.PACKAGE_FILTER);
-           if (isQualified()) {
-               ((OrFilter)filter).addFilter(ElementClassFilter.CLASS);
-           }
-           break;
-    case CLASS_IN_QUALIFIED_NEW_KIND:
-           filter = ElementClassFilter.CLASS;
-           break;
-    default:
-           throw new RuntimeException("Unknown reference type");
+    switch (getKind(getContainingFile())) {
+      case CLASS_OR_PACKAGE_NAME_KIND:
+        filter = new OrFilter();
+        ((OrFilter)filter).addFilter(ElementClassFilter.CLASS);
+        ((OrFilter)filter).addFilter(ElementClassFilter.PACKAGE_FILTER);
+        break;
+      case CLASS_NAME_KIND:
+        filter = ElementClassFilter.CLASS;
+        break;
+      case PACKAGE_NAME_KIND:
+        filter = ElementClassFilter.PACKAGE_FILTER;
+        break;
+      case CLASS_FQ_NAME_KIND:
+      case CLASS_FQ_OR_PACKAGE_NAME_KIND:
+        filter = new OrFilter();
+        ((OrFilter)filter).addFilter(ElementClassFilter.PACKAGE_FILTER);
+        if (isQualified()) {
+          ((OrFilter)filter).addFilter(ElementClassFilter.CLASS);
+        }
+        break;
+      case CLASS_IN_QUALIFIED_NEW_KIND:
+        filter = ElementClassFilter.CLASS;
+        break;
+      default:
+        throw new RuntimeException("Unknown reference type");
     }
 
     return PsiImplUtil.getReferenceVariantsByFilter(this, filter);
@@ -821,7 +829,7 @@
       filter.addFilter(new AndFilter(ElementClassFilter.METHOD, new NotFilter(new ConstructorFilter())));
       filter.addFilter(ElementClassFilter.VARIABLE);
     }
-    switch (getKind()) {
+    switch (getKind(getContainingFile())) {
       case CLASS_OR_PACKAGE_NAME_KIND:
         filter.addFilter(ElementClassFilter.CLASS);
         filter.addFilter(ElementClassFilter.PACKAGE_FILTER);
@@ -899,7 +907,7 @@
 
   @Override
   public String getQualifiedName() {
-    switch (getKind()) {
+    switch (getKind(getContainingFile())) {
       case CLASS_NAME_KIND:
       case CLASS_OR_PACKAGE_NAME_KIND:
       case CLASS_IN_QUALIFIED_NEW_KIND:
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/SourceJavaCodeReference.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/SourceJavaCodeReference.java
index cd3d5e4..9680725 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/SourceJavaCodeReference.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/SourceJavaCodeReference.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.psi.PsiClass;
 import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * This interface should be implemented by all PsiJavaCodeReference implementations
@@ -35,9 +36,8 @@
    * Helper method for ReferenceAdjuster. Tries to qualify this reference as if
    * it references <code>targetClass</code>. Does not check that it indeed references
    * targetClass
-   * @param targetClass
    */
-  void fullyQualify(PsiClass targetClass);
+  void fullyQualify(@NotNull PsiClass targetClass);
 
   boolean isQualified();
 
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java
index b109372..a2e5593 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ClassResolverProcessor.java
@@ -35,6 +35,8 @@
   private static final String[] DEFAULT_PACKAGES = {CommonClassNames.DEFAULT_PACKAGE};
 
   private final String myClassName;
+  @NotNull
+  private final PsiFile myContainingFile;
   private final PsiElement myPlace;
   private PsiClass myAccessClass = null;
   private List<ClassCandidateInfo> myCandidates = null;
@@ -43,8 +45,9 @@
   private JavaResolveResult[] myResult = JavaResolveResult.EMPTY_ARRAY;
   private PsiElement myCurrentFileContext;
 
-  public ClassResolverProcessor(String className, @NotNull PsiElement startPlace, PsiFile containingFile) {
+  public ClassResolverProcessor(@NotNull String className, @NotNull PsiElement startPlace, @NotNull PsiFile containingFile) {
     myClassName = className;
+    myContainingFile = containingFile;
     PsiElement place = containingFile instanceof JavaCodeFragment && ((JavaCodeFragment)containingFile).getVisibilityChecker() != null ? null : startPlace;
     myPlace = place;
     if (place instanceof PsiJavaCodeReferenceElement) {
@@ -111,7 +114,7 @@
     String fqn = psiClass.getQualifiedName();
     if (fqn == null) return false;
 
-    PsiFile file = myPlace == null ? null : FileContextUtil.getContextFile(myPlace);
+    PsiFile file = myPlace == null ? null : FileContextUtil.getContextFile(myContainingFile);
 
     String[] defaultPackages = file instanceof PsiJavaFile ? ((PsiJavaFile)file).getImplicitlyImportedPackages() : DEFAULT_PACKAGES;
     String packageName = StringUtil.getPackageName(fqn);
@@ -123,9 +126,8 @@
     return file instanceof PsiJavaFile && ((PsiJavaFile)file).getPackageName().equals(packageName);
   }
 
-  private Domination dominates(PsiClass aClass, boolean accessible, String fqName, ClassCandidateInfo info) {
+  private Domination dominates(@NotNull PsiClass aClass, boolean accessible, @NotNull String fqName, @NotNull ClassCandidateInfo info) {
     final PsiClass otherClass = info.getElement();
-    assert otherClass != null;
     String otherQName = otherClass.getQualifiedName();
     if (fqName.equals(otherQName)) {
       return Domination.DOMINATED_BY;
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java
index 20db589..ebeebe2 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/JavaResolveUtil.java
@@ -225,7 +225,7 @@
     return true;
   }
 
-  public static void substituteResults(final @NotNull PsiJavaCodeReferenceElement ref, @NotNull JavaResolveResult[] result) {
+  public static void substituteResults(@NotNull final PsiJavaCodeReferenceElement ref, @NotNull JavaResolveResult[] result) {
     if (result.length > 0 && result[0].getElement() instanceof PsiClass) {
       for (int i = 0; i < result.length; i++) {
         final CandidateInfo resolveResult = (CandidateInfo)result[i];
@@ -247,7 +247,7 @@
 
   @NotNull
   public static <T extends PsiPolyVariantReference> JavaResolveResult[] resolveWithContainingFile(@NotNull T ref,
-                                                                                                  @NotNull ResolveCache.PolyVariantResolver<T> resolver,
+                                                                                                  @NotNull ResolveCache.PolyVariantContextResolver<T> resolver,
                                                                                                   boolean needToPreventRecursion,
                                                                                                   boolean incompleteCode,
                                                                                                   @NotNull PsiFile containingFile) {
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 59c8d7f..556bf71 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
@@ -80,8 +80,9 @@
     final PsiJavaParserFacade parserFacade = JavaPsiFacade.getInstance(myManager.getProject()).getParserFacade();
     try {
       final PsiJavaCodeReferenceElement ref = parserFacade.createReferenceFromText(referenceText, context);
-      LOG.assertTrue(ref.isValid(), referenceText);
-      return ResolveClassUtil.resolveClass(ref);
+      PsiFile containingFile = ref.getContainingFile();
+      LOG.assertTrue(containingFile.isValid(), referenceText);
+      return ResolveClassUtil.resolveClass(ref, containingFile);
     }
     catch (IncorrectOperationException e) {
       return null;
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ResolveClassUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ResolveClassUtil.java
index 9c3505c..2bedff6 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ResolveClassUtil.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/ResolveClassUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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,15 +20,16 @@
 import com.intellij.psi.impl.source.PsiJavaCodeReferenceElementImpl;
 import com.intellij.psi.scope.util.PsiScopesUtil;
 import com.intellij.psi.util.PsiUtil;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 public class ResolveClassUtil {
   private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.resolve.ResolveClassUtil");
 
   @Nullable
-  public static PsiClass resolveClass(PsiJavaCodeReferenceElement ref) {
+  public static PsiClass resolveClass(@NotNull PsiJavaCodeReferenceElement ref, @NotNull PsiFile containingFile) {
     if (ref instanceof PsiJavaCodeReferenceElementImpl &&
-        ((PsiJavaCodeReferenceElementImpl)ref).getKind() == PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND) {
+        ((PsiJavaCodeReferenceElementImpl)ref).getKind(containingFile) == PsiJavaCodeReferenceElementImpl.CLASS_IN_QUALIFIED_NEW_KIND) {
       PsiElement parent = ref.getParent();
       if (parent instanceof PsiAnonymousClass){
         parent = parent.getParent();
@@ -63,7 +64,7 @@
     long time1 = System.currentTimeMillis();
     */
 
-    ClassResolverProcessor processor = new ClassResolverProcessor(className, ref, ref.getContainingFile());
+    ClassResolverProcessor processor = new ClassResolverProcessor(className, ref, containingFile);
     PsiScopesUtil.resolveAndWalk(processor, ref, null);
 
 
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/VariableResolverProcessor.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/VariableResolverProcessor.java
index ead814a..123e750 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/VariableResolverProcessor.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/VariableResolverProcessor.java
@@ -41,7 +41,7 @@
   private final PsiClass myAccessClass;
   private PsiElement myCurrentFileContext = null;
 
-  public VariableResolverProcessor(@NotNull PsiJavaCodeReferenceElement place, PsiFile placeFile) {
+  public VariableResolverProcessor(@NotNull PsiJavaCodeReferenceElement place, @NotNull PsiFile placeFile) {
     super(place.getText(), ourFilter, new PsiConflictResolver[]{new JavaVariableConflictResolver()}, new SmartList<CandidateInfo>(), place, placeFile);
 
     PsiElement referenceName = place.getReferenceNameElement();
@@ -54,16 +54,20 @@
       final JavaResolveResult accessClass = PsiUtil.getAccessObjectClass((PsiExpression)qualifier);
       final PsiElement element = accessClass.getElement();
       if (element instanceof PsiTypeParameter) {
-        PsiElementFactory factory = JavaPsiFacade.getInstance(element.getProject()).getElementFactory();
+        PsiElementFactory factory = JavaPsiFacade.getInstance(placeFile.getProject()).getElementFactory();
         final PsiClassType type = factory.createType((PsiTypeParameter)element);
         final PsiType accessType = accessClass.getSubstitutor().substitute(type);
         if (accessType instanceof PsiArrayType) {
-          LanguageLevel languageLevel = PsiUtil.getLanguageLevel(qualifier);
+          LanguageLevel languageLevel = PsiUtil.getLanguageLevel(placeFile);
           access = factory.getArrayClass(languageLevel);
         }
-        else if (accessType instanceof PsiClassType) access = ((PsiClassType)accessType).resolve();
+        else if (accessType instanceof PsiClassType) {
+          access = ((PsiClassType)accessType).resolve();
+        }
       }
-      else if (element instanceof PsiClass) access = (PsiClass)element;
+      else if (element instanceof PsiClass) {
+        access = (PsiClass)element;
+      }
     }
     myAccessClass = access;
   }
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java
index 3614624..9d9c373 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/InferenceSession.java
@@ -1070,7 +1070,7 @@
           session.addConstraint(new StrictSubtypingConstraint(tReturnType, sReturnType));
           return true;
         } else {
-          return TypeConversionUtil.isAssignable(sReturnType, tReturnType); 
+          return sReturnType != null && tReturnType != null && TypeConversionUtil.isAssignable(tReturnType, sReturnType); 
         }
       }
     }
@@ -1115,7 +1115,7 @@
         session.addConstraint(new StrictSubtypingConstraint(tReturnType, sReturnType));
         return true;
       } else {
-        return TypeConversionUtil.isAssignable(sReturnType, tReturnType);
+        return sReturnType != null && tReturnType != null && TypeConversionUtil.isAssignable(tReturnType, sReturnType);
       }
     }
 
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java
index 6ff1709..67097df 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/InputOutputConstraintFormula.java
@@ -65,7 +65,10 @@
             }
           }
 
-          collectReturnTypeVariables(session, psiExpression, substitutor.substitute(interfaceMethod.getReturnType()), result);
+          final PsiType returnType = interfaceMethod.getReturnType();
+          if (returnType != null) {
+            collectReturnTypeVariables(session, psiExpression, substitutor.substitute(returnType), result);
+          }
 
           return result;
         }
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaSourceUtil.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaSourceUtil.java
index f163624..8cf5b5b 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaSourceUtil.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaSourceUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -19,11 +19,12 @@
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.SourceJavaCodeReference;
 import com.intellij.util.CharTable;
+import org.jetbrains.annotations.NotNull;
 
 public class JavaSourceUtil {
   private JavaSourceUtil() { }
 
-  public static void fullyQualifyReference(final CompositeElement reference, final PsiClass targetClass) {
+  public static void fullyQualifyReference(@NotNull CompositeElement reference, @NotNull PsiClass targetClass) {
     if (((SourceJavaCodeReference)reference).isQualified()) { // qualified reference
       final PsiClass parentClass = targetClass.getContainingClass();
       if (parentClass == null) return;
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaTreeGenerator.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaTreeGenerator.java
index 918d7fe..c310f5e 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaTreeGenerator.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/JavaTreeGenerator.java
@@ -85,7 +85,7 @@
 
         boolean isFQ = false;
         if (original instanceof PsiJavaCodeReferenceElementImpl) {
-          int kind = ((PsiJavaCodeReferenceElementImpl)original).getKind();
+          int kind = ((PsiJavaCodeReferenceElementImpl)original).getKind(original.getContainingFile());
           switch (kind) {
             case PsiJavaCodeReferenceElementImpl.CLASS_OR_PACKAGE_NAME_KIND:
             case PsiJavaCodeReferenceElementImpl.CLASS_NAME_KIND:
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java
index cf25710..503cbf4 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/MethodReferenceResolver.java
@@ -41,14 +41,13 @@
 import java.util.List;
 import java.util.Map;
 
-class MethodReferenceResolver implements ResolveCache.PolyVariantResolver<PsiMethodReferenceExpression> {
+class MethodReferenceResolver implements ResolveCache.PolyVariantContextResolver<PsiMethodReferenceExpressionImpl> {
   private static final Logger LOG = Logger.getInstance("#" + MethodReferenceResolver.class.getName());
 
   @NotNull
   @Override
-  public ResolveResult[] resolve(@NotNull final PsiMethodReferenceExpression reference, boolean incompleteCode) {
-    final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(
-      reference);
+  public JavaResolveResult[] resolve(@NotNull final PsiMethodReferenceExpressionImpl reference, @NotNull final PsiFile containingFile, boolean incompleteCode) {
+    final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(reference);
 
     final PsiClass containingClass = qualifierResolveResult.getContainingClass();
     PsiSubstitutor substitutor = qualifierResolveResult.getSubstitutor();
@@ -87,7 +86,7 @@
 
         final PsiConflictResolver conflictResolver = createResolver(reference, qualifierResolveResult, interfaceMethod, signature);
         final MethodCandidatesProcessor processor =
-          new MethodCandidatesProcessor(reference, reference.getContainingFile(), new PsiConflictResolver[] {conflictResolver}, new SmartList<CandidateInfo>()) {
+          new MethodCandidatesProcessor(reference, containingFile, new PsiConflictResolver[] {conflictResolver}, new SmartList<CandidateInfo>()) {
             @Override
             protected boolean acceptVarargs() {
               return true;
@@ -156,7 +155,11 @@
                       final PsiSubstitutor receiverSubstitutor = pClass != null ? TypeConversionUtil
                         .getClassSubstitutor(containingClass, pClass, pResult.getSubstitutor()) : null;
                       if (receiverSubstitutor != null) {
-                        if (!method.hasTypeParameters() && signature.getParameterTypes().length == 1) return receiverSubstitutor;
+                        if (!method.hasTypeParameters()) {
+                          if (signature.getParameterTypes().length == 1 || PsiUtil.isRawSubstitutor(containingClass, receiverSubstitutor)) {
+                            return receiverSubstitutor;
+                          }
+                        }
                         psiSubstitutor = receiverSubstitutor;
                       }
                     }
@@ -175,7 +178,7 @@
                     return substitutor;
                   }
 
-                  if (interfaceMethodReturnType != PsiType.VOID) {
+                  if (interfaceMethodReturnType != PsiType.VOID && interfaceMethodReturnType != null) {
                     final PsiType returnType = method.isConstructor() ? composeReturnType(containingClass, substitutor) : method.getReturnType();
                     if (returnType != null) {
                       session.registerConstraints(returnType, interfaceMethodReturnType);
@@ -241,7 +244,7 @@
     return functionalInterfaceType;
   }
 
-  protected PsiConflictResolver createResolver(PsiMethodReferenceExpression referenceExpression,
+  protected PsiConflictResolver createResolver(PsiMethodReferenceExpressionImpl referenceExpression,
                                                PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult,
                                                PsiMethod interfaceMethod,
                                                MethodSignature signature) {
@@ -257,11 +260,11 @@
 
   private static class MethodReferenceConflictResolver extends JavaMethodsConflictResolver {
     private final MethodSignature mySignature;
-    private PsiMethodReferenceExpression myReferenceExpression;
+    private final PsiMethodReferenceExpressionImpl myReferenceExpression;
     private final PsiMethodReferenceUtil.QualifierResolveResult myQualifierResolveResult;
     private final boolean myFunctionalMethodVarArgs;
 
-    private MethodReferenceConflictResolver(PsiMethodReferenceExpression referenceExpression, 
+    private MethodReferenceConflictResolver(PsiMethodReferenceExpressionImpl referenceExpression,
                                             PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult,
                                             @Nullable MethodSignature signature, boolean varArgs) {
       super(referenceExpression, signature != null ? signature.getParameterTypes() : PsiType.EMPTY_ARRAY, PsiUtil.getLanguageLevel(referenceExpression));
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java
index 7a82b24..311b161 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiMethodReferenceExpressionImpl.java
@@ -47,6 +47,7 @@
 
 public class PsiMethodReferenceExpressionImpl extends PsiReferenceExpressionBase implements PsiMethodReferenceExpression {
   private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.source.tree.java.PsiMethodReferenceExpressionImpl");
+  private static final MethodReferenceResolver RESOLVER = new MethodReferenceResolver();
 
   public PsiMethodReferenceExpressionImpl() {
     super(JavaElementType.METHOD_REF_EXPRESSION);
@@ -77,7 +78,7 @@
 
     final MethodReferenceResolver resolver = new MethodReferenceResolver() {
       @Override
-      protected PsiConflictResolver createResolver(PsiMethodReferenceExpression referenceExpression,
+      protected PsiConflictResolver createResolver(PsiMethodReferenceExpressionImpl referenceExpression,
                                                    PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult,
                                                    PsiMethod interfaceMethod,
                                                    MethodSignature signature) {
@@ -90,7 +91,7 @@
       }
     };
 
-    final ResolveResult[] result = resolver.resolve(this, false);
+    final ResolveResult[] result = resolver.resolve(this, getContainingFile(), false);
     final PsiMethodReferenceUtil.QualifierResolveResult qualifierResolveResult = PsiMethodReferenceUtil.getQualifierResolveResult(this);
     final int interfaceArity = interfaceMethod.getParameterList().getParametersCount();
     for (ResolveResult resolveResult : result) {
@@ -262,12 +263,11 @@
       LOG.error("invalid!");
       return JavaResolveResult.EMPTY_ARRAY;
     }
-    final MethodReferenceResolver resolver = new MethodReferenceResolver();
     final Map<PsiMethodReferenceExpression, PsiType> map = PsiMethodReferenceUtil.ourRefs.get();
     if (map != null && map.containsKey(this)) {
-      return (JavaResolveResult[])resolver.resolve(this, incompleteCode);
+      return RESOLVER.resolve(this, file, incompleteCode);
     }
-    ResolveResult[] results = ResolveCache.getInstance(getProject()).resolveWithCaching(this, resolver, true, incompleteCode,file);
+    ResolveResult[] results = ResolveCache.getInstance(getProject()).resolveWithCaching(this, RESOLVER, true, incompleteCode, file);
     return results.length == 0 ? JavaResolveResult.EMPTY_ARRAY : (JavaResolveResult[])results;
   }
 
@@ -421,9 +421,7 @@
     if (interfaceMethod != null) {
       final PsiType interfaceReturnType = LambdaUtil.getFunctionalInterfaceReturnType(left);
 
-      LOG.assertTrue(interfaceReturnType != null);
-
-      if (interfaceReturnType == PsiType.VOID) {
+      if (interfaceReturnType == PsiType.VOID || interfaceReturnType == null) {
         return true;
       }
 
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiNewExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiNewExpressionImpl.java
index dc8f0bb..7862a73 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiNewExpressionImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiNewExpressionImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -136,12 +136,12 @@
     return new PsiPolyVariantCachingReference() {
       @Override
       @NotNull
-      public JavaResolveResult[] resolveInner(boolean incompleteCode) {
+      public JavaResolveResult[] resolveInner(boolean incompleteCode, @NotNull PsiFile containingFile) {
         ASTNode classRef = findChildByRole(ChildRole.TYPE_REFERENCE);
         if (classRef != null) {
           ASTNode argumentList = PsiImplUtil.skipWhitespaceAndComments(classRef.getTreeNext());
           if (argumentList != null && argumentList.getElementType() == JavaElementType.EXPRESSION_LIST) {
-            final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
+            final JavaPsiFacade facade = JavaPsiFacade.getInstance(containingFile.getProject());
             PsiType aClass = facade.getElementFactory().createType((PsiJavaCodeReferenceElement)SourceTreeToPsiMap.treeElementToPsi(classRef));
             return facade.getResolveHelper().multiResolveConstructor((PsiClassType)aClass,
                                                                       (PsiExpressionList)SourceTreeToPsiMap.treeElementToPsi(argumentList),
@@ -151,7 +151,7 @@
         else{
           ASTNode anonymousClassElement = findChildByType(JavaElementType.ANONYMOUS_CLASS);
           if (anonymousClassElement != null) {
-            final JavaPsiFacade facade = JavaPsiFacade.getInstance(getProject());
+            final JavaPsiFacade facade = JavaPsiFacade.getInstance(containingFile.getProject());
             final PsiAnonymousClass anonymousClass = (PsiAnonymousClass)SourceTreeToPsiMap.treeElementToPsi(anonymousClassElement);
             PsiType aClass = anonymousClass.getBaseClassType();
             ASTNode argumentList = anonymousClassElement.findChildByType(JavaElementType.EXPRESSION_LIST);
@@ -176,7 +176,7 @@
       @Override
       @NotNull
       public String getCanonicalText() {
-        return null;
+        throw new UnsupportedOperationException();
       }
 
       @Override
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java
index f91f01c..02ffaa6 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/tree/java/PsiReferenceExpressionImpl.java
@@ -181,23 +181,22 @@
     super.clearCaches();
   }
 
-  public static final class OurGenericsResolver implements ResolveCache.PolyVariantResolver<PsiJavaReference> {
+  public static final class OurGenericsResolver implements ResolveCache.PolyVariantContextResolver<PsiJavaReference> {
     public static final OurGenericsResolver INSTANCE = new OurGenericsResolver();
 
-    @Override
     @NotNull
-    public JavaResolveResult[] resolve(@NotNull PsiJavaReference ref, boolean incompleteCode) {
+    @Override
+    public ResolveResult[] resolve(@NotNull PsiJavaReference ref, @NotNull PsiFile containingFile, boolean incompleteCode) {
       PsiReferenceExpressionImpl expression = (PsiReferenceExpressionImpl)ref;
       CompositeElement treeParent = expression.getTreeParent();
       IElementType parentType = treeParent == null ? null : treeParent.getElementType();
-      PsiFile file = expression.getContainingFile();
 
-      List<PsiElement> qualifiers = resolveAllQualifiers(expression, file);
+      List<PsiElement> qualifiers = resolveAllQualifiers(expression, containingFile);
       try {
-        JavaResolveResult[] result = expression.resolve(parentType, file);
+        JavaResolveResult[] result = expression.resolve(parentType, containingFile);
 
         if (result.length == 0 && incompleteCode && parentType != JavaElementType.REFERENCE_EXPRESSION) {
-          result = expression.resolve(JavaElementType.REFERENCE_EXPRESSION, file);
+          result = expression.resolve(JavaElementType.REFERENCE_EXPRESSION, containingFile);
         }
 
         JavaResolveUtil.substituteResults(expression, result);
@@ -213,6 +212,7 @@
       }
     }
 
+    @NotNull
     private static List<PsiElement> resolveAllQualifiers(@NotNull PsiReferenceExpressionImpl expression, @NotNull final PsiFile containingFile) {
       // to avoid SOE, resolve all qualifiers starting from the innermost
       PsiElement qualifier = expression.getQualifier();
@@ -246,9 +246,9 @@
   }
 
   @NotNull
-  private JavaResolveResult[] resolve(IElementType parentType, PsiFile containingFile) {
+  private JavaResolveResult[] resolve(IElementType parentType, @NotNull PsiFile containingFile) {
     if (parentType == JavaElementType.REFERENCE_EXPRESSION) {
-      JavaResolveResult[] result = resolveToVariable();
+      JavaResolveResult[] result = resolveToVariable(containingFile);
       if (result.length > 0) {
         return result;
       }
@@ -280,7 +280,7 @@
       return resolve(JavaElementType.REFERENCE_EXPRESSION, containingFile);
     }
 
-    return resolveToVariable();
+    return resolveToVariable(containingFile);
   }
 
   @NotNull
@@ -297,7 +297,7 @@
   }
 
   @NotNull
-  private JavaResolveResult[] resolveToPackage(PsiFile containingFile) {
+  private JavaResolveResult[] resolveToPackage(@NotNull PsiFile containingFile) {
     final String packageName = getCachedNormalizedText();
     Project project = containingFile.getProject();
     JavaPsiFacade psiFacade = JavaPsiFacade.getInstance(project);
@@ -316,7 +316,7 @@
   }
 
   @NotNull
-  private JavaResolveResult[] resolveToClass(@NotNull PsiElement classNameElement, PsiFile containingFile) {
+  private JavaResolveResult[] resolveToClass(@NotNull PsiElement classNameElement, @NotNull PsiFile containingFile) {
     final String className = classNameElement.getText();
 
     final ClassResolverProcessor processor = new ClassResolverProcessor(className, this, containingFile);
@@ -325,8 +325,8 @@
   }
 
   @NotNull
-  private JavaResolveResult[] resolveToVariable() {
-    final VariableResolverProcessor processor = new VariableResolverProcessor(this, getContainingFile());
+  private JavaResolveResult[] resolveToVariable(@NotNull PsiFile containingFile) {
+    final VariableResolverProcessor processor = new VariableResolverProcessor(this, containingFile);
     PsiScopesUtil.resolveAndWalk(processor, this, null);
     return processor.getResult();
   }
@@ -730,7 +730,7 @@
   }
 
   @Override
-  public void fullyQualify(PsiClass targetClass) {
+  public void fullyQualify(@NotNull PsiClass targetClass) {
     JavaSourceUtil.fullyQualifyReference(this, targetClass);
   }
 
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 5f1e2f6..93a4440 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
@@ -624,11 +624,11 @@
             }
   
             if (!applicable12ignoreFunctionalType && applicable21ignoreFunctionalType) {
-              return specifics == Specifics.SECOND ? Specifics.SECOND : Specifics.NEITHER;
+              return specifics == Specifics.FIRST ? Specifics.FIRST : Specifics.NEITHER;
             }
   
             if (!applicable21ignoreFunctionalType && applicable12ignoreFunctionalType) {
-              return specifics == Specifics.FIRST ? Specifics.FIRST : Specifics.NEITHER;
+              return specifics == Specifics.SECOND ? Specifics.SECOND : Specifics.NEITHER;
             }
   
             return specifics;
diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/processor/MethodCandidatesProcessor.java b/java/java-psi-impl/src/com/intellij/psi/scope/processor/MethodCandidatesProcessor.java
index 7c83f10..7106063 100644
--- a/java/java-psi-impl/src/com/intellij/psi/scope/processor/MethodCandidatesProcessor.java
+++ b/java/java-psi-impl/src/com/intellij/psi/scope/processor/MethodCandidatesProcessor.java
@@ -94,7 +94,7 @@
     };
   }
 
-  protected PsiType[] getExpressionTypes(PsiExpressionList argumentList) {
+  protected static PsiType[] getExpressionTypes(PsiExpressionList argumentList) {
     return argumentList != null ? argumentList.getExpressionTypes() : null;
   }
 
diff --git a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/JavaClassTreeElementBase.java b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/JavaClassTreeElementBase.java
index 50cc8c4..a1d2468 100644
--- a/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/JavaClassTreeElementBase.java
+++ b/java/java-structure-view/src/com/intellij/ide/structureView/impl/java/JavaClassTreeElementBase.java
@@ -72,8 +72,7 @@
             myLocation = "";
           } else {
             myLocation = cls.getName();
-            char rightArrow = '\u2192';
-            myLocation = UIUtil.getLabelFont().canDisplay(rightArrow) ? rightArrow + myLocation :  "->" + myLocation;
+            myLocation = UIUtil.rightArrow() + myLocation;
           }
         } else {
           myLocation = "";
diff --git a/java/java-tests/testData/codeInsight/completeStatement/CaseColon.java b/java/java-tests/testData/codeInsight/completeStatement/CaseColon.java
new file mode 100644
index 0000000..b9ffc77
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completeStatement/CaseColon.java
@@ -0,0 +1,8 @@
+
+class Foo {
+    void foo(String a) {
+        switch (a) {
+            case "asdf<caret>"
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completeStatement/CaseColon_after.java b/java/java-tests/testData/codeInsight/completeStatement/CaseColon_after.java
new file mode 100644
index 0000000..7b177b7
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completeStatement/CaseColon_after.java
@@ -0,0 +1,9 @@
+
+class Foo {
+    void foo(String a) {
+        switch (a) {
+            case "asdf":
+                <caret>
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/MakeMultipleArgumentsFinalWhenInInner.java b/java/java-tests/testData/codeInsight/completion/normal/MakeMultipleArgumentsFinalWhenInInner.java
new file mode 100644
index 0000000..13d3bd46
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/normal/MakeMultipleArgumentsFinalWhenInInner.java
@@ -0,0 +1,13 @@
+class Example {
+  void foo(int a, int b) {
+    new Runnable() {
+      @Override
+      public void run() {
+        bar(<caret>);
+      }
+    };
+  }
+
+  void bar(int a, int b) {
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/MakeMultipleArgumentsFinalWhenInInner_after.java b/java/java-tests/testData/codeInsight/completion/normal/MakeMultipleArgumentsFinalWhenInInner_after.java
new file mode 100644
index 0000000..14f223d
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/normal/MakeMultipleArgumentsFinalWhenInInner_after.java
@@ -0,0 +1,13 @@
+class Example {
+  void foo(final int a, final int b) {
+    new Runnable() {
+      @Override
+      public void run() {
+        bar(a, b);<caret>
+      }
+    };
+  }
+
+  void bar(int a, int b) {
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/normal/NoFinalInAnonymousConstructor.java b/java/java-tests/testData/codeInsight/completion/normal/NoFinalInAnonymousConstructor.java
new file mode 100644
index 0000000..6807eec
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/normal/NoFinalInAnonymousConstructor.java
@@ -0,0 +1,9 @@
+import java.lang.Runnable;
+import java.util.List;
+import java.util.ArrayList;
+
+public class A {
+  void foo(List<String> parameter) {
+    new Runnable(par<caret>) {}
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/completion/normal/NoFinalInAnonymousConstructor_after.java b/java/java-tests/testData/codeInsight/completion/normal/NoFinalInAnonymousConstructor_after.java
new file mode 100644
index 0000000..b49303e
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/normal/NoFinalInAnonymousConstructor_after.java
@@ -0,0 +1,9 @@
+import java.lang.Runnable;
+import java.util.List;
+import java.util.ArrayList;
+
+public class A {
+  void foo(List<String> parameter) {
+    new Runnable(parameter<caret>) {}
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/completion/normalSorting/PreferClassesOfExpectedClassType.java b/java/java-tests/testData/codeInsight/completion/normalSorting/PreferClassesOfExpectedClassType.java
new file mode 100644
index 0000000..197dbb8
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/normalSorting/PreferClassesOfExpectedClassType.java
@@ -0,0 +1,12 @@
+import java.lang.Exception;
+
+public class Foo {
+  {
+    foo(X<caret>)
+  }
+
+  void foo(Class<? extends Throwable> c) {}
+}
+
+interface XIntf {}
+class XClass {}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/GetClassWhenClassExpected-out.java b/java/java-tests/testData/codeInsight/completion/smartType/GetClassWhenClassExpected-out.java
new file mode 100644
index 0000000..39fbcc4
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/smartType/GetClassWhenClassExpected-out.java
@@ -0,0 +1,7 @@
+class A {
+}
+class B extends A {
+  void m() {
+    Class<? extends A> c = getClass();<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/GetClassWhenClassExpected.java b/java/java-tests/testData/codeInsight/completion/smartType/GetClassWhenClassExpected.java
new file mode 100644
index 0000000..9180467
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/smartType/GetClassWhenClassExpected.java
@@ -0,0 +1,7 @@
+class A {
+}
+class B extends A {
+  void m() {
+    Class<? extends A> c = g<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA124271.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA124271.java
new file mode 100644
index 0000000..9886942
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA124271.java
@@ -0,0 +1,9 @@
+
+interface Container<T extends Content> extends Iterable<T> {}
+interface Content {}
+
+class Main {
+  public static void doSomething(Container container) {
+    for (<error descr="Incompatible types. Found: 'java.lang.Object', required: 'Content'">Content content : container</error>) {}
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/PairsWithSameErasure.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/PairsWithSameErasure.java
new file mode 100644
index 0000000..f7d2f026
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/PairsWithSameErasure.java
@@ -0,0 +1,9 @@
+import java.util.List;
+
+class MyClass {
+  <error descr="'method1(Comparable<Integer>)' clashes with 'method1(Comparable<Boolean>)'; both methods have same erasure">void method1 (Comparable<Integer> c)</error> {}
+  void method1(Comparable<Boolean> c) {}
+
+  <error descr="'method2(List<Integer>)' clashes with 'method2(List<Boolean>)'; both methods have same erasure">void method2(List<Integer> l)</error> {} 
+  void method2(List<Boolean> l) {}
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/UnrelatedReturnInTypeArgs.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/UnrelatedReturnInTypeArgs.java
new file mode 100644
index 0000000..4e0fb23
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/UnrelatedReturnInTypeArgs.java
@@ -0,0 +1,13 @@
+import java.util.*;
+
+class Test {
+  interface A {
+    Iterable<Integer> m(List ls);
+  }
+
+  interface B {
+    Iterable<String> m(List l);
+  }
+
+  <error descr="'m(List)' in 'Test.B' clashes with 'm(List)' in 'Test.A'; methods have unrelated return types">interface AB extends A, B</error> {}
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/advHighlighting/Underscore.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/advHighlighting/Underscore.java
new file mode 100644
index 0000000..50c8d6c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/advHighlighting/Underscore.java
@@ -0,0 +1,3 @@
+class Test {
+  void <warning descr="Use of '_' as an identifier might not be supported in releases after Java 8">_</warning>(){}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/FunctionalInterfaceAnnotation3.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/FunctionalInterfaceAnnotation3.java
new file mode 100644
index 0000000..6e392f2
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/FunctionalInterfaceAnnotation3.java
@@ -0,0 +1,8 @@
+interface I<T, K extends Integer> {
+    void m(T t);
+    void m(K k);
+  }
+
+@FunctionalInterface
+interface IEx extends I<Integer, Integer> { }
+
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/GenericNotGenericInterfaceMethod.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/GenericNotGenericInterfaceMethod.java
new file mode 100644
index 0000000..71b286a5
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/GenericNotGenericInterfaceMethod.java
@@ -0,0 +1,43 @@
+class Test {
+
+  interface A {
+    <X> void m();
+  }
+
+  interface B {
+    void m();
+  }
+
+  interface C extends A, B { }
+
+  {
+    C c = ()-> {};
+  }
+}
+
+class Test1 {
+
+  interface F {
+    <X> void  m();
+  }
+
+  {
+    F f = this::g;
+  }
+
+  void g() {}
+}
+
+class Test2 {
+
+  interface F {
+    <X> void  m();
+    void a();
+  }
+
+  {
+    F f = <error descr="Multiple non-overriding abstract methods found">() -> g()</error>;
+  }
+
+  void g() {}
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/InferredFromCast.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/InferredFromCast.java
new file mode 100644
index 0000000..e31cf5a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/InferredFromCast.java
@@ -0,0 +1,14 @@
+class Test {
+
+  interface A {
+    int m();
+  }
+
+  interface B {
+    int m(int i);
+  }
+
+  public static void main(String[] args) {
+    A a = ()-> ((B)i -> i).m(3);
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Intersection.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Intersection.java
new file mode 100644
index 0000000..767b547
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Intersection.java
@@ -0,0 +1,35 @@
+import java.io.Serializable;
+
+class Test {
+
+  interface I {
+    void foo();
+  }
+
+  interface A {
+    void bar(int i);
+  }
+
+  {
+    Object o1 = (Serializable & I) () -> {};
+    Object o2 = (I & Serializable) () -> {};
+    Object o3 = (I & Runnable) <error descr="Multiple non-overriding abstract methods found in Runnable & I">() -> {}</error>;
+    Object o4 = (A & Runnable) <error descr="Multiple non-overriding abstract methods found in Runnable & A">() -> {}</error>;
+    Object o5 = (Runnable & A) <error descr="Multiple non-overriding abstract methods found in Runnable & A">() -> {}</error>;
+  }
+}
+
+class Test1 {
+
+  interface A {
+    <X> void foo();
+  }
+
+  interface B {
+    void foo();
+  }
+
+  {
+    Object c0 = (A & B) ()->{};
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/NoBoxingInLambdaFormalParams.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/NoBoxingInLambdaFormalParams.java
new file mode 100644
index 0000000..30e096ff
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/NoBoxingInLambdaFormalParams.java
@@ -0,0 +1,8 @@
+class LambdaConv10 {
+
+  interface I<T, R> { public R call( T t); }
+
+  {
+    I<Integer,Integer> in = (<error descr="Incompatible parameter types in lambda expression">int i</error>) -> 2 * i;
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReferencedFromSelf.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReferencedFromSelf.java
new file mode 100644
index 0000000..5b029df
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/ReferencedFromSelf.java
@@ -0,0 +1,13 @@
+class Test {
+
+  Runnable r;
+  { r = r::run; }
+  Runnable r1;
+  { r1 = () -> r1.run(); }
+
+
+  {
+    Runnable r = () -> <error descr="Variable 'r' might not have been initialized">r</error>.run();
+    Runnable r1 = <error descr="Variable 'r1' might not have been initialized">r1</error>::run;
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Underscores.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Underscores.java
index 2d89ec3..154a75a 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Underscores.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/highlighting/Underscores.java
@@ -1,11 +1,6 @@
 class C {
   void test() {
     {
-      I <warning descr="Use of '_' as an identifier might not be supported in releases after Java 8">_</warning> = new I() { public void f(int i) { } };
-      accept(_);
-    }
-
-    {
       accept(<error descr="Use of '_' as a lambda parameter name is not allowed">_</error> -> System.out.println(_));
       accept((int <error descr="Use of '_' as a lambda parameter name is not allowed">_</error>) -> System.out.println(_));
     }
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/incomplete/MissedFunctionalInterfaceMethodReturnType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/incomplete/MissedFunctionalInterfaceMethodReturnType.java
new file mode 100644
index 0000000..5742687
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/incomplete/MissedFunctionalInterfaceMethodReturnType.java
@@ -0,0 +1,35 @@
+class Test {
+
+  interface A {
+    A f();
+  }
+  interface B {}
+
+  static abstract class C implements A, B {}
+  static abstract class D implements A, B {}
+
+  interface I<T> {
+    <error descr="Invalid method declaration; return type required">m</error>(T arg);
+  }
+
+  void bar(C c) {
+    foo(c, x -> x.f());
+    foo(c, x -> x);
+  }
+
+  <T> void foo(T t1, I<T> t3) {}
+
+}
+
+class Test2 {
+
+  interface F {
+    <X>  <error descr="Invalid method declaration; return type required">m</error>();
+  }
+
+  void g() {}
+
+  {
+    F f = this::g;
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/QualifiersInStaticContext.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/QualifiersInStaticContext.java
new file mode 100644
index 0000000..4832371
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/QualifiersInStaticContext.java
@@ -0,0 +1,11 @@
+public class Test {
+    interface I {
+        void foo();
+    }
+
+    private Object o;
+  
+    public static void main(String[] args){
+        I i = <error descr="Non-static field 'o' cannot be referenced from a static context">o</error>::wait;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/BoxingAndOverloadResolution.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/BoxingAndOverloadResolution.java
new file mode 100644
index 0000000..36db301
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/BoxingAndOverloadResolution.java
@@ -0,0 +1,33 @@
+class Test {
+  private static void m(int i) {System.out.println(i);}
+  private static void <warning descr="Private method 'm(java.lang.Integer)' is never used">m</warning>(Integer i) {System.out.println(i);}
+
+  interface I {
+    void foo(int p);
+  }
+
+  static {
+    I s = Test::m;
+    System.out.println(s);
+  }
+}
+
+class Test2 {
+
+  static void m(Integer i) { }
+
+  interface I1 {
+    void m(int x);
+  }
+
+  interface I2 {
+    void m(Integer x);
+  }
+
+  static void call(I1 i1) { System.out.println(i1);  }
+  static void call(I2 i2) { System.out.println(i2); }
+
+  static {
+    call<error descr="Ambiguous method call: both 'Test2.call(I1)' and 'Test2.call(I2)' match">(Test2::m)</error>;
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/DifferentParamsLength.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/DifferentParamsLength.java
new file mode 100644
index 0000000..951858b
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/DifferentParamsLength.java
@@ -0,0 +1,29 @@
+class Test {
+
+  interface I0 {
+    void m();
+  }
+
+  interface I1 {
+    void m(Object a);
+  }
+
+  interface I2 {
+    void m(Object a1, Object a2);
+  }
+
+  interface IVarargs {
+    void m(Object... as);
+  }
+
+  void call(I0 p) { }
+  void call(I1 p) { }
+  void call(I2 p) { }
+  void call(IVarargs p) { }
+
+  void test() {
+    call(() -> { });
+    call<error descr="Ambiguous method call: both 'Test.call(I1)' and 'Test.call(IVarargs)' match">(p1 -> { })</error>;
+    call((p1, p2) -> {});
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/IncompleteMethodInInterface.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/IncompleteMethodInInterface.java
new file mode 100644
index 0000000..8d71a82
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/IncompleteMethodInInterface.java
@@ -0,0 +1,12 @@
+class Test {
+  interface I { Object in<EOLError descr="';' expected"></EOLError>
+    <error descr="Invalid method declaration; return type required">voke</error>(); }
+  interface IStr { String foo(); }
+
+  public static void call(IStr str) {}
+  public static void call(I i) {  }
+
+  public static void main(String[] args)   {
+      call<error descr="Ambiguous method call: both 'Test.call(IStr)' and 'Test.call(I)' match">(()-> null)</error>;
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/MostSpecificByReturnType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/MostSpecificByReturnType.java
new file mode 100644
index 0000000..5588c3e
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/MostSpecificByReturnType.java
@@ -0,0 +1,16 @@
+class Test {
+  interface I { Object invoke(); }
+  interface IStr { String foo(); }
+
+  private static void call(IStr str) {
+    System.out.println(str);
+  }
+
+  private static void <warning descr="Private method 'call(Test.I)' is never used">call</warning>(I i) {
+    System.out.println(i);
+  }
+
+  public static void main(String[] args)   {
+      call(()-> null);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/NoReturnTypeResolutionForThrownException.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/NoReturnTypeResolutionForThrownException.java
new file mode 100644
index 0000000..8142913
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/mostSpecific/NoReturnTypeResolutionForThrownException.java
@@ -0,0 +1,14 @@
+class Test {
+
+  interface I1 {String m();}
+  interface I2 {void m();}
+
+  void call(I1 p) { }
+  void call(I2 p) { }
+ 
+  void test() {
+    call<error descr="Ambiguous method call: both 'Test.call(I1)' and 'Test.call(I2)' match">(() -> { throw new RuntimeException(); })</error>;
+    call(() -> { if (true) return ""; throw new RuntimeException(); });
+    call(() -> { if (true) return; throw new RuntimeException(); });
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/LiftedIntersectionType.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/LiftedIntersectionType.java
new file mode 100644
index 0000000..de9d517
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/LiftedIntersectionType.java
@@ -0,0 +1,22 @@
+class Test {
+
+  interface A {
+    A f();
+  }
+  interface B {}
+
+  static abstract class C implements A, B {}
+  static abstract class D implements A, B {}
+
+  interface I<T> {
+    T m(T arg);
+  }
+
+  void bar(C c) {
+    foo(c, <error descr="Incompatible return type A in lambda expression">x -> x.f()</error>);
+    foo(c, x -> x);
+  }
+
+  <T> void foo(T t1, I<T> t3) {}
+
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/OnlyLambdaAtTypeParameterPlace.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/OnlyLambdaAtTypeParameterPlace.java
new file mode 100644
index 0000000..aee4c84
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/OnlyLambdaAtTypeParameterPlace.java
@@ -0,0 +1,13 @@
+class Test {
+  interface I {
+    void m();
+  }
+
+  <T> void call(T t) {}
+  <T extends Runnable> void call1(T t) {}
+
+  {
+    call<error descr="'call(T)' in 'Test' cannot be applied to '(<lambda expression>)'">(() -> {})</error>; 
+    call1(() -> {}); 
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/AfterDistinctOps.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/AfterDistinctOps.java
index ee24b8c..9976acb 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/AfterDistinctOps.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/AfterDistinctOps.java
@@ -5,7 +5,7 @@
 class BBB {
 
     static <T> void f() {
-        TerminalOp<T, LinkedHashSet<T>> <warning descr="Variable 'reduceOp' is never used">reduceOp</warning> = BBB.<T, LinkedHashSet<T>>makeRef(LinkedHashSet::new, LinkedHashSet::add, LinkedHashSet::addAll);
+        TerminalOp<T, LinkedHashSet<T>> <warning descr="Variable 'reduceOp' is never used">reduceOp</warning> = BBB.<T, LinkedHashSet<T>>makeRef(LinkedHashSet::new, LinkedHashSet::<warning descr="Unchecked call to 'add(E)' as a member of raw type 'HashSet'">add</warning>, LinkedHashSet::<warning descr="Unchecked call to 'addAll(Collection<? extends E>)' as a member of raw type 'AbstractCollection'">addAll</warning>);
     }
 
     public static <T, U> TerminalOp<T, U> makeRef(U <warning descr="Parameter 'seed' is never used">seed</warning>, BiFunction<U, ? super T, U> <warning descr="Parameter 'reducer' is never used">reducer</warning>, BinaryOperator<U> <warning descr="Parameter 'combiner' is never used">combiner</warning>) {
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/IDEA124148.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/IDEA124148.java
new file mode 100644
index 0000000..073d649
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/IDEA124148.java
@@ -0,0 +1,25 @@
+import java.util.*;
+
+
+import java.util.Optional;
+import java.util.function.BiFunction;
+import java.util.function.Supplier;
+
+class A<T>
+{
+  public <S> S foldRight(Supplier<S> value, BiFunction<T, Supplier<S>, Supplier<S>> f)
+  {
+    return null;
+  }
+
+  public static <S> Optional<S> h(A<S> flow)
+  {
+    return flow.foldRight(() -> Optional.empty(), (element, lazyResult) -> () -> Optional.of(element));
+
+  }
+
+  public static <S> Optional<S> hR(A<S> flow)
+  {
+    return flow.foldRight(Optional::empty, (element, lazyResult) -> () -> Optional.of(element));
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/RefOnStaticInterfaceMethod.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/RefOnStaticInterfaceMethod.java
new file mode 100644
index 0000000..6687f96
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/RefOnStaticInterfaceMethod.java
@@ -0,0 +1,13 @@
+interface I {
+  static void a() {}
+}
+
+interface J {
+  void foo();
+}
+
+class Test {
+  {
+    J j = I::a;
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/UncheckedMethodReference.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/UncheckedMethodReference.java
new file mode 100644
index 0000000..4b451f2
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newMethodRef/UncheckedMethodReference.java
@@ -0,0 +1,15 @@
+import java.util.*;
+
+class Test {
+
+  interface I<T> {
+    void m(List<T> l, T el);
+  }
+
+  {
+    I<String> i1 =  List::add;
+    System.out.println(i1);
+    I i2 = List::<warning descr="Unchecked call to 'add(E)' as a member of raw type 'java.util.List'">add</warning>;
+    System.out.println(i2);
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromMethodRef/afterSubstitutionParams.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromMethodRef/afterSubstitutionParams.java
new file mode 100644
index 0000000..f4c3166
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromMethodRef/afterSubstitutionParams.java
@@ -0,0 +1,15 @@
+// "Create Method 'fooBar'" "true"
+class FooBar {
+  {
+    Comparator<String> c = this::fooBar;
+  }
+
+    private int fooBar(String s, String s1) {
+        return 0;
+    }
+}
+
+
+interface Comparator<T> {
+  int compare(T o1, T o2);
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromMethodRef/beforeSubstitutionParams.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromMethodRef/beforeSubstitutionParams.java
new file mode 100644
index 0000000..96dc6d1
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/createMethodFromMethodRef/beforeSubstitutionParams.java
@@ -0,0 +1,11 @@
+// "Create Method 'fooBar'" "true"
+class FooBar {
+  {
+    Comparator<String> c = this::foo<caret>Bar;
+  }
+}
+
+
+interface Comparator<T> {
+  int compare(T o1, T o2);
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18/afterInsideLambda.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18/afterInsideLambda.java
new file mode 100644
index 0000000..8754e8e
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18/afterInsideLambda.java
@@ -0,0 +1,11 @@
+// "Copy 'a' to temp final variable" "true"
+class Test {
+    public void test() {
+        int a = 1;
+        a = 2;
+        final int finalA = a;
+        Runnable r = () -> {
+            System.out.println(finalA);
+        };
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18/beforeInsideLambda.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18/beforeInsideLambda.java
new file mode 100644
index 0000000..7dabe19
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18/beforeInsideLambda.java
@@ -0,0 +1,10 @@
+// "Copy 'a' to temp final variable" "true"
+class Test {
+    public void test() {
+        int a = 1;
+        a = 2;
+        Runnable r = () -> {
+            System.out.println(<caret>a);
+        };
+    }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeIterable.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeIterable.java
new file mode 100644
index 0000000..dd94d2c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/streamApiMigration/beforeIterable.java
@@ -0,0 +1,15 @@
+// "Replace with forEach" "false"
+import java.util.ArrayList;
+import java.util.List;
+
+class Sample {
+  Iterable<String> foo = new ArrayList<>();
+  String foo(){
+    for (String s : fo<caret>o) {
+      if (s == null) {
+        return s;
+      }
+    }
+    return null;
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithFullMatchPrefix.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithFullMatchPrefix.java
new file mode 100644
index 0000000..9da7f68
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithFullMatchPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    complex key<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithFullMatchPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithFullMatchPrefix_after.java
new file mode 100644
index 0000000..63e36d3
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithFullMatchPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    complex template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefix.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefix.java
new file mode 100644
index 0000000..6cfe6e4
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefixcomplex key<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter.java
new file mode 100644
index 0000000..fdad1b2
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefix:comple<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter_after.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter_after.java
new file mode 100644
index 0000000..e6ad365
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefix:complex template text<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefix_after.java
new file mode 100644
index 0000000..f52e550
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithNotMatchedPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefixcomplex keycomplex template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithPartialPrefix.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithPartialPrefix.java
new file mode 100644
index 0000000..abd92e0
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithPartialPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    complex k<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithPartialPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithPartialPrefix_after.java
new file mode 100644
index 0000000..63e36d3
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithPartialPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    complex template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithoutPrefix.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithoutPrefix.java
new file mode 100644
index 0000000..10fc39c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithoutPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    <caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithoutPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithoutPrefix_after.java
new file mode 100644
index 0000000..63e36d3
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/ComplexKeyWithoutPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    complex template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/FullMatchPrefix.java b/java/java-tests/testData/codeInsight/template/list/FullMatchPrefix.java
new file mode 100644
index 0000000..cd1ce95
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/FullMatchPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    simple<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/FullMatchPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/FullMatchPrefix_after.java
new file mode 100644
index 0000000..d5540c1
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/FullMatchPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    simple template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/MatchingByTemplateDescription.java b/java/java-tests/testData/codeInsight/template/list/MatchingByTemplateDescription.java
new file mode 100644
index 0000000..2a382dc
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/MatchingByTemplateDescription.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    descri<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/MatchingByTemplateDescription_after.java b/java/java-tests/testData/codeInsight/template/list/MatchingByTemplateDescription_after.java
new file mode 100644
index 0000000..d5540c1
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/MatchingByTemplateDescription_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    simple template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefix.java b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefix.java
new file mode 100644
index 0000000..fa0b336
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefixsimpl<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefixAfterNonJavaCharacter.java b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefixAfterNonJavaCharacter.java
new file mode 100644
index 0000000..192539c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefixAfterNonJavaCharacter.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefix:simp<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefixAfterNonJavaCharacter_after.java b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefixAfterNonJavaCharacter_after.java
new file mode 100644
index 0000000..7e7699d
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefixAfterNonJavaCharacter_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefix:simple template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefix_after.java
new file mode 100644
index 0000000..252a6176
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/NotMatchedPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    prefixsimplsimple template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/PartialPrefix.java b/java/java-tests/testData/codeInsight/template/list/PartialPrefix.java
new file mode 100644
index 0000000..76f88e6
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/PartialPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    simp<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/PartialPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/PartialPrefix_after.java
new file mode 100644
index 0000000..d5540c1
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/PartialPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    simple template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/WithoutPrefix.java b/java/java-tests/testData/codeInsight/template/list/WithoutPrefix.java
new file mode 100644
index 0000000..10fc39c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/WithoutPrefix.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    <caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/list/WithoutPrefix_after.java b/java/java-tests/testData/codeInsight/template/list/WithoutPrefix_after.java
new file mode 100644
index 0000000..d5540c1
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/list/WithoutPrefix_after.java
@@ -0,0 +1,5 @@
+class A {
+  public static void main() {
+    simple template text
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/completion/restartCompletionForExactMatch.java b/java/java-tests/testData/codeInsight/template/postfix/completion/restartCompletionForExactMatch.java
new file mode 100644
index 0000000..1e7af40
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/completion/restartCompletionForExactMatch.java
@@ -0,0 +1,5 @@
+public class Test {
+  public static void main(String[] args) {
+    Boolean.FALSE.<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simple.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simple.java
new file mode 100644
index 0000000..152b358
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simple.java
@@ -0,0 +1,12 @@
+import java.lang.AutoCloseable
+
+public class Foo {
+    void m() {
+        getStream().twr<caret>
+    }
+
+    AutoCloseable getStream()
+    {
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleNotAutoCloseable.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleNotAutoCloseable.java
new file mode 100644
index 0000000..3b4e516
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleNotAutoCloseable.java
@@ -0,0 +1,12 @@
+import java.lang.AutoCloseable
+
+public class Foo {
+    void m() {
+        getStream().twr<caret>
+    }
+
+    Object getStream()
+    {
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleNotAutoCloseable_after.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleNotAutoCloseable_after.java
new file mode 100644
index 0000000..868f54a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleNotAutoCloseable_after.java
@@ -0,0 +1,12 @@
+import java.lang.AutoCloseable
+
+public class Foo {
+    void m() {
+        getStream().twr <caret>
+    }
+
+    Object getStream()
+    {
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithConflict.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithConflict.java
new file mode 100644
index 0000000..c23feda
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithConflict.java
@@ -0,0 +1,17 @@
+import java.lang.AutoCloseable
+
+public class Foo {
+    void m() {
+        getStream().twr<caret>
+    }
+
+    AutoCloseable getStream()
+    {
+        return null;
+    }
+
+    private class Exception extends java.lang.Exception
+    {
+
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithConflict_after.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithConflict_after.java
new file mode 100644
index 0000000..fff4f9d
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithConflict_after.java
@@ -0,0 +1,20 @@
+import java.lang.AutoCloseable
+
+public class Foo {
+    void m() {
+        try (AutoCloseable stream = getStream()) {
+            <caret>
+        } catch (java.lang.Exception e) {
+        }
+    }
+
+    AutoCloseable getStream()
+    {
+        return null;
+    }
+
+    private class Exception extends java.lang.Exception
+    {
+
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithMyException.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithMyException.java
new file mode 100644
index 0000000..dca1e61
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithMyException.java
@@ -0,0 +1,23 @@
+import java.lang.AutoCloseable
+import java.lang.Exception;
+
+public class Foo {
+    void m() {
+        getStream().twr<caret>
+    }
+
+    MyStream getStream()
+    {
+        return null;
+    }
+
+    private class MyStream implements AutoCloseable
+    {
+        public void close() throws MyException {}
+    }
+
+    private class MyException extends Exception
+    {
+
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithMyException_after.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithMyException_after.java
new file mode 100644
index 0000000..d820e55
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simpleWithMyException_after.java
@@ -0,0 +1,26 @@
+import java.lang.AutoCloseable
+import java.lang.Exception;
+
+public class Foo {
+    void m() {
+        try (MyStream stream = getStream()) {
+            <caret>
+        } catch (MyException e) {
+        }
+    }
+
+    MyStream getStream()
+    {
+        return null;
+    }
+
+    private class MyStream implements AutoCloseable
+    {
+        public void close() throws MyException {}
+    }
+
+    private class MyException extends Exception
+    {
+
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simple_after.java b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simple_after.java
new file mode 100644
index 0000000..f8d33d9
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/template/postfix/templates/twr/simple_after.java
@@ -0,0 +1,15 @@
+import java.lang.AutoCloseable
+
+public class Foo {
+    void m() {
+        try (AutoCloseable stream = getStream()) {
+            <caret>
+        } catch (Exception e) {
+        }
+    }
+
+    AutoCloseable getStream()
+    {
+        return null;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/ByteBufferGetter.java b/java/java-tests/testData/inspection/dataFlow/fixture/ByteBufferGetter.java
new file mode 100644
index 0000000..8cc15fe
--- /dev/null
+++ b/java/java-tests/testData/inspection/dataFlow/fixture/ByteBufferGetter.java
@@ -0,0 +1,14 @@
+import java.nio.MappedByteBuffer;
+
+class Test
+{
+  public static int triggerBug(MappedByteBuffer buffer)
+  {
+    int a = buffer.getInt();
+    int b = buffer.getInt();
+    if(a == 0 && b == 1)
+      return 0;
+    else
+      return 1;
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/InherentNumberRanges.java b/java/java-tests/testData/inspection/dataFlow/fixture/InherentNumberRanges.java
new file mode 100644
index 0000000..df784c7
--- /dev/null
+++ b/java/java-tests/testData/inspection/dataFlow/fixture/InherentNumberRanges.java
@@ -0,0 +1,25 @@
+class Foo {
+
+  private void foo(byte myByte) {
+    if (<warning descr="Condition 'myByte == 0xFF' is always 'false'">myByte == 0xFF</warning>) {
+      System.out.println("wrong");
+    }
+    if (<warning descr="Condition 'myByte != 0xFFF' is always 'true'">myByte != 0xFFF</warning>) {
+      System.out.println("wrong");
+    }
+    if (myByte == (byte) 0xFF) {
+      System.out.println("right");
+    }
+  }
+
+  void foo2(int i) {
+    boolean a = <warning descr="Condition 'i < 0x80000000L' is always 'true'">i < 0x80000000L</warning>;
+    boolean f = <warning descr="Condition 'i > 0x7fffffff' is always 'false'">i > 0x7fffffff</warning>;
+  }
+
+  void f(int k) {
+    if (<warning descr="Condition 'k <= Integer.MAX_VALUE' is always 'true'">k <= Integer.MAX_VALUE</warning>);
+    if (<warning descr="Condition 'k > Integer.MAX_VALUE' is always 'false'">k > Integer.MAX_VALUE</warning>);
+    if (<warning descr="Condition 'k >= Integer.MIN_VALUE' is always 'true'">k >= Integer.MIN_VALUE</warning>);
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/NullableForeachVariable.java b/java/java-tests/testData/inspection/dataFlow/fixture/NullableForeachVariable.java
index 027a659..bc81159 100644
--- a/java/java-tests/testData/inspection/dataFlow/fixture/NullableForeachVariable.java
+++ b/java/java-tests/testData/inspection/dataFlow/fixture/NullableForeachVariable.java
@@ -14,6 +14,13 @@
       System.out.println(<warning descr="Method invocation 'i.intValue()' may produce 'java.lang.NullPointerException'">i.intValue()</warning>);
     }
   }
+  void foo3() {
+    List<@Nullable String> list = new ArrayList<>();
+    list.add(null);
+    for (String s : list) {
+      System.out.println(<warning descr="Method invocation 's.length()' may produce 'java.lang.NullPointerException'">s.length()</warning>);
+    }
+  }
 
 }
 
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/CompleteStatementTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/CompleteStatementTest.java
index d8a89cb..2eecdaa 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/CompleteStatementTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/CompleteStatementTest.java
@@ -201,6 +201,7 @@
   public void testSwitchKeyword() throws Exception { doTest(); }
 
   public void testSwitchKeywordWithCondition() throws Exception { doTest(); }
+  public void testCaseColon() { doTest(); }
 
   public void testNewInParentheses() throws Exception { doTest(); }
   
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy
index d789ce2..5910f17 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/JavaAutoPopupTest.groovy
@@ -1624,4 +1624,15 @@
     def tabKeyPresentation = KeyEvent.getKeyText(TemplateSettings.TAB_CHAR as int)
     assert p.typeText == "  [$tabKeyPresentation] "
   }
+
+  public void "test autopopup after package completion"() {
+    myFixture.addClass("package foo.bar.goo; class Foo {}")
+    myFixture.configureByText "a.java", "class Foo { { foo.b<caret> } }"
+    myFixture.completeBasic()
+    assert myFixture.editor.document.text.contains('foo.bar. ')
+    joinAutopopup()
+    joinCompletion()
+    assert lookup
+    assert myFixture.lookupElementStrings == ['goo']
+  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy
index 64dba68..7f94ec4 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionOrderingTest.groovy
@@ -620,6 +620,11 @@
     checkPreferredItems 0, 'MyEnum.BAR', 'MyEnum', 'MyEnum.FOO'
   }
 
+  public void testPreferClassesOfExpectedClassType() {
+    myFixture.addClass "class XException extends Exception {}"
+    checkPreferredItems 0, 'XException', 'XClass', 'XIntf'
+  }
+
   public void testGlobalStaticMemberStats() {
     configureNoCompletion(getTestName(false) + ".java")
     myFixture.complete(CompletionType.BASIC, 2)
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy
index d30e352..cbb86bb 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/NormalCompletionTest.groovy
@@ -1283,9 +1283,18 @@
     lookup.currentItem = lookup.items[1]
     type '\n'
     checkResult()
-
   }
 
+  public void testMakeMultipleArgumentsFinalWhenInInner() {
+    configure()
+    def item = lookup.items.find { 'a, b' == it.lookupString }
+    assert item
+    lookup.currentItem = item
+    type '\n'
+    checkResult()
+  }
+
+  public void testNoFinalInAnonymousConstructor() { doTest() }
   public void testListArrayListCast() { doTest('\n') }
   public void testInterfaceImplementationNoCast() { doTest() }
   public void testStaticallyImportedMethodsBeforeExpression() { doTest() }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java
index 6779aac..478cc94 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartTypeCompletionTest.java
@@ -1022,6 +1022,7 @@
   public void testDuplicateMembersFromSuperClass() throws Throwable { doTest(); }
   public void testInnerAfterNew() throws Throwable { doTest(); }
   public void testEverythingInStringConcatenation() throws Throwable { doTest(); }
+  public void testGetClassWhenClassExpected() { doTest(); }
 
   public void testMemberImportStatically() {
     configureByTestName();
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/VariablesCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/VariablesCompletionTest.groovy
index bd974555..3675a99 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/VariablesCompletionTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/VariablesCompletionTest.groovy
@@ -227,4 +227,17 @@
     myFixture.assertPreferredCompletionItems 0, 'l', 'nanoTime', 'time'
   }
 
+  public void "test use superclass for inner class variable name suggestion"() {
+    myFixture.configureByText 'a.java', '''
+class FooFoo {
+  { Rectangle2D.Double <caret>x }
+}
+class Rectangle2D {
+  static class Double extends Rectangle2D {}
+}
+'''
+    myFixture.completeBasic()
+    myFixture.assertPreferredCompletionItems 0, 'aDouble', 'rectangle2D'
+  }
+
 }
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 f4e40bd..bf74b4e 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
@@ -74,6 +74,7 @@
   public void testEnum() { doTest(LanguageLevel.JDK_1_5, JavaSdkVersion.JDK_1_5, false); }
   public void testEnum56239() { doTest(LanguageLevel.JDK_1_6, JavaSdkVersion.JDK_1_6, false); }
   public void testSameErasure() { doTest5(false); }
+  public void testPairsWithSameErasure() { doTest5(false); }
   public void testMethods() { doTest5(false); }
   public void testFields() { doTest5(false); }
   public void testStaticImports() { doTest5(true); }
@@ -341,10 +342,12 @@
   public void testIDEA120563() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
   public void testIDEA121400() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
   public void testIDEA123316() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
+  public void testUnrelatedReturnInTypeArgs() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
   public void testIDEA123352() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
   public void testIDEA123518() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
   public void testIDEA64103() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
   public void testIDEA123338() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
+  public void testIDEA124271() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, 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/codeInsight/daemon/lambda/FunctionalExpressionIncompleteHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/FunctionalExpressionIncompleteHighlightingTest.java
new file mode 100644
index 0000000..3d60915
--- /dev/null
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/FunctionalExpressionIncompleteHighlightingTest.java
@@ -0,0 +1,53 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.daemon.lambda;
+
+import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
+import com.intellij.codeInspection.LocalInspectionTool;
+import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.testFramework.IdeaTestUtil;
+import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
+
+public class FunctionalExpressionIncompleteHighlightingTest extends LightDaemonAnalyzerTestCase {
+  @NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/incomplete";
+
+  @NotNull
+  @Override
+  protected LocalInspectionTool[] configureLocalInspectionTools() {
+    return new LocalInspectionTool[]{
+      new UnusedSymbolLocalInspection(),
+    };
+  }
+
+  public void testMissedFunctionalInterfaceMethodReturnType() throws Exception {
+    doTest();
+  }
+
+  private void doTest() {
+    doTest(false);
+  }
+
+  private void doTest(final boolean checkWarnings) {
+    doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", checkWarnings, false);
+  }
+
+  @Override
+  protected Sdk getProjectJDK() {
+    return IdeaTestUtil.getMockJdk18();
+  }
+}
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java
index aa18173..a3a326c 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LambdaHighlightingTest.java
@@ -78,6 +78,7 @@
   public void testAmbiguitySpecificReturn() { doTest(true); }
   public void testFunctionalInterfaceAnnotation() { doTest(); }
   public void testFunctionalInterfaceAnnotation2() { doTest(); }
+  public void testFunctionalInterfaceAnnotation3() { doTest(); }
   public void testAmbiguityReturnValueResolution() { doTest(); }
   public void testAmbiguityReturnValueResolution1() { doTest(); }
   public void testAmbiguityReturnValueResolution2() { doTest(true); }
@@ -100,6 +101,11 @@
   public void testBreakContinueInside() {doTest();}
   public void testSameLambdaParamNames() {doTest();}
   public void testIDEA123308() {doTest();}
+  public void testIntersection() {doTest();}
+  public void testNoBoxingInLambdaFormalParams() {doTest();}
+  public void testGenericNotGenericInterfaceMethod() {doTest();}
+  public void testInferredFromCast() {doTest();}
+  public void testReferencedFromSelf() {doTest();}
 
   private void doTest() {
     doTest(false);
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LightAdvHighlightingJdk8Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LightAdvHighlightingJdk8Test.java
new file mode 100644
index 0000000..630acb0
--- /dev/null
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/LightAdvHighlightingJdk8Test.java
@@ -0,0 +1,52 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.daemon.lambda;
+
+import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
+import com.intellij.codeInspection.LocalInspectionTool;
+import com.intellij.codeInspection.compiler.JavacQuirksInspection;
+import com.intellij.codeInspection.unusedSymbol.UnusedSymbolLocalInspection;
+import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.testFramework.IdeaTestUtil;
+import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
+
+public class LightAdvHighlightingJdk8Test extends LightDaemonAnalyzerTestCase {
+  @NonNls static final String BASE_PATH = "/codeInsight/daemonCodeAnalyzer/lambda/advHighlighting";
+
+  @NotNull
+  @Override
+  protected LocalInspectionTool[] configureLocalInspectionTools() {
+    return new LocalInspectionTool[]{
+      new JavacQuirksInspection(),
+    };
+  }
+
+  public void testUnderscore() throws Exception {
+    doTest();
+  }
+
+  private void doTest() {
+    IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
+    doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", true, false);
+  }
+
+  @Override
+  protected Sdk getProjectJDK() {
+    return IdeaTestUtil.getMockJdk18();
+  }
+}
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MethodRefHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MethodRefHighlightingTest.java
index 1d09f51..b5c69c1 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MethodRefHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MethodRefHighlightingTest.java
@@ -99,6 +99,10 @@
     doTest();
   }
 
+  public void testQualifiersInStaticContext() throws Exception {
+    doTest();
+  }
+
   private void doTest() {
     doTest(false);
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MostSpecificResolutionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MostSpecificResolutionTest.java
index a46036c..e2a1411 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MostSpecificResolutionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MostSpecificResolutionTest.java
@@ -75,6 +75,26 @@
     doTest();
   }
 
+  public void testIncompleteMethodInInterface() throws Exception {
+    doTest(false);
+  }
+
+  public void testMostSpecificByReturnType() throws Exception {
+    doTest();
+  }
+
+  public void testDifferentParamsLength() throws Exception {
+    doTest(false);
+  }
+
+  public void testNoReturnTypeResolutionForThrownException() throws Exception {
+    doTest(false);
+  }
+
+  public void testBoxingAndOverloadResolution() throws Exception {
+    doTest();
+  }
+
   private void doTest() {
     doTest(true);
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java
index 5e21a82..f5f286a1 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewLambdaHighlightingTest.java
@@ -198,6 +198,14 @@
     doTest();
   }
 
+  public void testOnlyLambdaAtTypeParameterPlace() throws Exception {
+    doTest();
+  }
+
+  public void testLiftedIntersectionType() throws Exception {
+    doTest();
+  }
+
   private void doTest() {
     doTest(false);
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java
index 54ee87c..4028d71 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/NewMethodRefHighlightingTest.java
@@ -237,6 +237,18 @@
     doTest();
   }
 
+  public void testRefOnStaticInterfaceMethod() throws Exception {
+    doTest();
+  }
+
+  public void testUncheckedMethodReference() throws Exception {
+    doTest(true);
+  }
+
+  public void testIDEA124148() throws Exception {
+    doTest();
+  }
+
   private void doTest() {
     doTest(false);
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClass18Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClass18Test.java
index 84201d7..dfdf74b 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClass18Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClass18Test.java
@@ -15,8 +15,6 @@
  */
 package com.intellij.codeInsight.daemon.quickFix;
 
-import com.intellij.openapi.command.WriteCommandAction;
-
 /**
  * User: anna
  */
@@ -29,21 +27,4 @@
   protected String getBasePath() {
     return "/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal18";
   }
-
-  @Override
-  protected void beforeActionStarted(String testName, String contents) {
-    for (int i=0;i<10;i++) {
-      WriteCommandAction.runWriteCommandAction(null, new Runnable() {
-        @Override
-        public void run() {
-          myEditor.getDocument().insertString(myEditor.getCaretModel().getOffset(), "//");
-        }
-      });
-
-      doHighlighting();
-      delete();
-      delete();
-      doHighlighting();
-    }
-  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClassTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClassTest.java
index 98b8a74..e5bd455 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClassTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/quickFix/VariableAccessFromInnerClassTest.java
@@ -3,8 +3,12 @@
 
 import com.intellij.pom.java.LanguageLevel;
 
-public class VariableAccessFromInnerClassTest extends VariableAccessFromInnerClass18Test {
+public class VariableAccessFromInnerClassTest extends LightQuickFixParameterizedTestCase  {
 
+  public void test() throws Exception {
+    doAllTests();
+  }
+  
   @Override
   protected String getBasePath() {
     return "/codeInsight/daemonCodeAnalyzer/quickFix/mustBeFinal";
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/ListTemplateActionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/ListTemplateActionTest.java
new file mode 100644
index 0000000..6c06350
--- /dev/null
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/ListTemplateActionTest.java
@@ -0,0 +1,114 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template;
+
+import com.intellij.JavaTestUtil;
+import com.intellij.codeInsight.lookup.Lookup;
+import com.intellij.codeInsight.lookup.LookupElement;
+import com.intellij.codeInsight.template.impl.TemplateImpl;
+import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
+import com.intellij.codeInsight.template.impl.actions.ListTemplatesAction;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase;
+import com.intellij.util.containers.ContainerUtil;
+import org.jetbrains.annotations.NotNull;
+
+public class ListTemplateActionTest extends LightCodeInsightFixtureTestCase {
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    TemplateManagerImpl.setTemplateTesting(getProject(), getTestRootDisposable());
+    addTemplate("simple", "simple template text", "description");
+    addTemplate("complex key", "complex template text", "");
+  }
+
+  private void addTemplate(String key, String text, String description) {
+    TemplateManager manager = TemplateManager.getInstance(getProject());
+    TemplateImpl template = (TemplateImpl)manager.createTemplate(key, "test", text);
+    template.setDescription(description);
+    TemplateContextType contextType = ContainerUtil.findInstance(TemplateContextType.EP_NAME.getExtensions(), JavaCodeContextType.class);
+    template.getTemplateContext().setEnabled(contextType, true);
+    LiveTemplateTest.addTemplate(template, getTestRootDisposable());
+  }
+
+  @Override
+  protected String getBasePath() {
+    return JavaTestUtil.getRelativeJavaTestDataPath() + "/codeInsight/template/list/";
+  }
+
+  public void testWithoutPrefix() {
+    doTest("simple");
+  }
+
+  public void testPartialPrefix() {
+    doTest("simple");
+  }
+
+  public void testFullMatchPrefix() {
+    doTest("simple");
+  }
+
+  public void testNotMatchedPrefix() {
+    doTest("simple");
+  }
+
+  public void testNotMatchedPrefixAfterNonJavaCharacter() {
+    doTest("simple");
+  }
+
+  public void testMatchingByTemplateDescription() {
+    doTest("simple");
+  }
+
+  public void testComplexKeyWithoutPrefix() {
+    doTest("complex key");
+  }
+
+  public void testComplexKeyWithPartialPrefix() {
+    doTest("complex key");
+  }
+
+  public void testComplexKeyWithFullMatchPrefix() {
+    doTest("complex key");
+  }
+
+  public void testComplexKeyWithNotMatchedPrefix() {
+    doTest("complex key");
+  }
+
+  public void testComplexKeyWithNotMatchedPrefixAfterNonJavaCharacter() {
+    doTest("complex key");
+  }
+
+  private void doTest(@NotNull String lookupText) {
+    myFixture.configureByFile(getTestName(false) + ".java");
+    new ListTemplatesAction().actionPerformedImpl(myFixture.getProject(), myFixture.getEditor());
+
+    LookupElement[] elements = myFixture.getLookupElements();
+    assertNotNull(elements);
+    for (LookupElement element : elements) {
+      if (lookupText.equals(element.getLookupString())) {
+        myFixture.getLookup().setCurrentItem(element);
+        myFixture.finishLookup(Lookup.NORMAL_SELECT_CHAR);
+        myFixture.checkResultByFile(getTestName(false) + "_after.java");
+        return;
+      }
+    }
+    //noinspection ConstantConditions
+    fail("Lookup element with text '" + lookupText + "' not found:\n" + StringUtil.join(myFixture.getLookupElementStrings(), "\n"));
+  }
+}
+                                                                                                                          
\ No newline at end of file
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java
index 9fa0063..69d4585 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/completion/TemplatesCompletionTest.java
@@ -78,6 +78,21 @@
     doCompleteTest(".2", '\n');
   }
 
+  public void testRestartCompletionForExactMatch() {
+    configureByFile();
+    type("not");
+    LookupElement currentItem = getLookup().getCurrentItem();
+    assertNotNull(currentItem);
+    assertInstanceOf(currentItem, PostfixTemplateLookupElement.class);
+    assertEquals(".not", currentItem.getLookupString());
+
+    type("null");
+    currentItem = getLookup().getCurrentItem();
+    assertNotNull(currentItem);
+    assertInstanceOf(currentItem, PostfixTemplateLookupElement.class);
+    assertEquals(".notnull", currentItem.getLookupString());
+  }
+
   public void testShowTemplateInAutoPopup() {
     doAutoPopupTest("instanceof", InstanceofExpressionPostfixTemplate.class);
   }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateTestCase.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateTestCase.java
index 8960088..33e8447 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateTestCase.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/PostfixTemplateTestCase.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
 
 import com.intellij.JavaTestUtil;
@@ -37,5 +52,7 @@
     myFixture.addClass("package java.util;\n" +
                        "public class ArrayList<E> extends AbstractList<E>\n" +
                        "        implements List<E>, Iterable<E>, RandomAccess, Cloneable, java.io.Serializable {}");
+    myFixture.addClass("package java.lang;\n" +
+                       "public interface AutoCloseable {}");
   }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryPostfixTemplateTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryPostfixTemplateTest.java
index 7183883..4d6ebc3 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryPostfixTemplateTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryPostfixTemplateTest.java
@@ -17,28 +17,15 @@
 
 import org.jetbrains.annotations.NotNull;
 
-
 public class TryPostfixTemplateTest extends PostfixTemplateTestCase {
-
   @NotNull
   @Override
   protected String getSuffix() {
     return "try";
   }
 
-  public void testSimple() {
-    doTest();
-  }
-
-  public void testStatement() {
-    doTest();
-  }
-
-  public void testMultiStatement() {
-    doTest();
-  }
-
-  public void testNotStatement() {
-    doTest();
-  }
+  public void testSimple()          { doTest(); }
+  public void testStatement()       { doTest(); }
+  public void testMultiStatement()  { doTest(); }
+  public void testNotStatement()    { doTest(); }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplateTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplateTest.java
new file mode 100644
index 0000000..8363327
--- /dev/null
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/template/postfix/templates/TryWithResourcesPostfixTemplateTest.java
@@ -0,0 +1,39 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.template.postfix.templates;
+
+import com.intellij.openapi.roots.LanguageLevelProjectExtension;
+import com.intellij.pom.java.LanguageLevel;
+import org.jetbrains.annotations.NotNull;
+
+public class TryWithResourcesPostfixTemplateTest extends PostfixTemplateTestCase {
+  @NotNull
+  @Override
+  protected String getSuffix() {
+    return "twr";
+  }
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    LanguageLevelProjectExtension.getInstance(getProject()).setLanguageLevel(LanguageLevel.JDK_1_7);
+  }
+
+  public void testSimple()                  { doTest(); }
+  public void testSimpleWithMyException()   { doTest(); }
+  public void testSimpleWithConflict()      { doTest(); }
+  public void testSimpleNotAutoCloseable()  { doTest(); }
+}
diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java
index af69793..8de5e67 100644
--- a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspectionTest.java
@@ -179,6 +179,7 @@
   }
 
   public void testConstantDoubleComparisons() { doTest(); }
+  public void testInherentNumberRanges() { doTest(); }
 
   public void testMutableNullableFieldsTreatment() { doTest(); }
   public void testMutableVolatileNullableFieldsTreatment() { doTest(); }
@@ -286,7 +287,12 @@
   public void testNoConfusionWithAnonymousConstantInitializer() { doTest(); }
   public void testForeachOverWildcards() { doTest(); }
   public void testFinalGetter() { doTest(); }
-  
+
+  public void testByteBufferGetter() {
+    myFixture.addClass("package java.nio; public class MappedByteBuffer { public int getInt() {} }");
+    doTest();
+  }
+
   public void testManySequentialIfsNotComplex() { doTest(); }
   public void testManySequentialInstanceofsNotComplex() { doTest(); }
   public void testLongDisjunctionsNotComplex() { doTest(); }
diff --git a/java/java-tests/testSrc/com/intellij/execution/BaseConfigurationTestCase.java b/java/java-tests/testSrc/com/intellij/execution/BaseConfigurationTestCase.java
index 9a88daa..b6f79c1 100644
--- a/java/java-tests/testSrc/com/intellij/execution/BaseConfigurationTestCase.java
+++ b/java/java-tests/testSrc/com/intellij/execution/BaseConfigurationTestCase.java
@@ -103,7 +103,7 @@
 
   @NotNull
   public static Module createTempModule(TempFiles tempFiles, final Project project) {
-    final String tempPath = tempFiles.createTempPath();
+    final String tempPath = tempFiles.createTempFile("xxx").getAbsolutePath();
     return ApplicationManager.getApplication().runWriteAction(new Computable<Module>() {
       @Override
       public Module compute() {
diff --git a/java/java-tests/testSrc/com/intellij/execution/impl/RunConfigurableTest.java b/java/java-tests/testSrc/com/intellij/execution/impl/RunConfigurableTest.java
index 0591489..6d1b6b1 100644
--- a/java/java-tests/testSrc/com/intellij/execution/impl/RunConfigurableTest.java
+++ b/java/java-tests/testSrc/com/intellij/execution/impl/RunConfigurableTest.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2014 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.execution.impl;
 
 import com.intellij.execution.application.ApplicationConfigurationType;
@@ -179,7 +194,6 @@
     RunManagerImpl runManager = new RunManagerImpl(getProject(), PropertiesComponent.getInstance());
     runManager.initializeConfigurationTypes(new ConfigurationType[]{ApplicationConfigurationType.getInstance(),
       JUnitConfigurationType.getInstance(), UnknownConfigurationType.INSTANCE});
-    runManager.initComponent();
     runManager.readExternal(element);
     return runManager;
   }
diff --git a/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy b/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy
index 5deabbd..7b4d554 100644
--- a/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/navigation/ChooseByNameTest.groovy
@@ -184,7 +184,7 @@
     List<Object> elements = ['empty']
     def semaphore = new Semaphore()
     semaphore.down()
-    popup.scheduleCalcElements(text, false, false, ModalityState.NON_MODAL, { set ->
+    popup.scheduleCalcElements(text, false, ModalityState.NON_MODAL, { set ->
       elements = set as List
       semaphore.up()
     } as Consumer<Set<?>>)
diff --git a/java/openapi/src/com/intellij/openapi/projectRoots/JavaSdk.java b/java/openapi/src/com/intellij/openapi/projectRoots/JavaSdk.java
index 51ae01f..8221324 100644
--- a/java/openapi/src/com/intellij/openapi/projectRoots/JavaSdk.java
+++ b/java/openapi/src/com/intellij/openapi/projectRoots/JavaSdk.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +16,6 @@
 package com.intellij.openapi.projectRoots;
 
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.projectRoots.impl.SdkVersionUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -24,7 +23,7 @@
 
 import java.io.File;
 
-public abstract class JavaSdk extends SdkType implements JavaSdkType, ApplicationComponent {
+public abstract class JavaSdk extends SdkType implements JavaSdkType {
   public JavaSdk(@NotNull @NonNls String name) {
     super(name);
   }
diff --git a/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java b/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java
index 5df827f..bc99f65 100644
--- a/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java
+++ b/java/testFramework/src/com/intellij/testFramework/TestSourceBasedTestCase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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,6 +18,7 @@
 import com.intellij.ide.highlighter.ProjectFileType;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ex.PathManagerEx;
+import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -52,6 +53,12 @@
 
   }
 
+  @Override
+  protected void tearDown() throws Exception {
+    FileEditorManagerEx.getInstanceEx(getProject()).closeAllFiles();
+    super.tearDown();
+  }
+
   protected String getTestDataPath() {
     return PathManagerEx.getTestDataPath(getClass());
   }
diff --git a/platform/analysis-api/src/com/intellij/codeInspection/ui/MultipleCheckboxOptionsPanel.java b/platform/analysis-api/src/com/intellij/codeInspection/ui/MultipleCheckboxOptionsPanel.java
index da36da2..a43b60ad 100644
--- a/platform/analysis-api/src/com/intellij/codeInspection/ui/MultipleCheckboxOptionsPanel.java
+++ b/platform/analysis-api/src/com/intellij/codeInspection/ui/MultipleCheckboxOptionsPanel.java
@@ -22,22 +22,25 @@
 import javax.swing.event.ChangeEvent;
 import javax.swing.event.ChangeListener;
 import java.awt.*;
-import java.lang.reflect.Field;
 
 public class MultipleCheckboxOptionsPanel extends JPanel {
 
-    private final InspectionProfileEntry owner;
+    private final OptionAccessor myOptionAccessor;
 
-    public MultipleCheckboxOptionsPanel(InspectionProfileEntry owner) {
+    public MultipleCheckboxOptionsPanel(final InspectionProfileEntry owner) {
+        this(new OptionAccessor.Default(owner));
+    }
+
+    public MultipleCheckboxOptionsPanel(final OptionAccessor optionAccessor) {
         super(new GridBagLayout());
-        this.owner = owner;
+        myOptionAccessor = optionAccessor;
     }
 
     public void addCheckbox(String label,
                             @NonNls String property) {
-        final boolean selected = getPropertyValue(owner, property);
+        final boolean selected = myOptionAccessor.getOption(property);
         final JCheckBox checkBox = new JCheckBox(label, selected);
-        configureCheckbox(owner, property, checkBox);
+        configureCheckbox(myOptionAccessor, property, checkBox);
         final GridBagConstraints constraints = new GridBagConstraints();
         constraints.anchor = GridBagConstraints.FIRST_LINE_START;
         constraints.gridx = 0;
@@ -54,59 +57,33 @@
         add(checkBox, constraints);
     }
 
-    private static void configureCheckbox(InspectionProfileEntry owner, String property, JCheckBox checkBox) {
+    private static void configureCheckbox(OptionAccessor accessor, String property, JCheckBox checkBox) {
         final ButtonModel model = checkBox.getModel();
-        final CheckboxChangeListener changeListener = new CheckboxChangeListener(owner, property, model);
+        final CheckboxChangeListener changeListener = new CheckboxChangeListener(accessor, property, model);
         model.addChangeListener(changeListener);
     }
 
     public static void initAndConfigureCheckbox(InspectionProfileEntry owner, String property, JCheckBox checkBox) {
-        checkBox.setSelected(getPropertyValue(owner, property));
-        configureCheckbox(owner, property, checkBox);
-    }
-
-    private static boolean getPropertyValue(InspectionProfileEntry owner,
-                                            String property) {
-        try {
-            final Class<? extends InspectionProfileEntry> aClass = owner.getClass();
-            final Field field = aClass.getField(property);
-            return field.getBoolean(owner);
-        } catch (IllegalAccessException ignored) {
-            return false;
-        } catch (NoSuchFieldException ignored) {
-            return false;
-        }
+        OptionAccessor optionAccessor = new OptionAccessor.Default(owner);
+        checkBox.setSelected(optionAccessor.getOption(property));
+        configureCheckbox(optionAccessor, property, checkBox);
     }
 
     private static class CheckboxChangeListener implements ChangeListener {
-        private final InspectionProfileEntry owner;
+        private final OptionAccessor myAccessor;
         private final String property;
         private final ButtonModel model;
 
-        CheckboxChangeListener(InspectionProfileEntry owner, String property,
-                               ButtonModel model) {
-            this.owner = owner;
+        CheckboxChangeListener(OptionAccessor myAccessor, String property, ButtonModel model) {
+            this.myAccessor = myAccessor;
             this.property = property;
             this.model = model;
         }
 
         @Override
         public void stateChanged(ChangeEvent e) {
-            setPropertyValue(owner, property, model.isSelected());
+            myAccessor.setOption(property, model.isSelected());
         }
 
-        private static void setPropertyValue(InspectionProfileEntry owner,
-                                             String property,
-                                             boolean selected) {
-            try {
-                final Class<? extends InspectionProfileEntry> aClass = owner.getClass();
-                final Field field = aClass.getField(property);
-                field.setBoolean(owner, selected);
-            } catch (IllegalAccessException ignored) {
-                // nothing
-            } catch (NoSuchFieldException ignored) {
-                // nothing
-            }
-        }
     }
 }
\ No newline at end of file
diff --git a/platform/analysis-api/src/com/intellij/codeInspection/ui/OptionAccessor.java b/platform/analysis-api/src/com/intellij/codeInspection/ui/OptionAccessor.java
new file mode 100644
index 0000000..eecd6d7
--- /dev/null
+++ b/platform/analysis-api/src/com/intellij/codeInspection/ui/OptionAccessor.java
@@ -0,0 +1,65 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.ui;
+
+import com.intellij.codeInspection.InspectionProfileEntry;
+
+import java.lang.reflect.Field;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public interface OptionAccessor {
+
+  boolean getOption(String optionName);
+
+  void setOption(String optionName, boolean optionValue);
+
+  class Default implements OptionAccessor {
+    private final InspectionProfileEntry myInspection;
+
+    public Default(final InspectionProfileEntry inspection) {
+      myInspection = inspection;
+    }
+
+    @Override
+    public boolean getOption(final String optionName) {
+      try {
+        final Class<? extends InspectionProfileEntry> aClass = myInspection.getClass();
+        final Field field = aClass.getField(optionName);
+        return field.getBoolean(myInspection);
+      } catch (IllegalAccessException ignored) {
+        return false;
+      } catch (NoSuchFieldException ignored) {
+        return false;
+      }
+    }
+
+    @Override
+    public void setOption(final String optionName, boolean optionValue) {
+      try {
+        final Class<? extends InspectionProfileEntry> aClass = myInspection.getClass();
+        final Field field = aClass.getField(optionName);
+        field.setBoolean(myInspection, optionValue);
+      } catch (IllegalAccessException ignored) {
+        // nothing
+      } catch (NoSuchFieldException ignored) {
+        // nothing
+      }
+    }
+  }
+
+}
diff --git a/platform/analysis-api/src/com/intellij/problems/WolfTheProblemSolver.java b/platform/analysis-api/src/com/intellij/problems/WolfTheProblemSolver.java
index d57e62ed..c4580e0 100644
--- a/platform/analysis-api/src/com/intellij/problems/WolfTheProblemSolver.java
+++ b/platform/analysis-api/src/com/intellij/problems/WolfTheProblemSolver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +17,6 @@
 package com.intellij.problems;
 
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.components.ProjectComponent;
 import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
@@ -31,7 +30,7 @@
 /**
  * @author cdr
  */
-public abstract class WolfTheProblemSolver implements ProjectComponent {
+public abstract class WolfTheProblemSolver {
   public static final ExtensionPointName<Condition<VirtualFile>> FILTER_EP_NAME = ExtensionPointName.create("com.intellij.problemFileHighlightFilter");
 
   public static WolfTheProblemSolver getInstance(Project project) {
diff --git a/platform/analysis-impl/src/com/intellij/codeInspection/inspection-black-list.txt b/platform/analysis-impl/src/com/intellij/codeInspection/inspection-black-list.txt
index 18ea3dd..5b937f5 100644
--- a/platform/analysis-impl/src/com/intellij/codeInspection/inspection-black-list.txt
+++ b/platform/analysis-impl/src/com/intellij/codeInspection/inspection-black-list.txt
@@ -10,7 +10,7 @@
 com.intellij.codeInspection.htmlInspections.HtmlUnknownTagInspection
 com.intellij.codeInspection.htmlInspections.RequiredAttributesInspection
 com.intellij.codeInspection.i18n.I18nInspection
-com.intellij.codeInspection.i18n.InconsistentResourceBundleInspection
+com.intellij.codeInspection.i18n.inconsistentResourceBundle.InconsistentResourceBundleInspection
 com.intellij.codeInspection.javaDoc.JavaDocLocalInspection
 com.intellij.codeInspection.localCanBeFinal.LocalCanBeFinal
 com.intellij.codeInspection.miscGenerics.SuspiciousCollectionsMethodCallsInspection
diff --git a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java
index b15ecb7..1ab2466 100644
--- a/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java
+++ b/platform/analysis-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/providers/FileReference.java
@@ -128,15 +128,11 @@
     return ResolveCache.getInstance(file.getProject()).resolveWithCaching(this, MyResolver.INSTANCE, false, false, file);
   }
 
-  protected ResolveResult[] innerResolve() {
-    return innerResolve(getFileReferenceSet().isCaseSensitive());
-  }
-
   @NotNull
-  protected ResolveResult[] innerResolve(boolean caseSensitive) {
+  protected ResolveResult[] innerResolve(boolean caseSensitive, @NotNull PsiFile containingFile) {
     final String referenceText = getText();
     if (referenceText.isEmpty() && myIndex == 0) {
-      return new ResolveResult[]{new PsiElementResolveResult(getElement().getContainingFile())};
+      return new ResolveResult[]{new PsiElementResolveResult(containingFile)};
     }
     final Collection<PsiFileSystemItem> contexts = getContexts();
     final Collection<ResolveResult> result = new THashSet<ResolveResult>();
@@ -144,7 +140,7 @@
       innerResolveInContext(referenceText, context, result, caseSensitive);
     }
     if (contexts.isEmpty() && isAllowedEmptyPath(referenceText)) {
-      result.add(new PsiElementResolveResult(getElement().getContainingFile()));
+      result.add(new PsiElementResolveResult(containingFile));
     }
     final int resultCount = result.size();
     return resultCount > 0 ? result.toArray(new ResolveResult[resultCount]) : ResolveResult.EMPTY_ARRAY;
@@ -330,8 +326,8 @@
   }
 
   @Nullable
-  public PsiFileSystemItem innerSingleResolve(final boolean caseSensitive) {
-    final ResolveResult[] resolveResults = innerResolve(caseSensitive);
+  public PsiFileSystemItem innerSingleResolve(final boolean caseSensitive, @NotNull PsiFile containingFile) {
+    final ResolveResult[] resolveResults = innerResolve(caseSensitive, containingFile);
     return resolveResults.length == 1 ? (PsiFileSystemItem)resolveResults[0].getElement() : null;
   }
 
@@ -553,13 +549,13 @@
     return myFileReferenceSet.getLastReference();
   }
 
-  static class MyResolver implements ResolveCache.PolyVariantResolver<FileReference> {
+  static class MyResolver implements ResolveCache.PolyVariantContextResolver<FileReference> {
     static final MyResolver INSTANCE = new MyResolver();
 
     @NotNull
     @Override
-    public ResolveResult[] resolve(@NotNull FileReference ref, boolean incompleteCode) {
-      return ref.innerResolve(ref.getFileReferenceSet().isCaseSensitive());
+    public ResolveResult[] resolve(@NotNull FileReference ref, @NotNull PsiFile containingFile, boolean incompleteCode) {
+      return ref.innerResolve(ref.getFileReferenceSet().isCaseSensitive(), containingFile);
     }
   }
 }
diff --git a/platform/bootstrap/src/com/intellij/ide/startup/StartupActionScriptManager.java b/platform/bootstrap/src/com/intellij/ide/startup/StartupActionScriptManager.java
index 3a21db3..fd2882d 100644
--- a/platform/bootstrap/src/com/intellij/ide/startup/StartupActionScriptManager.java
+++ b/platform/bootstrap/src/com/intellij/ide/startup/StartupActionScriptManager.java
@@ -33,6 +33,7 @@
 @SuppressWarnings({"HardCodedStringLiteral"})
 public class StartupActionScriptManager {
   private static final Logger LOG = Logger.getInstance("#com.intellij.ide.startup.StartupActionScriptManager");
+  @NonNls public static final String STARTUP_WIZARD_MODE = "StartupWizardMode";
 
   @NonNls private static final String ACTION_SCRIPT_FILE = "action.script";
 
@@ -53,6 +54,10 @@
   }
 
   public static synchronized void addActionCommand(ActionCommand command) throws IOException {
+    if (Boolean.getBoolean(STARTUP_WIZARD_MODE)) {
+      command.execute();
+      return;
+    }
     final List<ActionCommand> commands = loadActionScript();
     commands.add(command);
     saveActionScript(commands);
diff --git a/platform/core-api/src/com/intellij/lang/folding/CustomFoldingBuilder.java b/platform/core-api/src/com/intellij/lang/folding/CustomFoldingBuilder.java
index b215fad..f9f3148 100644
--- a/platform/core-api/src/com/intellij/lang/folding/CustomFoldingBuilder.java
+++ b/platform/core-api/src/com/intellij/lang/folding/CustomFoldingBuilder.java
@@ -29,7 +29,8 @@
     List<FoldingDescriptor> descriptors = new ArrayList<FoldingDescriptor>();
     if (CustomFoldingProvider.getAllProviders().length > 0) {
       myDefaultProvider = null;
-      addCustomFoldingRegionsRecursively(null, root.getNode(), descriptors, 0);
+      ASTNode rootNode = root.getNode();
+      addCustomFoldingRegionsRecursively(new FoldingStack(rootNode), rootNode, descriptors, 0);
     }
     buildLanguageFoldRegions(descriptors, root, document, quick);
     return descriptors.toArray(new FoldingDescriptor[descriptors.size()]);
@@ -55,11 +56,11 @@
                                                    @NotNull Document document,
                                                    boolean quick);
 
-  private void addCustomFoldingRegionsRecursively(@Nullable FoldingStack foldingStack,
+  private void addCustomFoldingRegionsRecursively(@NotNull FoldingStack foldingStack,
                                                   @NotNull ASTNode node,
                                                   @NotNull List<FoldingDescriptor> descriptors,
                                                   int currDepth) {
-    FoldingStack localFoldingStack = isCustomFoldingRoot(node) || foldingStack == null ? new FoldingStack(node) : foldingStack;
+    FoldingStack localFoldingStack = isCustomFoldingRoot(node) ? new FoldingStack(node) : foldingStack;
     for (ASTNode child = node.getFirstChildNode(); child != null; child = child.getTreeNext()) {
       if (isCustomRegionStart(child)) {
         localFoldingStack.push(child);
@@ -103,15 +104,10 @@
 
   @Override
   public final boolean isCollapsedByDefault(@NotNull ASTNode node) {
-    // TODO<rv>: Modify Folding API and pass here folding range.
-    if (isCustomFoldingRoot(node)) {
-      for (ASTNode child = node.getFirstChildNode(); child != null; child = child.getTreeNext()) {
-        if (isCustomRegionStart(child)) {
-          String childText = child.getText();
-          CustomFoldingProvider defaultProvider = getDefaultProvider(childText);
-          return defaultProvider != null && defaultProvider.isCollapsedByDefault(childText);
-        }
-      }
+    if (isCustomRegionStart(node)) {
+      String childText = node.getText();
+      CustomFoldingProvider defaultProvider = getDefaultProvider(childText);
+      return defaultProvider != null && defaultProvider.isCollapsedByDefault(childText);
     }
     return isRegionCollapsedByDefault(node);
   }
@@ -180,8 +176,8 @@
 
   /**
    * Checks if the node is used as custom folding root. Any custom folding elements inside the root are considered to be at the same level
-   * even if they are located at different levels of PSI tree. Collected folding descriptors always contain only root elements with
-   * appropriate ranges. The method returns true if the node has any child elements.
+   * even if they are located at different levels of PSI tree. By default the method returns true if the node has any child elements
+   * (only custom folding comments at the same PSI tree level are processed, start/end comments at different levels will be ignored).
    *
    * @param node  The node to check.
    * @return      True if the node is a root for custom foldings.
diff --git a/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java b/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java
index 36333be..bd4c921 100644
--- a/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java
+++ b/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -172,6 +172,7 @@
    * @return a copy of the file
    * @throws java.io.IOException if file failed to be copied
    */
+  @NotNull
   public static VirtualFile copyFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile toDir) throws IOException {
     return copyFile(requestor, file, toDir, file.getName());
   }
@@ -188,6 +189,7 @@
    * @return a copy of the file
    * @throws java.io.IOException if file failed to be copied
    */
+  @NotNull
   public static VirtualFile copyFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile toDir, @NotNull @NonNls String newName)
     throws IOException {
     final VirtualFile newChild = toDir.createChildData(requestor, newName);
diff --git a/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileSystem.java b/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileSystem.java
index 8bd36a1..9da56eb 100644
--- a/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileSystem.java
+++ b/platform/core-api/src/com/intellij/openapi/vfs/VirtualFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -151,6 +151,7 @@
    *
    * @see VirtualFile#createChildData(Object,String)
    */
+  @NotNull
   protected abstract VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException;
 
   /**
@@ -166,6 +167,7 @@
    *
    * @see VirtualFile#copy(Object,VirtualFile,String)
    */
+  @NotNull
   protected abstract VirtualFile copyFile(final Object requestor,
                                           @NotNull VirtualFile virtualFile,
                                           @NotNull VirtualFile newParent,
diff --git a/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java
index c9344b0..48f5c27 100644
--- a/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java
+++ b/platform/core-api/src/com/intellij/openapi/vfs/encoding/EncodingRegistry.java
@@ -50,6 +50,7 @@
   @Nullable
   public abstract Charset getEncoding(@Nullable VirtualFile virtualFile, boolean useParentDefaults);
 
+  @Deprecated // return true always
   public abstract boolean isUseUTFGuessing(VirtualFile virtualFile);
 
   public abstract void setEncoding(@Nullable("null means project") VirtualFile virtualFileOrDir, @Nullable("null means remove mapping") Charset charset);
diff --git a/platform/core-api/src/com/intellij/openapi/vfs/ex/http/HttpFileSystem.java b/platform/core-api/src/com/intellij/openapi/vfs/ex/http/HttpFileSystem.java
index 9f8982f..9ab4fd3 100644
--- a/platform/core-api/src/com/intellij/openapi/vfs/ex/http/HttpFileSystem.java
+++ b/platform/core-api/src/com/intellij/openapi/vfs/ex/http/HttpFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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,14 +16,13 @@
 package com.intellij.openapi.vfs.ex.http;
 
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.vfs.DeprecatedVirtualFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.VirtualFileManager;
 import com.intellij.util.io.URLUtil;
 import org.jetbrains.annotations.NotNull;
 
-public abstract class HttpFileSystem extends DeprecatedVirtualFileSystem implements ApplicationComponent {
+public abstract class HttpFileSystem extends DeprecatedVirtualFileSystem {
   @Deprecated
   @SuppressWarnings("UnusedDeclaration")
   /**
diff --git a/platform/core-api/src/com/intellij/psi/search/DelegatingGlobalSearchScope.java b/platform/core-api/src/com/intellij/psi/search/DelegatingGlobalSearchScope.java
index 55b85d1..d3ae32a 100644
--- a/platform/core-api/src/com/intellij/psi/search/DelegatingGlobalSearchScope.java
+++ b/platform/core-api/src/com/intellij/psi/search/DelegatingGlobalSearchScope.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -35,7 +35,7 @@
     myEquality = ArrayUtil.EMPTY_OBJECT_ARRAY;
   }
 
-  public DelegatingGlobalSearchScope(GlobalSearchScope baseScope, Object... equality) {
+  public DelegatingGlobalSearchScope(@NotNull GlobalSearchScope baseScope, @NotNull Object... equality) {
     super(baseScope.getProject());
     myBaseScope = baseScope;
     myEquality = Arrays.asList(equality);
diff --git a/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java b/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java
index 96255eb..b73cb5d 100644
--- a/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java
+++ b/platform/core-api/src/com/intellij/psi/search/GlobalSearchScope.java
@@ -187,6 +187,11 @@
       public boolean isSearchOutsideRootModel() {
         return true;
       }
+
+      @Override
+      public String toString() {
+        return "NOT: "+myBaseScope;
+      }
     };
   }
 
@@ -568,6 +573,11 @@
     public GlobalSearchScope uniteWith(@NotNull final GlobalSearchScope scope) {
       return scope;
     }
+
+    @Override
+    public String toString() {
+      return "EMPTY";
+    }
   }
 
   public static final GlobalSearchScope EMPTY_SCOPE = new EmptyScope();
@@ -576,11 +586,10 @@
     private final VirtualFile myVirtualFile;
     private final Module myModule;
 
-    private FileScope(@NotNull Project project, final VirtualFile virtualFile) {
+    private FileScope(@NotNull Project project, VirtualFile virtualFile) {
       super(project);
       myVirtualFile = virtualFile;
-      myModule = virtualFile != null && !project.isDefault() ?
-                 FileIndexFacade.getInstance(project).getModuleForFile(virtualFile) : null;
+      myModule = virtualFile == null || project.isDefault() ? null : FileIndexFacade.getInstance(project).getModuleForFile(virtualFile);
     }
 
     @Override
@@ -602,12 +611,17 @@
     public boolean isSearchInLibraries() {
       return myModule == null;
     }
+
+    @Override
+    public String toString() {
+      return "File :"+myVirtualFile;
+    }
   }
 
   public static class FilesScope extends GlobalSearchScope {
     private final Collection<VirtualFile> myFiles;
 
-    public FilesScope(final Project project, final Collection<VirtualFile> files) {
+    public FilesScope(final Project project, @NotNull Collection<VirtualFile> files) {
       super(project);
       myFiles = files;
     }
@@ -642,5 +656,11 @@
     public int hashCode() {
       return myFiles.hashCode();
     }
+
+    @Override
+    public String toString() {
+      List<VirtualFile> files = myFiles.size() <= 20 ? new ArrayList<VirtualFile>(myFiles) : new ArrayList<VirtualFile>(myFiles).subList(0,20);
+      return "Files: ("+ files +")";
+    }
   }
 }
diff --git a/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java b/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java
index 55222cf..bc518e1 100644
--- a/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java
+++ b/platform/core-api/src/com/intellij/testFramework/LightVirtualFile.java
@@ -150,6 +150,7 @@
     public void moveFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent) throws IOException {
     }
 
+    @NotNull
     @Override
     public VirtualFile copyFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent, @NotNull final String copyName) throws IOException {
       throw new IOException("Cannot copy files");
@@ -159,6 +160,7 @@
     public void renameFile(Object requestor, @NotNull VirtualFile vFile, @NotNull String newName) throws IOException {
     }
 
+    @NotNull
     @Override
     public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
       throw new IOException("Cannot create files");
diff --git a/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java b/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java
index 34c1e06..f5f234a 100644
--- a/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java
+++ b/platform/core-impl/src/com/intellij/openapi/fileEditor/impl/LoadTextUtil.java
@@ -158,14 +158,14 @@
     return bomAndCharset;
   }
 
+  private static final boolean GUESS_UTF = Boolean.parseBoolean(System.getProperty("idea.guess.utf.encoding", "true"));
+
   @Nullable("null means no luck, otherwise it's tuple(guessed encoding, hint about content if was unable to guess, BOM)")
   public static Trinity<Charset, CharsetToolkit.GuessedEncoding, byte[]> guessFromContent(@NotNull VirtualFile virtualFile, @NotNull byte[] content, int length) {
-    EncodingRegistry settings = EncodingRegistry.getInstance();
-    boolean shouldGuess = settings != null && settings.isUseUTFGuessing(virtualFile);
-    CharsetToolkit toolkit = shouldGuess ? new CharsetToolkit(content, EncodingRegistry.getInstance().getDefaultCharset()) : null;
+    CharsetToolkit toolkit = GUESS_UTF ? new CharsetToolkit(content, EncodingRegistry.getInstance().getDefaultCharset()) : null;
     String detectedFromBytes = null;
     try {
-      if (shouldGuess) {
+      if (GUESS_UTF) {
         toolkit.setEnforce8Bit(true);
         Charset charset = toolkit.guessFromBOM();
         if (charset != null) {
diff --git a/platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/CoreJarFileSystem.java b/platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/CoreJarFileSystem.java
index 31c5ab2..82e84ef 100644
--- a/platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/CoreJarFileSystem.java
+++ b/platform/core-impl/src/com/intellij/openapi/vfs/impl/jar/CoreJarFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -83,6 +83,7 @@
     throw new UnsupportedOperationException("JarFileSystem is read-only");
   }
 
+  @NotNull
   @Override
   protected VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
     throw new UnsupportedOperationException("JarFileSystem is read-only");
@@ -94,6 +95,7 @@
     throw new UnsupportedOperationException("JarFileSystem is read-only");
   }
 
+  @NotNull
   @Override
   protected VirtualFile copyFile(Object requestor,
                                  @NotNull VirtualFile virtualFile,
diff --git a/platform/core-impl/src/com/intellij/openapi/vfs/local/CoreLocalFileSystem.java b/platform/core-impl/src/com/intellij/openapi/vfs/local/CoreLocalFileSystem.java
index 3049b39..b9d99c4 100644
--- a/platform/core-impl/src/com/intellij/openapi/vfs/local/CoreLocalFileSystem.java
+++ b/platform/core-impl/src/com/intellij/openapi/vfs/local/CoreLocalFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -69,6 +69,7 @@
     throw new UnsupportedOperationException("renameFile() not supported");
   }
 
+  @NotNull
   @Override
   protected VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
     throw new UnsupportedOperationException("createChildFile() not supported");
@@ -80,6 +81,7 @@
     throw new UnsupportedOperationException("createChildDirectory() not supported");
   }
 
+  @NotNull
   @Override
   protected VirtualFile copyFile(Object requestor,
                                  @NotNull VirtualFile virtualFile,
diff --git a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java
index 364c9d7..c580f65 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/PsiDocumentManagerBase.java
@@ -20,7 +20,6 @@
 import com.intellij.lang.injection.InjectedLanguageManager;
 import com.intellij.openapi.application.Application;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.components.ProjectComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.event.DocumentEvent;
@@ -56,7 +55,7 @@
 import javax.swing.*;
 import java.util.*;
 
-public abstract class PsiDocumentManagerBase extends PsiDocumentManager implements ProjectComponent, DocumentListener {
+public abstract class PsiDocumentManagerBase extends PsiDocumentManager implements DocumentListener {
   protected static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.PsiDocumentManagerImpl");
   private static final Key<PsiFile> HARD_REF_TO_PSI = new Key<PsiFile>("HARD_REFERENCE_TO_PSI");
   private static final Key<List<Runnable>> ACTION_AFTER_COMMIT = Key.create("ACTION_AFTER_COMMIT");
@@ -87,28 +86,6 @@
   }
 
   @Override
-  public void projectOpened() {
-  }
-
-  @Override
-  public void projectClosed() {
-  }
-
-  @Override
-  @NotNull
-  public String getComponentName() {
-    return "PsiDocumentManager";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   @Nullable
   public PsiFile getPsiFile(@NotNull Document document) {
     final PsiFile userData = document.getUserData(HARD_REF_TO_PSI);
diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java b/platform/core-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java
index b6fd267..859a604 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/source/resolve/ResolveCache.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -53,6 +53,10 @@
     @NotNull
     ResolveResult[] resolve(@NotNull T t, boolean incompleteCode);
   }
+  public interface PolyVariantContextResolver<T extends PsiPolyVariantReference> {
+    @NotNull
+    ResolveResult[] resolve(@NotNull T ref, @NotNull PsiFile containingFile, boolean incompleteCode);
+  }
 
   public interface Resolver extends AbstractResolver<PsiReference,PsiElement>{
   }
@@ -132,6 +136,36 @@
     return result == null ? ResolveResult.EMPTY_ARRAY : result;
   }
 
+  @NotNull
+  public <T extends PsiPolyVariantReference> ResolveResult[] resolveWithCaching(@NotNull final T ref,
+                                                                                @NotNull final PolyVariantContextResolver<T> resolver,
+                                                                                boolean needToPreventRecursion,
+                                                                                final boolean incompleteCode,
+                                                                                @NotNull final PsiFile containingFile) {
+    ProgressIndicatorProvider.checkCanceled();
+    ApplicationManager.getApplication().assertReadAccessAllowed();
+
+    ConcurrentMap<T, Getter<ResolveResult[]>> map = getMap(containingFile.isPhysical(), incompleteCode, true);
+    Getter<ResolveResult[]> reference = map.get(ref);
+    ResolveResult[] result = reference == null ? null : reference.get();
+    if (result != null) {
+      return result;
+    }
+
+    RecursionGuard.StackStamp stamp = myGuard.markStack();
+    result = needToPreventRecursion ? myGuard.doPreventingRecursion(Pair.create(ref, incompleteCode), true, new Computable<ResolveResult[]>() {
+      @Override
+      public ResolveResult[] compute() {
+        return resolver.resolve(ref, containingFile, incompleteCode);
+      }
+    }) : resolver.resolve(ref, containingFile, incompleteCode);
+
+    if (stamp.mayCacheNow()) {
+      cache(ref, map, result, true);
+    }
+    return result == null ? ResolveResult.EMPTY_ARRAY : result;
+  }
+
   @Nullable
   public <T extends PsiPolyVariantReference> ResolveResult[] getCachedResults(@NotNull T ref, boolean physical, boolean incompleteCode, boolean isPoly) {
     Map<T, Getter<ResolveResult[]>> map = getMap(physical, incompleteCode, isPoly);
@@ -148,13 +182,14 @@
     return resolve(ref, resolver, needToPreventRecursion, incompleteCode, false, ref.getElement().isPhysical());
   }
 
+  @NotNull
   private <TRef extends PsiReference,TResult> ConcurrentMap<TRef, Getter<TResult>> getMap(boolean physical, boolean incompleteCode, boolean isPoly) {
     //noinspection unchecked
     return myMaps[(physical ? 0 : 1)*4 + (incompleteCode ? 0 : 1)*2 + (isPoly ? 0 : 1)];
   }
 
   private static class SoftGetter<T> extends SoftReference<T> implements Getter<T> {
-    public SoftGetter(T referent) {
+    public SoftGetter(@NotNull T referent) {
       super(referent);
     }
   }
diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/PsiPolyVariantCachingReference.java b/platform/core-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/PsiPolyVariantCachingReference.java
index f55958d..fb54390 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/PsiPolyVariantCachingReference.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/source/resolve/reference/impl/PsiPolyVariantCachingReference.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -39,7 +39,7 @@
   }
 
   @NotNull
-  protected abstract ResolveResult[] resolveInner(boolean incompleteCode);
+  protected abstract ResolveResult[] resolveInner(boolean incompleteCode, @NotNull PsiFile containingFile);
 
   @Override
   public boolean isReferenceTo(final PsiElement element) {
@@ -56,13 +56,13 @@
     return ElementManipulators.getManipulator(currentElement);
   }
 
-  private static class MyResolver implements ResolveCache.PolyVariantResolver<PsiPolyVariantReference> {
+  private static class MyResolver implements ResolveCache.PolyVariantContextResolver<PsiPolyVariantReference> {
     private static final MyResolver INSTANCE = new MyResolver();
 
     @NotNull
     @Override
-    public ResolveResult[] resolve(@NotNull PsiPolyVariantReference reference, boolean incompleteCode) {
-      return ((PsiPolyVariantCachingReference)reference).resolveInner(incompleteCode);
+    public ResolveResult[] resolve(@NotNull PsiPolyVariantReference ref, @NotNull PsiFile containingFile, boolean incompleteCode) {
+      return ((PsiPolyVariantCachingReference)ref).resolveInner(incompleteCode, containingFile);
     }
   }
 }
diff --git a/platform/core-impl/src/com/intellij/util/PatchedWeakReference.java b/platform/core-impl/src/com/intellij/util/PatchedWeakReference.java
index b3c5367..17d81e0 100644
--- a/platform/core-impl/src/com/intellij/util/PatchedWeakReference.java
+++ b/platform/core-impl/src/com/intellij/util/PatchedWeakReference.java
@@ -15,77 +15,12 @@
  */
 package com.intellij.util;
 
-import com.intellij.concurrency.JobScheduler;
-import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.Getter;
-import org.jetbrains.annotations.TestOnly;
 
-import java.lang.ref.Reference;
-import java.lang.ref.ReferenceQueue;
 import java.lang.ref.WeakReference;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
 
 public class PatchedWeakReference<T> extends WeakReference<T> implements Getter<T> {
-  private static final Logger LOG = Logger.getInstance("#com.intellij.util.PatchedWeakReference");
-
-  private static List<PatchedWeakReference<?>> ourRefsList = new ArrayList<PatchedWeakReference<?>>();
-  private static final ReferenceQueue ourQueue = new ReferenceQueue();
-
-  static {
-    JobScheduler.getScheduler().scheduleWithFixedDelay(new Runnable() {
-      @Override
-      public void run() {
-        processQueue();
-      }
-    }, (long)500, (long)500, TimeUnit.MILLISECONDS);
-  }
-
   public PatchedWeakReference(T referent) {
-    super(referent, ourQueue);
-    synchronized(ourQueue) {
-      ourRefsList.add(this);
-    }
-  }
-
-  private static void processQueue() {
-    boolean haveClearedRefs = false;
-    while(true){
-      Reference ref = ourQueue.poll();
-      if (ref == null) {
-        break;
-      }
-      else {
-        haveClearedRefs = true;
-      }
-    }
-    if (!haveClearedRefs) return;
-
-    synchronized(ourQueue) {
-      ArrayList<PatchedWeakReference<?>> newList = new ArrayList<PatchedWeakReference<?>>(ourRefsList.size()/2+1);
-      for(int i = 0; i < ourRefsList.size(); i++){
-        PatchedWeakReference<?> ref = ourRefsList.get(i);
-        if (ref.get() != null){
-          newList.add(ref);
-        }
-      }
-
-      if (LOG.isDebugEnabled()){
-        LOG.info("old size:" + ourRefsList.size());
-        LOG.info("new size:" + newList.size());
-      }
-      //System.out.println("old size:" + ourRefsList.size());
-      //System.out.println("new size:" + newList.size());
-      ourRefsList = newList;
-    }
-  }
-
-  @TestOnly
-  public static void clearAll() {
-    synchronized (ourQueue) {
-      while (ourQueue.poll() != null);
-      ourRefsList = new ArrayList<PatchedWeakReference<?>>();
-    }
+    super(referent);
   }
 }
diff --git a/platform/core-impl/src/com/intellij/util/indexing/SubstitutedFileType.java b/platform/core-impl/src/com/intellij/util/indexing/SubstitutedFileType.java
index 83c2573..0e0a5ef 100644
--- a/platform/core-impl/src/com/intellij/util/indexing/SubstitutedFileType.java
+++ b/platform/core-impl/src/com/intellij/util/indexing/SubstitutedFileType.java
@@ -41,7 +41,7 @@
   }
 
   @NotNull
-  public static FileType substituteFileType(VirtualFile file, @NotNull FileType fileType, Project project) {
+  public static FileType substituteFileType(@NotNull VirtualFile file, @NotNull FileType fileType, Project project) {
     if (project == null) {
       return fileType;
     }
@@ -98,4 +98,9 @@
   public boolean isSameFileType() {
     return myFileType.equals(myOriginalFileType);
   }
+
+  @Override
+  public String toString() {
+    return "SubstitutedFileType: original="+myOriginalFileType+"; substituted="+myFileType;
+  }
 }
diff --git a/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java b/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
index f098090..dba42be 100644
--- a/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
+++ b/platform/editor-ui-api/src/com/intellij/ide/ui/UISettings.java
@@ -110,6 +110,7 @@
   public int MAX_LOOKUP_WIDTH2 = 500;
   public int MAX_LOOKUP_LIST_HEIGHT = 11;
   public boolean HIDE_NAVIGATION_ON_FOCUS_LOSS = true;
+  public boolean DND_WITH_PRESSED_ALT_ONLY = false;
   public boolean FILE_COLORS_IN_PROJECT_VIEW = false;
   public boolean DEFAULT_AUTOSCROLL_TO_SOURCE = false;
   @Transient
diff --git a/platform/editor-ui-api/src/com/intellij/openapi/editor/EditorFactory.java b/platform/editor-ui-api/src/com/intellij/openapi/editor/EditorFactory.java
index de3fc9b..730ff5f 100644
--- a/platform/editor-ui-api/src/com/intellij/openapi/editor/EditorFactory.java
+++ b/platform/editor-ui-api/src/com/intellij/openapi/editor/EditorFactory.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +18,6 @@
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.application.Application;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.editor.event.EditorEventMulticaster;
 import com.intellij.openapi.editor.event.EditorFactoryListener;
 import com.intellij.openapi.fileTypes.FileType;
@@ -30,7 +29,7 @@
 /**
  * Provides services for creating document and editor instances.
  */
-public abstract class EditorFactory implements ApplicationComponent {
+public abstract class EditorFactory {
   /**
    * Returns the editor factory instance.
    *
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ContentRootData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ContentRootData.java
index e1b199c..fb54cd2 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ContentRootData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ContentRootData.java
@@ -9,6 +9,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import java.io.File;
+import java.io.Serializable;
 import java.util.Collection;
 import java.util.Collections;
 import java.util.Locale;
@@ -97,7 +98,7 @@
     return buffer.toString();
   }
 
-  public static class SourceRoot {
+  public static class SourceRoot implements Serializable {
     @NotNull
     private final String myPath;
 
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java
index 83a010b..ae3e75f 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemFacadeManager.java
@@ -186,7 +186,7 @@
   @NotNull
   private RemoteExternalSystemFacade doCreateFacade(@NotNull IntegrationKey key, @NotNull Project project,
                                                     @NotNull ExternalSystemCommunicationManager communicationManager) throws Exception {
-    final RemoteExternalSystemFacade facade = communicationManager.acquire(project.getName(), key.getExternalSystemId());
+    final RemoteExternalSystemFacade facade = communicationManager.acquire(key.getExternalProjectConfigPath(), key.getExternalSystemId());
     if (facade == null) {
       throw new IllegalStateException("Can't obtain facade to working with external api at the remote process. Project: " + project);
     }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java
index b8ad4f1..2cc4b2e 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemCommunicationManager.java
@@ -60,6 +60,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.io.File;
 import java.nio.charset.Charset;
 import java.rmi.RemoteException;
 import java.rmi.server.UnicastRemoteObject;
@@ -99,7 +100,7 @@
 
       @Override
       protected RunProfileState getRunProfileState(Object o, String configuration, Executor executor) throws ExecutionException {
-        return createRunProfileState();
+        return createRunProfileState(configuration);
       }
     };
 
@@ -114,14 +115,15 @@
     mySupport.stopAll(wait);
   }
 
-  private RunProfileState createRunProfileState() {
+  private RunProfileState createRunProfileState(final String configuration) {
     return new CommandLineState(null) {
       private SimpleJavaParameters createJavaParameters() throws ExecutionException {
 
         final SimpleJavaParameters params = new SimpleJavaParameters();
         params.setJdk(new SimpleJavaSdkType().createJdk("tmp", SystemProperties.getJavaHome()));
 
-        params.setWorkingDirectory(PathManager.getBinPath());
+        File myWorkingDirectory = new File(configuration);
+        params.setWorkingDirectory(myWorkingDirectory.isDirectory() ? myWorkingDirectory.getPath() : PathManager.getBinPath());
         final List<String> classPath = ContainerUtilRt.newArrayList();
 
         // IDE jars.
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 8560aca..6a3bb5a 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
@@ -8,6 +8,7 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
+import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode;
 import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask;
 import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback;
 import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager;
@@ -18,7 +19,6 @@
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
 import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
 import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
-import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode;
 import com.intellij.openapi.module.ModifiableModuleModel;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.options.ConfigurationException;
@@ -38,7 +38,6 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.packaging.artifacts.ModifiableArtifactModel;
 import com.intellij.projectImport.ProjectImportBuilder;
-import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
@@ -101,7 +100,7 @@
 
   public void prepare(@NotNull WizardContext context) {
     myControl.reset();
-    String pathToUse = context.getProjectFileDirectory();
+    String pathToUse = getFileToImport();
     myControl.setLinkedProjectPath(pathToUse);
     doPrepare(context);
   }
diff --git a/platform/icons/src/modules/generatedFolder.png b/platform/icons/src/modules/generatedFolder.png
new file mode 100644
index 0000000..4432aa0
--- /dev/null
+++ b/platform/icons/src/modules/generatedFolder.png
Binary files differ
diff --git a/platform/icons/src/modules/[email protected] b/platform/icons/src/modules/[email protected]
new file mode 100644
index 0000000..21c42f8
--- /dev/null
+++ b/platform/icons/src/modules/[email protected]
Binary files differ
diff --git a/platform/icons/src/modules/generatedFolder@2x_dark.png b/platform/icons/src/modules/generatedFolder@2x_dark.png
new file mode 100644
index 0000000..012cd11
--- /dev/null
+++ b/platform/icons/src/modules/generatedFolder@2x_dark.png
Binary files differ
diff --git a/platform/icons/src/modules/generatedFolder_dark.png b/platform/icons/src/modules/generatedFolder_dark.png
new file mode 100644
index 0000000..63c85d3
--- /dev/null
+++ b/platform/icons/src/modules/generatedFolder_dark.png
Binary files differ
diff --git a/platform/indexing-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndex.java b/platform/indexing-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndex.java
index f61eceb..ad76a80 100644
--- a/platform/indexing-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndex.java
+++ b/platform/indexing-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndex.java
@@ -50,7 +50,7 @@
     }
   };
 
-  public static final boolean ourSnapshotMappingsEnabled = SystemProperties.getBooleanProperty("idea.index.snapshot.mappings.enabled", false);
+  public static final boolean ourSnapshotMappingsEnabled = SystemProperties.getBooleanProperty("idea.index.snapshot.mappings.enabled", true);
 
   private final DataExternalizer<Integer> myValueExternalizer = new DataExternalizer<Integer>() {
     @Override
diff --git a/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java b/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java
index 289b31e..5d30159 100644
--- a/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java
+++ b/platform/indexing-impl/src/com/intellij/psi/impl/search/PsiSearchHelperImpl.java
@@ -394,7 +394,7 @@
         public Void compute() {
           if (myManager.getProject().isDisposed()) throw new ProcessCanceledException();
           List<PsiFile> psiRoots = file.getViewProvider().getAllFiles();
-          Set<PsiElement> processed = new THashSet<PsiElement>(psiRoots.size() * 2, (float)0.5);
+          Set<PsiFile> processed = new THashSet<PsiFile>(psiRoots.size() * 2, (float)0.5);
           for (final PsiFile psiRoot : psiRoots) {
             checkCanceled(progress);
             assert psiRoot != null : "One of the roots of file " + file + " is null. All roots: " + psiRoots + "; ViewProvider: " +
diff --git a/platform/indexing-impl/src/com/intellij/psi/search/FileTypeIndex.java b/platform/indexing-impl/src/com/intellij/psi/search/FileTypeIndex.java
index c4e6b9f..850fc5a 100644
--- a/platform/indexing-impl/src/com/intellij/psi/search/FileTypeIndex.java
+++ b/platform/indexing-impl/src/com/intellij/psi/search/FileTypeIndex.java
@@ -78,7 +78,7 @@
 
   @Override
   public boolean dependsOnFileContent() {
-    return true;
+    return false;
   }
 
   @Override
diff --git a/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsCustomizable.java b/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsCustomizable.java
index 5c63059..2658334 100644
--- a/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsCustomizable.java
+++ b/platform/lang-api/src/com/intellij/psi/codeStyle/CodeStyleSettingsCustomizable.java
@@ -88,6 +88,8 @@
     SPACE_BEFORE_TYPE_PARAMETER_LIST,
     SPACE_BEFORE_ANOTATION_PARAMETER_LIST,
     SPACE_WITHIN_ANNOTATION_PARENTHESES,
+    SPACE_WITHIN_EMPTY_METHOD_CALL_PARENTHESES,
+    SPACE_WITHIN_EMPTY_METHOD_PARENTHESES
   }
 
   enum BlankLinesOption {
diff --git a/platform/lang-impl/src/com/intellij/application/options/ModuleAwareProjectConfigurable.java b/platform/lang-impl/src/com/intellij/application/options/ModuleAwareProjectConfigurable.java
index 71b7dc7..f7d8ab8 100644
--- a/platform/lang-impl/src/com/intellij/application/options/ModuleAwareProjectConfigurable.java
+++ b/platform/lang-impl/src/com/intellij/application/options/ModuleAwareProjectConfigurable.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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,6 +16,7 @@
 package com.intellij.application.options;
 
 import com.intellij.openapi.module.Module;
+import com.intellij.openapi.options.Configurable;
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.options.SearchableConfigurable;
 import com.intellij.openapi.options.UnnamedConfigurable;
@@ -34,6 +35,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
+import javax.swing.border.EmptyBorder;
 import javax.swing.event.ListSelectionEvent;
 import javax.swing.event.ListSelectionListener;
 import java.awt.*;
@@ -44,7 +46,8 @@
 /**
  * @author yole
  */
-public abstract class ModuleAwareProjectConfigurable<T extends UnnamedConfigurable> implements SearchableConfigurable {
+public abstract class ModuleAwareProjectConfigurable<T extends UnnamedConfigurable> implements SearchableConfigurable,
+                                                                                               Configurable.NoScroll {
   @NotNull
   private final Project myProject;
   private final String myDisplayName;
@@ -113,7 +116,8 @@
     for (Module module : modules) {
       final T configurable = createModuleConfigurable(module);
       myModuleConfigurables.put(module, configurable);
-      final JComponent component = configurable.createComponent();
+      final JComponent component = new JBScrollPane(configurable.createComponent());
+      component.setBorder(new EmptyBorder(0, 0, 0, 0));
       cardPanel.add(component, module.getName());
     }
     moduleList.addListSelectionListener(new ListSelectionListener() {
diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java b/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java
index 6f54db66..22eca01 100644
--- a/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java
+++ b/platform/lang-impl/src/com/intellij/application/options/colors/SimpleEditorPreview.java
@@ -19,7 +19,10 @@
 import com.intellij.application.options.colors.highlighting.HighlightData;
 import com.intellij.application.options.colors.highlighting.HighlightsExtractor;
 import com.intellij.ide.highlighter.HighlighterFactory;
-import com.intellij.openapi.editor.*;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.EditorFactory;
+import com.intellij.openapi.editor.LogicalPosition;
+import com.intellij.openapi.editor.ScrollType;
 import com.intellij.openapi.editor.colors.CodeInsightColors;
 import com.intellij.openapi.editor.colors.EditorColorsScheme;
 import com.intellij.openapi.editor.colors.TextAttributesKey;
@@ -42,10 +45,7 @@
 import java.awt.*;
 import java.awt.event.MouseEvent;
 import java.awt.event.MouseMotionAdapter;
-import java.util.ArrayList;
-import java.util.Collections;
-import java.util.Comparator;
-import java.util.Map;
+import java.util.*;
 import java.util.List;
 
 public class SimpleEditorPreview implements PreviewPanel{
@@ -91,6 +91,10 @@
     }
   }
 
+  public EditorEx getEditor() {
+    return myEditor;
+  }
+
   private void addMouseMotionListener(final Editor view,
                                       final SyntaxHighlighter highlighter,
                                       final HighlightData[] data, final boolean isBackgroundImportant) {
diff --git a/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.form b/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.form
index 2d795f4..3e5c8a0 100644
--- a/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.form
+++ b/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.form
@@ -446,7 +446,7 @@
                       </component>
                     </children>
                   </grid>
-                  <grid id="62a96" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+                  <grid id="62a96" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
                     <margin top="0" left="0" bottom="0" right="0"/>
                     <constraints>
                       <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
@@ -455,17 +455,8 @@
                     <clientProperties>
                       <BorderFactoryClass class="java.lang.String" value="com.intellij.ui.IdeBorderFactory$PlainSmallWithIndent"/>
                     </clientProperties>
-                    <border type="none"  title-resource-bundle="messages/ApplicationBundle" title-key="group.richcopy"/>
+                    <border type="none" title-resource-bundle="messages/ApplicationBundle" title-key="group.richcopy"/>
                     <children>
-                      <component id="8b6fe" class="javax.swing.JCheckBox" binding="myRichCopyStripWhitespaceCheckBox">
-                        <constraints>
-                          <grid row="1" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
-                        </constraints>
-                        <properties>
-                          <selected value="true"/>
-                          <text resource-bundle="messages/ApplicationBundle" key="checkbox.richcopy.strip.whitespace.at.line.start"/>
-                        </properties>
-                      </component>
                       <component id="828ad" class="javax.swing.JLabel">
                         <constraints>
                           <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
diff --git a/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.java b/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.java
index dbedfc0..9e5d855 100644
--- a/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.java
+++ b/platform/lang-impl/src/com/intellij/application/options/editor/EditorOptionsPanel.java
@@ -97,7 +97,6 @@
   private JBLabel      myQuickDocDelayLabel;
   private JTextField   myQuickDocDelayTextField;
   private JComboBox    myRichCopyColorSchemeComboBox;
-  private JCheckBox    myRichCopyStripWhitespaceCheckBox;
 
   private static final String ACTIVE_COLOR_SCHEME = ApplicationBundle.message("combobox.richcopy.color.scheme.active");
 
@@ -224,8 +223,6 @@
     if (!StringUtil.isEmpty(toSelect)) {
       myRichCopyColorSchemeComboBox.setSelectedItem(toSelect);
     }
-
-    myRichCopyStripWhitespaceCheckBox.setSelected(settings.isStripIndents());
   }
 
   public void apply() throws ConfigurationException {
@@ -332,7 +329,6 @@
     if (item instanceof String) {
       settings.setSchemeName(item.toString());
     }
-    settings.setStripIndents(myRichCopyStripWhitespaceCheckBox.isSelected());
 
     restartDaemons();
   }
@@ -454,7 +450,6 @@
 
     RichCopySettings settings = RichCopySettings.getInstance();
     isModified |= !Comparing.equal(settings.getSchemeName(), myRichCopyColorSchemeComboBox.getSelectedItem());
-    isModified |= isModified(myRichCopyStripWhitespaceCheckBox, settings.isStripIndents());
 
     return isModified;
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
index 392e35a..25f0bf2 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
@@ -430,7 +430,8 @@
 
       // the insert handler may have started a live template with completion
       if (CompletionService.getCompletionService().getCurrentCompletion() == null &&
-          !ApplicationManager.getApplication().isUnitTestMode()) {
+          // ...or scheduled another autopopup
+          !CompletionServiceImpl.isPhase(CompletionPhase.CommittingDocuments.class)) {
         CompletionServiceImpl.setCompletionPhase(hasModifiers? new CompletionPhase.InsertedSingleItem(indicator, restorePrefix) : CompletionPhase.NoCompletion);
       }
       checkNotSync(indicator, items);
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java
index c24fb9c..e064ddc 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -601,7 +601,7 @@
     final CharSequence text = myEditor.getDocument().getCharsSequence();
     for (Pair<Integer, ElementPattern<String>> pair : myRestartingPrefixConditions) {
       int start = pair.first;
-      if (caretOffset >= start) {
+      if (caretOffset >= start && start >= 0) {
         final String newPrefix = text.subSequence(start, caretOffset).toString();
         if (pair.second.accepts(newPrefix)) {
           scheduleRestart();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/LookupStringWeigher.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/LookupStringWeigher.java
deleted file mode 100644
index 6f83fd7..0000000
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/LookupStringWeigher.java
+++ /dev/null
@@ -1,33 +0,0 @@
-/*
- * Copyright 2000-2009 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.codeInsight.completion;
-
-import com.intellij.codeInsight.lookup.LookupElement;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * @author peter
- */
-public class LookupStringWeigher extends CompletionWeigher {
-  @Override
-  public String weigh(@NotNull LookupElement element, @NotNull CompletionLocation location) {
-    if (location == null) {
-      return null;
-    }
-    return element.getLookupString().toLowerCase();
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/quickFix/FileReferenceQuickFixProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/quickFix/FileReferenceQuickFixProvider.java
index 5ccc3fe..a2c6954 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/quickFix/FileReferenceQuickFixProvider.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/quickFix/FileReferenceQuickFixProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -28,10 +28,7 @@
 import com.intellij.openapi.module.ModuleUtilCore;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.psi.PsiDirectory;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiFileSystemItem;
-import com.intellij.psi.PsiNamedElement;
+import com.intellij.psi.*;
 import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference;
 import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet;
 import com.intellij.util.IncorrectOperationException;
@@ -51,7 +48,7 @@
   private FileReferenceQuickFixProvider() {}
 
   @NotNull
-  public static List<? extends LocalQuickFix> registerQuickFix(final FileReference reference) {
+  public static List<? extends LocalQuickFix> registerQuickFix(@NotNull FileReference reference) {
     final FileReferenceSet fileReferenceSet = reference.getFileReferenceSet();
     int index = reference.getIndex();
 
@@ -68,16 +65,19 @@
     }
 
     PsiFileSystemItem context = null;
+    PsiElement element = reference.getElement();
+    PsiFile containingFile = element == null ? null : element.getContainingFile();
+
     if(index > 0) {
       context = fileReferenceSet.getReference(index - 1).resolve();
-    } else { // index == 0
+    }
+    else { // index == 0
       final Collection<PsiFileSystemItem> defaultContexts = fileReferenceSet.getDefaultContexts();
       if (defaultContexts.isEmpty()) {
         return Collections.emptyList();
       }
 
-      PsiElement element = reference.getElement();
-      Module module = element != null ? ModuleUtilCore.findModuleForPsiElement(element) : null;
+      Module module = containingFile == null ? null : ModuleUtilCore.findModuleForPsiElement(containingFile);
 
       for (PsiFileSystemItem defaultContext : defaultContexts) {
         if (defaultContext != null) {
@@ -108,7 +108,7 @@
     if (directory == null) return Collections.emptyList();
 
     if (fileReferenceSet.isCaseSensitive()) {
-      final PsiElement psiElement = reference.innerSingleResolve(false);
+      final PsiElement psiElement = containingFile == null ? null : reference.innerSingleResolve(false, containingFile);
 
       if (psiElement != null) {
         final String existingElementName = ((PsiNamedElement)psiElement).getName();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java
index 618e771..861a838 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/CopyHandler.java
@@ -56,15 +56,15 @@
 
     final CodeInsightSettings settings = CodeInsightSettings.getInstance();
 
-    if (file == null || settings.ADD_IMPORTS_ON_PASTE == CodeInsightSettings.NO){
-      if (myOriginalAction != null){
+    if (file == null || settings.ADD_IMPORTS_ON_PASTE == CodeInsightSettings.NO) {
+      if (myOriginalAction != null) {
         myOriginalAction.execute(editor, dataContext);
       }
       return;
     }
 
     final SelectionModel selectionModel = editor.getSelectionModel();
-    if(!selectionModel.hasSelection(true) && !selectionModel.hasBlockSelection()) {
+    if (!selectionModel.hasSelection(true) && !selectionModel.hasBlockSelection()) {
       if (Registry.is(CopyAction.SKIP_COPY_AND_CUT_FOR_EMPTY_SELECTION_KEY)) {
         return;
       }
@@ -89,7 +89,7 @@
     final int[] endOffsets = selectionModel.getBlockSelectionEnds();
 
     List<TextBlockTransferableData> transferableDatas = new ArrayList<TextBlockTransferableData>();
-    for(CopyPastePostProcessor processor: Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) {
+    for (CopyPastePostProcessor processor : Extensions.getExtensions(CopyPastePostProcessor.EP_NAME)) {
       final TextBlockTransferableData e = processor.collectTransferableData(file, editor, startOffsets, endOffsets);
       if (e != null) {
         transferableDatas.add(e);
@@ -98,7 +98,7 @@
 
     String rawText = TextBlockTransferable.convertLineSeparators(selectionModel.getSelectedText(true), "\n", transferableDatas);
     String escapedText = null;
-    for(CopyPastePreProcessor processor: Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
+    for (CopyPastePreProcessor processor : Extensions.getExtensions(CopyPastePreProcessor.EP_NAME)) {
       escapedText = processor.preprocessOnCopy(file, startOffsets, endOffsets, rawText);
       if (escapedText != null) {
         break;
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java
index ef77725..409ea24 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/PasteHandler.java
@@ -229,12 +229,12 @@
       VirtualFile virtualFile = file.getVirtualFile();
       if (!pastedTextContainsWhiteSpacesOnly && (virtualFile == null || !SingleRootFileViewProvider.isTooLargeForIntelligence(virtualFile))) {
         final int indentOptions1 = indentOptions;
-        PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
 
         ApplicationManager.getApplication().runWriteAction(
           new Runnable() {
             @Override
             public void run() {
+              PsiDocumentManager.getInstance(project).doPostponedOperationsAndUnblockDocument(document);
               switch (indentOptions1) {
                 case CodeInsightSettings.INDENT_BLOCK:
                   if (!indented.get()) {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TextBlockTransferable.java b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TextBlockTransferable.java
index 2c62b5b..075f761 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TextBlockTransferable.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/editorActions/TextBlockTransferable.java
@@ -27,37 +27,38 @@
 import java.io.StringReader;
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.Collections;
 import java.util.List;
 
 class TextBlockTransferable implements Transferable {
   private final Collection<TextBlockTransferableData> myExtraData;
   private final RawText myRawText;
   private final String myText;
+  private final DataFlavor[] myTransferDataFlavors;
 
   public TextBlockTransferable(String text, Collection<TextBlockTransferableData> extraData, RawText rawText) {
     myText = text;
     myExtraData = extraData;
     myRawText = rawText;
+
+    List<DataFlavor> dataFlavors = new ArrayList<DataFlavor>();
+    Collections.addAll(dataFlavors, DataFlavor.stringFlavor, DataFlavor.plainTextFlavor);
+    final DataFlavor flavor = RawText.getDataFlavor();
+    if (myRawText != null && flavor != null) {
+      dataFlavors.add(flavor);
+    }
+    for(TextBlockTransferableData data: extraData) {
+      final DataFlavor blockFlavor = data.getFlavor();
+      if (blockFlavor != null) {
+        dataFlavors.add(blockFlavor);
+      }
+    }
+    myTransferDataFlavors = dataFlavors.toArray(new DataFlavor[dataFlavors.size()]);
   }
 
   @Override
   public DataFlavor[] getTransferDataFlavors() {
-    // We don't cache the result to allow certain dataflavors to 'expire'.
-    // This is used e.g. for RTF and HTML flavors to avoid memory leaking.
-    List<DataFlavor> flavors = new ArrayList<DataFlavor>(myExtraData.size() + 3);
-    flavors.add(DataFlavor.stringFlavor);
-    flavors.add(DataFlavor.plainTextFlavor);
-    final DataFlavor flavor = RawText.getDataFlavor();
-    if (myRawText != null && flavor != null) {
-      flavors.add(flavor);
-    }
-    for(TextBlockTransferableData data : myExtraData) {
-      final DataFlavor blockFlavor = data.getFlavor();
-      if (blockFlavor != null) {
-        flavors.add(blockFlavor);
-      }
-    }
-    return flavors.toArray(new DataFlavor[flavors.size()]);
+    return myTransferDataFlavors;
   }
 
   @Override
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/OffsetsElementSignatureProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/OffsetsElementSignatureProvider.java
index cae4fe6..5a9defd 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/OffsetsElementSignatureProvider.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/folding/impl/OffsetsElementSignatureProvider.java
@@ -206,7 +206,7 @@
     buffer.append(ELEMENT_TOKENS_SEPARATOR).append(index);
     PsiFile containingFile = element.getContainingFile();
     if (containingFile != null && containingFile.getViewProvider().getLanguages().size() > 1) {
-      buffer.append(ELEMENT_TOKENS_SEPARATOR).append(element.getLanguage().getID());
+      buffer.append(ELEMENT_TOKENS_SEPARATOR).append(containingFile.getLanguage().getID());
     }
     return buffer.toString();
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/generation/actions/SurroundWithAction.java b/platform/lang-impl/src/com/intellij/codeInsight/generation/actions/SurroundWithAction.java
index 6f0d6df..53a0fe1 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/generation/actions/SurroundWithAction.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/generation/actions/SurroundWithAction.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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,9 +17,9 @@
 package com.intellij.codeInsight.generation.actions;
 
 import com.intellij.codeInsight.CodeInsightActionHandler;
-import com.intellij.codeInsight.template.impl.SurroundWithTemplateHandler;
 import com.intellij.codeInsight.actions.BaseCodeInsightAction;
 import com.intellij.codeInsight.generation.surroundWith.SurroundWithHandler;
+import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
 import com.intellij.lang.Language;
 import com.intellij.lang.LanguageSurrounders;
 import com.intellij.openapi.editor.Editor;
@@ -50,7 +50,7 @@
       return true;
     }
 
-    if (!SurroundWithTemplateHandler.getApplicableTemplates(editor, file, true).isEmpty()) {
+    if (!TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(editor, file, true).isEmpty()) {
       return true;
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/generation/surroundWith/SurroundWithHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/generation/surroundWith/SurroundWithHandler.java
index a461ab9..1fd552d 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/generation/surroundWith/SurroundWithHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/generation/surroundWith/SurroundWithHandler.java
@@ -23,8 +23,8 @@
 import com.intellij.codeInsight.template.CustomLiveTemplate;
 import com.intellij.codeInsight.template.TemplateManager;
 import com.intellij.codeInsight.template.impl.InvokeTemplateAction;
-import com.intellij.codeInsight.template.impl.SurroundWithTemplateHandler;
 import com.intellij.codeInsight.template.impl.TemplateImpl;
+import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
 import com.intellij.codeInsight.template.impl.WrapWithCustomTemplateAction;
 import com.intellij.ide.DataManager;
 import com.intellij.lang.Language;
@@ -247,8 +247,8 @@
       }
     }
 
-    List<CustomLiveTemplate> customTemplates = SurroundWithTemplateHandler.getApplicableCustomTemplates(editor, file);
-    List<TemplateImpl> templates = SurroundWithTemplateHandler.getApplicableTemplates(editor, file, true);
+    List<CustomLiveTemplate> customTemplates = TemplateManagerImpl.listApplicableCustomTemplates(editor, file, true);
+    List<TemplateImpl> templates = TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(editor, file, true);
 
     if (!templates.isEmpty() || !customTemplates.isEmpty()) {
       applicable.add(new Separator("Live templates"));
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightManagerImpl.java
index 1b02e32..8299f59 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightManagerImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/highlighting/HighlightManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -24,7 +24,6 @@
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
 import com.intellij.openapi.actionSystem.ex.AnActionListener;
-import com.intellij.openapi.components.ProjectComponent;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.EditorFactory;
@@ -49,31 +48,12 @@
 import java.awt.*;
 import java.util.*;
 
-public class HighlightManagerImpl extends HighlightManager implements ProjectComponent {
+public class HighlightManagerImpl extends HighlightManager {
   private final Project myProject;
 
   public HighlightManagerImpl(Project project) {
     myProject = project;
-  }
-
-  @Override
-  @NotNull
-  public String getComponentName() {
-    return "HighlightManager";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
-  public void projectOpened() {
-    AnActionListener anActionListener = new MyAnActionListener();
-    ActionManagerEx.getInstanceEx().addAnActionListener(anActionListener, myProject);
+    ActionManagerEx.getInstanceEx().addAnActionListener(new MyAnActionListener(), myProject);
 
     DocumentListener documentListener = new DocumentAdapter() {
       @Override
@@ -102,10 +82,6 @@
     EditorFactory.getInstance().getEventMulticaster().addDocumentListener(documentListener, myProject);
   }
 
-  @Override
-  public void projectClosed() {
-  }
-
   @Nullable
   public Map<RangeHighlighter, HighlightInfo> getHighlightInfoMap(@NotNull Editor editor, boolean toCreate) {
     if (editor instanceof EditorWindow) return getHighlightInfoMap(((EditorWindow)editor).getDelegate(), toCreate);
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupArranger.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupArranger.java
index faf6b6a..9f02c20 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupArranger.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/LookupArranger.java
@@ -19,6 +19,7 @@
 import com.intellij.codeInsight.completion.PrefixMatcher;
 import com.intellij.codeInsight.completion.impl.CompletionServiceImpl;
 import com.intellij.codeInsight.lookup.impl.LookupImpl;
+import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Pair;
 import org.jetbrains.annotations.NotNull;
 
@@ -86,7 +87,7 @@
 
   protected static boolean isPrefixItem(Lookup lookup, LookupElement item, final boolean exactly) {
     final String pattern = lookup.itemPattern(item);
-    if (pattern.equals(item.getLookupString())) {
+    if (Comparing.strEqual(pattern, item.getLookupString(), item.isCaseSensitive())) {
       return true;
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
index 0402bba..8df9537 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupImpl.java
@@ -16,7 +16,6 @@
 
 package com.intellij.codeInsight.lookup.impl;
 
-import com.intellij.codeInsight.CodeInsightBundle;
 import com.intellij.codeInsight.FileModificationService;
 import com.intellij.codeInsight.completion.CodeCompletionFeatures;
 import com.intellij.codeInsight.completion.CompletionLookupArranger;
@@ -27,25 +26,19 @@
 import com.intellij.codeInsight.hint.HintManagerImpl;
 import com.intellij.codeInsight.lookup.*;
 import com.intellij.featureStatistics.FeatureUsageTracker;
-import com.intellij.icons.AllIcons;
-import com.intellij.ide.DataManager;
 import com.intellij.ide.IdeEventQueue;
 import com.intellij.ide.ui.UISettings;
 import com.intellij.lang.LangBundle;
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.event.*;
 import com.intellij.openapi.editor.event.DocumentAdapter;
-import com.intellij.openapi.keymap.KeymapUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.JBPopup;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
-import com.intellij.openapi.util.ActionCallback;
 import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.Pair;
@@ -57,20 +50,12 @@
 import com.intellij.psi.impl.DebugUtil;
 import com.intellij.ui.*;
 import com.intellij.ui.awt.RelativePoint;
-import com.intellij.ui.components.JBLayeredPane;
 import com.intellij.ui.components.JBList;
-import com.intellij.ui.components.JBScrollPane;
-import com.intellij.ui.plaf.beg.BegPopupMenuBorder;
 import com.intellij.ui.popup.AbstractPopup;
-import com.intellij.util.Alarm;
 import com.intellij.util.CollectConsumer;
-import com.intellij.util.PlatformIcons;
 import com.intellij.util.containers.ConcurrentHashMap;
 import com.intellij.util.containers.ConcurrentWeakHashMap;
 import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.ui.AbstractLayoutManager;
-import com.intellij.util.ui.AsyncProcessIcon;
-import com.intellij.util.ui.ButtonlessScrollBarUI;
 import com.intellij.util.ui.update.Activatable;
 import com.intellij.util.ui.update.UiNotifyConnector;
 import org.jetbrains.annotations.NotNull;
@@ -78,13 +63,11 @@
 import org.jetbrains.annotations.TestOnly;
 
 import javax.swing.*;
-import javax.swing.border.Border;
-import javax.swing.border.EmptyBorder;
-import javax.swing.border.LineBorder;
 import javax.swing.event.ListSelectionEvent;
 import javax.swing.event.ListSelectionListener;
 import java.awt.*;
-import java.awt.event.*;
+import java.awt.event.KeyEvent;
+import java.awt.event.MouseEvent;
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.List;
@@ -120,8 +103,7 @@
       return myExtender;
     }
   };
-  private final LookupCellRenderer myCellRenderer;
-  private Boolean myPositionedAbove = null;
+  final LookupCellRenderer myCellRenderer;
 
   private final List<LookupListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
 
@@ -131,12 +113,10 @@
   private boolean myHidden = false;
   private boolean mySelectionTouched;
   private FocusDegree myFocusDegree = FocusDegree.FOCUSED;
-  private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress");
-  private final JPanel myIconPanel = new JPanel(new BorderLayout());
   private volatile boolean myCalculating;
   private final Advertiser myAdComponent;
   private volatile String myAdText;
-  private volatile int myLookupTextWidth = 50;
+  volatile int myLookupTextWidth = 50;
   private boolean myChangeGuard;
   private volatile LookupArranger myArranger;
   private LookupArranger myPresentableArranger;
@@ -144,18 +124,11 @@
     ContainerUtil.<LookupElement>identityStrategy());
   private final Map<LookupElement, Font> myCustomFonts = new ConcurrentWeakHashMap<LookupElement, Font>(
     ContainerUtil.<LookupElement>identityStrategy());
-  private LookupHint myElementHint = null;
-  private final Alarm myHintAlarm = new Alarm();
-  private final JLabel mySortingLabel = new JLabel();
-  private final JScrollPane myScrollPane;
-  final LookupLayeredPane myLayeredPane = new LookupLayeredPane();
-  private final JButton myScrollBarIncreaseButton;
   private boolean myStartCompletionWhenNothingMatches;
-  private boolean myResizePending;
-  private int myMaximumHeight = Integer.MAX_VALUE;
+  boolean myResizePending;
   private boolean myFinishing;
-  private boolean myUpdating;
-  private final ModalityState myModalityState;
+  boolean myUpdating;
+  private LookupUi myUi;
 
   public LookupImpl(Project project, Editor editor, @NotNull LookupArranger arranger) {
     super(new JPanel(new BorderLayout()));
@@ -169,7 +142,6 @@
     myArranger = arranger;
     myPresentableArranger = arranger;
 
-    myIconPanel.setVisible(false);
     myCellRenderer = new LookupCellRenderer(this);
     myList.setCellRenderer(myCellRenderer);
 
@@ -181,36 +153,7 @@
 
     myList.getExpandableItemsHandler();
 
-    myScrollBarIncreaseButton = new JButton();
-    myScrollBarIncreaseButton.setFocusable(false);
-    myScrollBarIncreaseButton.setRequestFocusEnabled(false);
-
-    myScrollPane = new JBScrollPane(myList);
-    myScrollPane.setViewportBorder(new EmptyBorder(0, 0, 0, 0));
-    myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
-    myScrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(13, -1));
-    myScrollPane.getVerticalScrollBar().setUI(new ButtonlessScrollBarUI() {
-      @Override
-      protected JButton createIncreaseButton(int orientation) {
-        return myScrollBarIncreaseButton;
-      }
-    });
-    getComponent().add(myLayeredPane, BorderLayout.CENTER);
-
-    //IDEA-82111
-    fixMouseCheaters();
-
-    myLayeredPane.mainPanel.add(myScrollPane, BorderLayout.CENTER);
-    myScrollPane.setBorder(null);
-
     myAdComponent = new Advertiser();
-    JComponent adComponent = myAdComponent.getAdComponent();
-    adComponent.setBorder(new EmptyBorder(0, 1, 1, 2 + AllIcons.Ide.LookupRelevance.getIconWidth()));
-    myLayeredPane.mainPanel.add(adComponent, BorderLayout.SOUTH);
-    getComponent().setBorder(new BegPopupMenuBorder());
-
-    myIconPanel.setBackground(Color.LIGHT_GRAY);
-    myIconPanel.add(myProcessIcon);
 
     myOffsets = new LookupOffsets(editor);
 
@@ -218,14 +161,7 @@
     addEmptyItem(model);
     updateListHeight(model);
 
-
     addListeners();
-
-    mySortingLabel.setBorder(new LineBorder(new JBColor(Color.LIGHT_GRAY, JBColor.background())));
-    mySortingLabel.setOpaque(true);
-    new ChangeLookupSorting().installOn(mySortingLabel);
-    updateSorting();
-    myModalityState = ModalityState.stateForComponent(getComponent());
   }
 
   private CollectionListModel<LookupElement> getListModel() {
@@ -233,34 +169,6 @@
     return (CollectionListModel<LookupElement>)myList.getModel();
   }
 
-  //Yes, it's possible to move focus to the hint. It's inconvenient, it doesn't make sense, but it's possible.
-  // This fix is for those jerks
-  private void fixMouseCheaters() {
-    getComponent().addFocusListener(new FocusAdapter() {
-      @Override
-      public void focusGained(FocusEvent e) {
-        final ActionCallback done = IdeFocusManager.getInstance(myProject).requestFocus(myEditor.getContentComponent(), true);
-        IdeFocusManager.getInstance(myProject).typeAheadUntil(done);
-        new Alarm(LookupImpl.this).addRequest(new Runnable() {
-          @Override
-          public void run() {
-            if (!done.isDone()) {
-              done.setDone();
-            }
-          }
-        }, 300, myModalityState);
-      }
-    });
-  }
-
-  void updateSorting() {
-    final boolean lexi = UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
-    mySortingLabel.setIcon(lexi ? AllIcons.Ide.LookupAlphanumeric : AllIcons.Ide.LookupRelevance);
-    mySortingLabel.setToolTipText(lexi ? "Click to sort variants by relevance" : "Click to sort variants alphabetically");
-
-    resort(false);
-  }
-
   public void setArranger(LookupArranger arranger) {
     myArranger = arranger;
   }
@@ -284,22 +192,8 @@
 
   public void setCalculating(final boolean calculating) {
     myCalculating = calculating;
-    Runnable setVisible = new Runnable() {
-      @Override
-      public void run() {
-        myIconPanel.setVisible(myCalculating);
-      }
-    };
-    if (myCalculating) {
-      new Alarm(this).addRequest(setVisible, 100, myModalityState);
-    } else {
-      setVisible.run();
-    }
-
-    if (calculating) {
-      myProcessIcon.resume();
-    } else {
-      myProcessIcon.suspend();
+    if (myUi != null) {
+      myUi.setCalculating(calculating);
     }
   }
 
@@ -564,50 +458,6 @@
     return myMatchers.get(item);
   }
 
-  // in layered pane coordinate system.
-  private Rectangle calculatePosition() {
-    Dimension dim = getComponent().getPreferredSize();
-    int lookupStart = getLookupStart();
-    if (lookupStart < 0 || lookupStart > myEditor.getDocument().getTextLength()) {
-      LOG.error(lookupStart + "; offset=" + myEditor.getCaretModel().getOffset() + "; element=" +
-                getPsiElement());
-    }
-
-    LogicalPosition pos = myEditor.offsetToLogicalPosition(lookupStart);
-    Point location = myEditor.logicalPositionToXY(pos);
-    location.y += myEditor.getLineHeight();
-    location.x -= myCellRenderer.getIconIndent() + getComponent().getInsets().left;
-
-    SwingUtilities.convertPointToScreen(location, myEditor.getContentComponent());
-    final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(location);
-
-    if (!isPositionedAboveCaret()) {
-      int shiftLow = screenRectangle.height - (location.y + dim.height);
-      myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height && location.y >= dim.height;
-    }
-    if (isPositionedAboveCaret()) {
-      location.y -= dim.height + myEditor.getLineHeight();
-      if (pos.line == 0) {
-        location.y += 1;
-        //otherwise the lookup won't intersect with the editor and every editor's resize (e.g. after typing in console) will close the lookup
-      }
-    }
-
-    if (!screenRectangle.contains(location)) {
-      location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
-    }
-
-    final JRootPane rootPane = myEditor.getComponent().getRootPane();
-    if (rootPane == null) {
-      LOG.error(myEditor.isDisposed() + "; shown=" + myShown + "; disposed=" + myDisposed + "; editorShowing=" + myEditor.getContentComponent().isShowing());
-    }
-    Rectangle candidate = new Rectangle(location, dim);
-    ScreenUtil.cropRectangleToFitTheScreen(candidate);
-
-    SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
-    return new Rectangle(location.x, location.y, dim.width, candidate.height);
-  }
-
   public void finishLookup(final char completionChar) {
     finishLookup(completionChar, (LookupElement)myList.getSelectedValue());
   }
@@ -794,7 +644,7 @@
       return false;
     }
     if (isVisible()) {
-      updateLookupLocation();
+      HintManagerImpl.updateLocation(this, myEditor, myUi.calculatePosition().getLocation());
     }
     checkValid();
     return true;
@@ -835,12 +685,9 @@
 
     myAdComponent.showRandomText();
 
-    getComponent().setBorder(null);
-    updateScrollbarVisibility();
-
-    Rectangle bounds = calculatePosition();
-    myMaximumHeight = bounds.height;
-    Point p = bounds.getLocation();
+    myUi = new LookupUi(this, myAdComponent, myList, myProject);
+    myUi.setCalculating(myCalculating);
+    Point p = myUi.calculatePosition().getLocation();
     HintManagerImpl.getInstanceImpl().showEditorHint(this, myEditor, p, HintManager.HIDE_BY_ESCAPE | HintManager.UPDATE_BY_SCROLLING, 0, false,
                                                      HintManagerImpl.createHintHint(myEditor, p, this, HintManager.UNDER).setAwtTooltip(false));
 
@@ -923,8 +770,6 @@
 
       @Override
       public void valueChanged(ListSelectionEvent e){
-        myHintAlarm.cancelAllRequests();
-
         final LookupElement item = getCurrentItem();
         if (oldItem != item && !myList.isEmpty()) { // do not update on temporary model wipe
           fireCurrentItemChanged(item);
@@ -933,9 +778,6 @@
           }
           oldItem = item;
         }
-        if (item != null) {
-          updateHint(item);
-        }
       }
     });
 
@@ -956,53 +798,6 @@
         return true;
       }
     }.installOn(myList);
-
-    final Alarm alarm = new Alarm(this);
-    myScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
-      @Override
-      public void adjustmentValueChanged(AdjustmentEvent e) {
-        if (!myShown || myUpdating || myDisposed) return;
-        alarm.addRequest(new Runnable() {
-          @Override
-          public void run() {
-            refreshUi(false, false);
-          }
-        }, 300, myModalityState);
-      }
-    });
-  }
-
-  private void updateHint(@NotNull final LookupElement item) {
-    checkValid();
-    if (myElementHint != null) {
-      myLayeredPane.remove(myElementHint);
-      myElementHint = null;
-      final JRootPane rootPane = getComponent().getRootPane();
-      if (rootPane != null) {
-        rootPane.revalidate();
-        rootPane.repaint();
-      }
-    }
-    if (!isFocused()) {
-      return;
-    }
-
-    final Collection<LookupElementAction> actions = getActionsFor(item);
-    if (!actions.isEmpty()) {
-      myHintAlarm.addRequest(new Runnable() {
-        @Override
-        public void run() {
-          assert !myDisposed;
-          if (!ShowHideIntentionIconLookupAction.shouldShowLookupHint() ||
-              ((CompletionExtender)myList.getExpandableItemsHandler()).isShowing()) {
-            return;
-          }
-          myElementHint = new LookupHint();
-          myLayeredPane.add(myElementHint, 20, 0);
-          myLayeredPane.layoutHint();
-        }
-      }, 500, myModalityState);
-    }
   }
 
   @Override
@@ -1075,7 +870,7 @@
     }
   }
 
-  private void fireCurrentItemChanged(LookupElement item){
+  void fireCurrentItemChanged(LookupElement item){
     if (!myListeners.isEmpty()){
       LookupEvent event = new LookupEvent(this, item, (char)0);
       for (LookupListener listener : myListeners) {
@@ -1208,7 +1003,7 @@
 
   @Override
   public boolean isPositionedAboveCaret(){
-    return myPositionedAbove != null && myPositionedAbove.booleanValue();
+    return myUi != null && myUi.isPositionedAboveCaret();
   }
 
   @Override
@@ -1279,8 +1074,6 @@
     }
 
     myOffsets.disposeMarkers();
-    Disposer.dispose(myProcessIcon);
-    Disposer.dispose(myHintAlarm);
     myDisposed = true;
     disposeTrace = DebugUtil.currentStackTrace() + "\n============";
     //noinspection AssignmentToStaticFieldFromInstanceMethod
@@ -1291,59 +1084,19 @@
     assert !myUpdating;
     myUpdating = true;
     try {
-      doRefreshUi(mayCheckReused, onExplicitAction);
+      final boolean reused = mayCheckReused && checkReused();
+      boolean selectionVisible = isSelectionVisible();
+      boolean itemsChanged = updateList(onExplicitAction, reused);
+      if (isVisible()) {
+        LOG.assertTrue(!ApplicationManager.getApplication().isUnitTestMode());
+        myUi.refreshUi(selectionVisible, itemsChanged, reused, onExplicitAction);
+      }
     }
     finally {
       myUpdating = false;
     }
   }
 
-  private void doRefreshUi(boolean mayCheckReused, boolean onExplicitAction) {
-    final boolean reused = mayCheckReused && checkReused();
-
-    boolean selectionVisible = isSelectionVisible();
-
-    boolean itemsChanged = updateList(onExplicitAction, reused);
-
-    if (isVisible()) {
-      LOG.assertTrue(!ApplicationManager.getApplication().isUnitTestMode());
-
-      if (myEditor.getComponent().getRootPane() == null) {
-        return;
-      }
-
-      updateScrollbarVisibility();
-
-      if (myResizePending || itemsChanged) {
-        myMaximumHeight = Integer.MAX_VALUE;
-      }
-      Rectangle rectangle = calculatePosition();
-      myMaximumHeight = rectangle.height;
-
-      if (myResizePending || itemsChanged) {
-        myResizePending = false;
-        pack();
-      }
-      HintManagerImpl.updateLocation(this, myEditor, rectangle.getLocation());
-
-      if (reused || selectionVisible || onExplicitAction) {
-        ensureSelectionVisible(false);
-      }
-    }
-  }
-
-  private void updateLookupLocation() {
-    Rectangle rectangle = calculatePosition();
-    myMaximumHeight = rectangle.height;
-    HintManagerImpl.updateLocation(this, myEditor, rectangle.getLocation());
-  }
-
-  private void updateScrollbarVisibility() {
-    boolean showSorting = isCompletion() && getListModel().getSize() >= 3;
-    mySortingLabel.setVisible(showSorting);
-    myScrollPane.setVerticalScrollBarPolicy(showSorting ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
-  }
-
   public void markReused() {
     myAdComponent.clearAdvertisements();
     synchronized (myList) {
@@ -1368,7 +1121,7 @@
     if (ApplicationManager.getApplication().isDispatchThread()) {
       runnable.run();
     } else {
-      ApplicationManager.getApplication().invokeLater(runnable, myModalityState);
+      ApplicationManager.getApplication().invokeLater(runnable);
     }
   }
 
@@ -1406,155 +1159,12 @@
     return true;
   }
 
-  private class LookupLayeredPane extends JBLayeredPane {
-    final JPanel mainPanel = new JPanel(new BorderLayout());
-
-    private LookupLayeredPane() {
-      add(mainPanel, 0, 0);
-      add(myIconPanel, 42, 0);
-      add(mySortingLabel, 10, 0);
-
-      setLayout(new AbstractLayoutManager() {
-        @Override
-        public Dimension preferredLayoutSize(@Nullable Container parent) {
-          int maxCellWidth = myLookupTextWidth + myCellRenderer.getIconIndent();
-          int scrollBarWidth = myScrollPane.getPreferredSize().width - myScrollPane.getViewport().getPreferredSize().width;
-          int listWidth = Math.min(scrollBarWidth + maxCellWidth, UISettings.getInstance().MAX_LOOKUP_WIDTH2);
-
-          Dimension adSize = myAdComponent.getAdComponent().getPreferredSize();
-
-          int panelHeight = myList.getPreferredScrollableViewportSize().height + adSize.height;
-          if (getListModel().getSize() > myList.getVisibleRowCount() && myList.getVisibleRowCount() >= 5) {
-            panelHeight -= myList.getFixedCellHeight() / 2;
-          }
-          return new Dimension(Math.max(listWidth, adSize.width), Math.min(panelHeight, myMaximumHeight));
-        }
-
-        @Override
-        public void layoutContainer(Container parent) {
-          Dimension size = getSize();
-          mainPanel.setSize(size);
-          mainPanel.validate();
-
-          if (!myResizePending) {
-            Dimension preferredSize = preferredLayoutSize(null);
-            if (preferredSize.width != size.width) {
-              UISettings.getInstance().MAX_LOOKUP_WIDTH2 = Math.max(500, size.width);
-            }
-
-            int listHeight = myList.getLastVisibleIndex() - myList.getFirstVisibleIndex() + 1;
-            if (listHeight != getListModel().getSize() && listHeight != myList.getVisibleRowCount() && preferredSize.height != size.height) {
-              UISettings.getInstance().MAX_LOOKUP_LIST_HEIGHT = Math.max(5, listHeight);
-            }
-          }
-
-          myList.setFixedCellWidth(myScrollPane.getViewport().getWidth());
-          layoutStatusIcons();
-          layoutHint();
-        }
-      });
-    }
-
-    private void layoutStatusIcons() {
-      int adHeight = myAdComponent.getAdComponent().getPreferredSize().height;
-      Dimension buttonSize = adHeight > 0 || !mySortingLabel.isVisible() ? new Dimension(0, 0) : new Dimension(
-        AllIcons.Ide.LookupRelevance.getIconWidth(), AllIcons.Ide.LookupRelevance.getIconHeight());
-      myScrollBarIncreaseButton.setPreferredSize(buttonSize);
-      myScrollBarIncreaseButton.setMinimumSize(buttonSize);
-      myScrollBarIncreaseButton.setMaximumSize(buttonSize);
-      JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
-      scrollBar.revalidate();
-      scrollBar.repaint();
-
-      final Dimension iconSize = myProcessIcon.getPreferredSize();
-      myIconPanel.setBounds(getWidth() - iconSize.width - (scrollBar.isVisible() ? scrollBar.getWidth() : 0), 0, iconSize.width, iconSize.height);
-
-      final Dimension sortSize = mySortingLabel.getPreferredSize();
-      final Point sbLocation = SwingUtilities.convertPoint(scrollBar, 0, 0, myLayeredPane);
-
-      final int sortHeight = Math.max(adHeight, mySortingLabel.getPreferredSize().height);
-      mySortingLabel.setBounds(sbLocation.x, getHeight() - sortHeight, sortSize.width, sortHeight);
-    }
-
-    void layoutHint() {
-      if (myElementHint != null && getCurrentItem() != null) {
-        final Rectangle bounds = getCurrentItemBounds();
-        myElementHint.setSize(myElementHint.getPreferredSize());
-
-        JScrollBar sb = myScrollPane.getVerticalScrollBar();
-        int x = bounds.x + bounds.width - myElementHint.getWidth() + (sb.isVisible() ? sb.getWidth() : 0);
-        x = Math.min(x, getWidth() - myElementHint.getWidth());
-        myElementHint.setLocation(new Point(x, bounds.y));
-      }
-    }
-  }
-
-  private class LookupHint extends JLabel {
-    private final Border INACTIVE_BORDER = BorderFactory.createEmptyBorder(2, 2, 2, 2);
-    private final Border ACTIVE_BORDER = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK, 1), BorderFactory.createEmptyBorder(1, 1, 1, 1));
-    private LookupHint() {
-      setOpaque(false);
-      setBorder(INACTIVE_BORDER);
-      setIcon(AllIcons.Actions.IntentionBulb);
-      String acceleratorsText = KeymapUtil.getFirstKeyboardShortcutText(
-              ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS));
-      if (acceleratorsText.length() > 0) {
-        setToolTipText(CodeInsightBundle.message("lightbulb.tooltip", acceleratorsText));
-      }
-
-      addMouseListener(new MouseAdapter() {
-        @Override
-        public void mouseEntered(MouseEvent e) {
-          setBorder(ACTIVE_BORDER);
-        }
-
-        @Override
-        public void mouseExited(MouseEvent e) {
-          setBorder(INACTIVE_BORDER);
-        }
-        @Override
-        public void mousePressed(MouseEvent e) {
-          if (!e.isPopupTrigger() && e.getButton() == MouseEvent.BUTTON1) {
-            showElementActions();
-          }
-        }
-      });
-    }
-  }
-
   public Map<LookupElement,StringBuilder> getRelevanceStrings() {
     synchronized (myList) {
       return myPresentableArranger.getRelevanceStrings();
     }
   }
 
-  private class ChangeLookupSorting extends ClickListener {
-
-    @Override
-    public boolean onClick(@NotNull MouseEvent e, int clickCount) {
-      DataContext context = DataManager.getInstance().getDataContext(mySortingLabel);
-      DefaultActionGroup group = new DefaultActionGroup();
-      group.add(createSortingAction(true));
-      group.add(createSortingAction(false));
-      JBPopupFactory.getInstance().createActionGroupPopup("Change sorting", group, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false).showInBestPositionFor(
-        context);
-      return true;
-    }
-
-    private AnAction createSortingAction(boolean checked) {
-      boolean currentSetting = UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
-      final boolean newSetting = checked ? currentSetting : !currentSetting;
-      return new AnAction(newSetting ? "Sort lexicographically" : "Sort by relevance", null, checked ? PlatformIcons.CHECK_ICON : null) {
-        @Override
-        public void actionPerformed(AnActionEvent e) {
-          FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CHANGE_SORTING);
-          UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = newSetting;
-          updateSorting();
-        }
-      };
-    }
-  }
-
   public enum FocusDegree { FOCUSED, SEMI_FOCUSED, UNFOCUSED }
 
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java
new file mode 100644
index 0000000..2851eb3
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/LookupUi.java
@@ -0,0 +1,466 @@
+/*
+ * Copyright 2000-2014 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.codeInsight.lookup.impl;
+
+import com.intellij.codeInsight.CodeInsightBundle;
+import com.intellij.codeInsight.completion.CodeCompletionFeatures;
+import com.intellij.codeInsight.completion.ShowHideIntentionIconLookupAction;
+import com.intellij.codeInsight.hint.HintManagerImpl;
+import com.intellij.codeInsight.lookup.LookupElement;
+import com.intellij.codeInsight.lookup.LookupElementAction;
+import com.intellij.featureStatistics.FeatureUsageTracker;
+import com.intellij.icons.AllIcons;
+import com.intellij.ide.DataManager;
+import com.intellij.ide.ui.UISettings;
+import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.application.ModalityState;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.LogicalPosition;
+import com.intellij.openapi.keymap.KeymapUtil;
+import com.intellij.openapi.project.DumbAwareAction;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.ui.popup.JBPopupFactory;
+import com.intellij.openapi.util.ActionCallback;
+import com.intellij.openapi.util.Disposer;
+import com.intellij.openapi.wm.IdeFocusManager;
+import com.intellij.ui.ClickListener;
+import com.intellij.ui.JBColor;
+import com.intellij.ui.ScreenUtil;
+import com.intellij.ui.components.JBLayeredPane;
+import com.intellij.ui.components.JBList;
+import com.intellij.ui.components.JBScrollPane;
+import com.intellij.util.Alarm;
+import com.intellij.util.PlatformIcons;
+import com.intellij.util.ui.AbstractLayoutManager;
+import com.intellij.util.ui.AsyncProcessIcon;
+import com.intellij.util.ui.ButtonlessScrollBarUI;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+import javax.swing.border.Border;
+import javax.swing.border.EmptyBorder;
+import javax.swing.border.LineBorder;
+import javax.swing.event.ListSelectionEvent;
+import javax.swing.event.ListSelectionListener;
+import java.awt.*;
+import java.awt.event.*;
+import java.util.Collection;
+
+/**
+ * @author peter
+ */
+class LookupUi {
+  private static final Logger LOG = Logger.getInstance("#com.intellij.codeInsight.lookup.impl.LookupUi");
+  private final LookupImpl myLookup;
+  private final Advertiser myAdvertiser;
+  private final JBList myList;
+  private final Project myProject;
+  private final ModalityState myModalityState;
+  private final Alarm myHintAlarm = new Alarm();
+  private final JLabel mySortingLabel = new JLabel();
+  private final JScrollPane myScrollPane;
+  private final JButton myScrollBarIncreaseButton;
+  private final AsyncProcessIcon myProcessIcon = new AsyncProcessIcon("Completion progress");
+  private final JPanel myIconPanel = new JPanel(new BorderLayout());
+  private final LookupLayeredPane myLayeredPane = new LookupLayeredPane();
+
+  private LookupHint myElementHint = null;
+  private int myMaximumHeight = Integer.MAX_VALUE;
+  private Boolean myPositionedAbove = null;
+
+  LookupUi(LookupImpl lookup, Advertiser advertiser, JBList list, Project project) {
+    myLookup = lookup;
+    myAdvertiser = advertiser;
+    myList = list;
+    myProject = project;
+
+    myIconPanel.setVisible(false);
+    myIconPanel.setBackground(Color.LIGHT_GRAY);
+    myIconPanel.add(myProcessIcon);
+
+    JComponent adComponent = advertiser.getAdComponent();
+    adComponent.setBorder(new EmptyBorder(0, 1, 1, 2 + AllIcons.Ide.LookupRelevance.getIconWidth()));
+    myLayeredPane.mainPanel.add(adComponent, BorderLayout.SOUTH);
+
+    myScrollBarIncreaseButton = new JButton();
+    myScrollBarIncreaseButton.setFocusable(false);
+    myScrollBarIncreaseButton.setRequestFocusEnabled(false);
+
+    myScrollPane = new JBScrollPane(lookup.getList());
+    myScrollPane.setViewportBorder(new EmptyBorder(0, 0, 0, 0));
+    myScrollPane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
+    myScrollPane.getVerticalScrollBar().setPreferredSize(new Dimension(13, -1));
+    myScrollPane.getVerticalScrollBar().setUI(new ButtonlessScrollBarUI() {
+      @Override
+      protected JButton createIncreaseButton(int orientation) {
+        return myScrollBarIncreaseButton;
+      }
+    });
+    lookup.getComponent().add(myLayeredPane, BorderLayout.CENTER);
+
+    //IDEA-82111
+    fixMouseCheaters();
+
+    myLayeredPane.mainPanel.add(myScrollPane, BorderLayout.CENTER);
+    myScrollPane.setBorder(null);
+
+    mySortingLabel.setBorder(new LineBorder(new JBColor(Color.LIGHT_GRAY, JBColor.background())));
+    mySortingLabel.setOpaque(true);
+    new ChangeLookupSorting().installOn(mySortingLabel);
+    updateSorting();
+    myModalityState = ModalityState.stateForComponent(myLookup.getComponent());
+
+    addListeners();
+
+    updateScrollbarVisibility();
+
+    Disposer.register(lookup, myProcessIcon);
+    Disposer.register(lookup, myHintAlarm);
+  }
+
+  private void addListeners() {
+    myList.addListSelectionListener(new ListSelectionListener() {
+      @Override
+      public void valueChanged(ListSelectionEvent e) {
+        myHintAlarm.cancelAllRequests();
+
+        final LookupElement item = myLookup.getCurrentItem();
+        if (item != null) {
+          updateHint(item);
+        }
+      }
+    });
+
+    final Alarm alarm = new Alarm(myLookup);
+    myScrollPane.getVerticalScrollBar().addAdjustmentListener(new AdjustmentListener() {
+      @Override
+      public void adjustmentValueChanged(AdjustmentEvent e) {
+        if (myLookup.myUpdating || myLookup.isLookupDisposed()) return;
+        alarm.addRequest(new Runnable() {
+          @Override
+          public void run() {
+            myLookup.refreshUi(false, false);
+          }
+        }, 300, myModalityState);
+      }
+    });
+  }
+
+  private void updateScrollbarVisibility() {
+    boolean showSorting = myLookup.isCompletion() && myList.getModel().getSize() >= 3;
+    mySortingLabel.setVisible(showSorting);
+    myScrollPane.setVerticalScrollBarPolicy(showSorting ? ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS : ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED);
+  }
+
+  private void updateHint(@NotNull final LookupElement item) {
+    myLookup.checkValid();
+    if (myElementHint != null) {
+      myLayeredPane.remove(myElementHint);
+      myElementHint = null;
+      final JRootPane rootPane = myLookup.getComponent().getRootPane();
+      if (rootPane != null) {
+        rootPane.revalidate();
+        rootPane.repaint();
+      }
+    }
+    if (!myLookup.isFocused()) {
+      return;
+    }
+
+    final Collection<LookupElementAction> actions = myLookup.getActionsFor(item);
+    if (!actions.isEmpty()) {
+      myHintAlarm.addRequest(new Runnable() {
+        @Override
+        public void run() {
+          if (!ShowHideIntentionIconLookupAction.shouldShowLookupHint() ||
+              ((CompletionExtender)myList.getExpandableItemsHandler()).isShowing()) {
+            return;
+          }
+          myElementHint = new LookupHint();
+          myLayeredPane.add(myElementHint, 20, 0);
+          myLayeredPane.layoutHint();
+        }
+      }, 500, myModalityState);
+    }
+  }
+
+  //Yes, it's possible to move focus to the hint. It's inconvenient, it doesn't make sense, but it's possible.
+  // This fix is for those jerks
+  private void fixMouseCheaters() {
+    myLookup.getComponent().addFocusListener(new FocusAdapter() {
+      @Override
+      public void focusGained(FocusEvent e) {
+        final ActionCallback done = IdeFocusManager.getInstance(myProject).requestFocus(myLookup.getEditor().getContentComponent(), true);
+        IdeFocusManager.getInstance(myProject).typeAheadUntil(done);
+        new Alarm(myLookup).addRequest(new Runnable() {
+          @Override
+          public void run() {
+            if (!done.isDone()) {
+              done.setDone();
+            }
+          }
+        }, 300, myModalityState);
+      }
+    });
+  }
+
+  void setCalculating(final boolean calculating) {
+    Runnable setVisible = new Runnable() {
+      @Override
+      public void run() {
+        myIconPanel.setVisible(myLookup.isCalculating());
+      }
+    };
+    if (myLookup.isCalculating()) {
+      new Alarm(myLookup).addRequest(setVisible, 100, myModalityState);
+    } else {
+      setVisible.run();
+    }
+
+    if (calculating) {
+      myProcessIcon.resume();
+    } else {
+      myProcessIcon.suspend();
+    }
+  }
+
+  private void updateSorting() {
+    final boolean lexi = UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
+    mySortingLabel.setIcon(lexi ? AllIcons.Ide.LookupAlphanumeric : AllIcons.Ide.LookupRelevance);
+    mySortingLabel.setToolTipText(lexi ? "Click to sort variants by relevance" : "Click to sort variants alphabetically");
+
+    myLookup.resort(false);
+  }
+
+  void refreshUi(boolean selectionVisible, boolean itemsChanged, boolean reused, boolean onExplicitAction) {
+    if (myLookup.getEditor().getComponent().getRootPane() == null) {
+      return;
+    }
+
+    updateScrollbarVisibility();
+
+    if (myLookup.myResizePending || itemsChanged) {
+      myMaximumHeight = Integer.MAX_VALUE;
+    }
+    Rectangle rectangle = calculatePosition();
+    myMaximumHeight = rectangle.height;
+
+    if (myLookup.myResizePending || itemsChanged) {
+      myLookup.myResizePending = false;
+      myLookup.pack();
+    }
+    HintManagerImpl.updateLocation(myLookup, myLookup.getEditor(), rectangle.getLocation());
+
+    if (reused || selectionVisible || onExplicitAction) {
+      myLookup.ensureSelectionVisible(false);
+    }
+  }
+
+  boolean isPositionedAboveCaret() {
+    return myPositionedAbove != null && myPositionedAbove.booleanValue();
+  }
+
+  // in layered pane coordinate system.
+  Rectangle calculatePosition() {
+    Dimension dim = myLookup.getComponent().getPreferredSize();
+    int lookupStart = myLookup.getLookupStart();
+    Editor editor = myLookup.getEditor();
+    if (lookupStart < 0 || lookupStart > editor.getDocument().getTextLength()) {
+      LOG.error(lookupStart + "; offset=" + editor.getCaretModel().getOffset() + "; element=" +
+                myLookup.getPsiElement());
+    }
+
+    LogicalPosition pos = editor.offsetToLogicalPosition(lookupStart);
+    Point location = editor.logicalPositionToXY(pos);
+    location.y += editor.getLineHeight();
+    location.x -= myLookup.myCellRenderer.getIconIndent() + myLookup.getComponent().getInsets().left;
+
+    SwingUtilities.convertPointToScreen(location, editor.getContentComponent());
+    final Rectangle screenRectangle = ScreenUtil.getScreenRectangle(location);
+
+    if (!isPositionedAboveCaret()) {
+      int shiftLow = screenRectangle.height - (location.y + dim.height);
+      myPositionedAbove = shiftLow < 0 && shiftLow < location.y - dim.height && location.y >= dim.height;
+    }
+    if (isPositionedAboveCaret()) {
+      location.y -= dim.height + editor.getLineHeight();
+      if (pos.line == 0) {
+        location.y += 1;
+        //otherwise the lookup won't intersect with the editor and every editor's resize (e.g. after typing in console) will close the lookup
+      }
+    }
+
+    if (!screenRectangle.contains(location)) {
+      location = ScreenUtil.findNearestPointOnBorder(screenRectangle, location);
+    }
+
+    final JRootPane rootPane = editor.getComponent().getRootPane();
+    if (rootPane == null) {
+      LOG.error("editor.disposed=" + editor.isDisposed() + "; lookup.disposed=" + myLookup.isLookupDisposed() + "; editorShowing=" + editor.getContentComponent().isShowing());
+    }
+    Rectangle candidate = new Rectangle(location, dim);
+    ScreenUtil.cropRectangleToFitTheScreen(candidate);
+
+    SwingUtilities.convertPointFromScreen(location, rootPane.getLayeredPane());
+    myMaximumHeight = candidate.height;
+    return new Rectangle(location.x, location.y, dim.width, candidate.height);
+  }
+
+  private class LookupLayeredPane extends JBLayeredPane {
+    final JPanel mainPanel = new JPanel(new BorderLayout());
+
+    private LookupLayeredPane() {
+      add(mainPanel, 0, 0);
+      add(myIconPanel, 42, 0);
+      add(mySortingLabel, 10, 0);
+
+      setLayout(new AbstractLayoutManager() {
+        @Override
+        public Dimension preferredLayoutSize(@Nullable Container parent) {
+          int maxCellWidth = myLookup.myLookupTextWidth + myLookup.myCellRenderer.getIconIndent();
+          int scrollBarWidth = myScrollPane.getPreferredSize().width - myScrollPane.getViewport().getPreferredSize().width;
+          int listWidth = Math.min(scrollBarWidth + maxCellWidth, UISettings.getInstance().MAX_LOOKUP_WIDTH2);
+
+          Dimension adSize = myAdvertiser.getAdComponent().getPreferredSize();
+
+          int panelHeight = myList.getPreferredScrollableViewportSize().height + adSize.height;
+          if (myList.getModel().getSize() > myList.getVisibleRowCount() && myList.getVisibleRowCount() >= 5) {
+            panelHeight -= myList.getFixedCellHeight() / 2;
+          }
+          return new Dimension(Math.max(listWidth, adSize.width), Math.min(panelHeight, myMaximumHeight));
+        }
+
+        @Override
+        public void layoutContainer(Container parent) {
+          Dimension size = getSize();
+          mainPanel.setSize(size);
+          mainPanel.validate();
+
+          if (!myLookup.myResizePending) {
+            Dimension preferredSize = preferredLayoutSize(null);
+            if (preferredSize.width != size.width) {
+              UISettings.getInstance().MAX_LOOKUP_WIDTH2 = Math.max(500, size.width);
+            }
+
+            int listHeight = myList.getLastVisibleIndex() - myList.getFirstVisibleIndex() + 1;
+            if (listHeight != myList.getModel().getSize() && listHeight != myList.getVisibleRowCount() && preferredSize.height != size.height) {
+              UISettings.getInstance().MAX_LOOKUP_LIST_HEIGHT = Math.max(5, listHeight);
+            }
+          }
+
+          myList.setFixedCellWidth(myScrollPane.getViewport().getWidth());
+          layoutStatusIcons();
+          layoutHint();
+        }
+      });
+    }
+
+    private void layoutStatusIcons() {
+      int adHeight = myAdvertiser.getAdComponent().getPreferredSize().height;
+      Dimension buttonSize = adHeight > 0 || !mySortingLabel.isVisible() ? new Dimension(0, 0) : new Dimension(
+        AllIcons.Ide.LookupRelevance.getIconWidth(), AllIcons.Ide.LookupRelevance.getIconHeight());
+      myScrollBarIncreaseButton.setPreferredSize(buttonSize);
+      myScrollBarIncreaseButton.setMinimumSize(buttonSize);
+      myScrollBarIncreaseButton.setMaximumSize(buttonSize);
+      JScrollBar scrollBar = myScrollPane.getVerticalScrollBar();
+      scrollBar.revalidate();
+      scrollBar.repaint();
+
+      final Dimension iconSize = myProcessIcon.getPreferredSize();
+      myIconPanel.setBounds(getWidth() - iconSize.width - (scrollBar.isVisible() ? scrollBar.getWidth() : 0), 0, iconSize.width, iconSize.height);
+
+      final Dimension sortSize = mySortingLabel.getPreferredSize();
+      final Point sbLocation = SwingUtilities.convertPoint(scrollBar, 0, 0, myLayeredPane);
+
+      final int sortHeight = Math.max(adHeight, mySortingLabel.getPreferredSize().height);
+      mySortingLabel.setBounds(sbLocation.x, getHeight() - sortHeight, sortSize.width, sortHeight);
+    }
+
+    void layoutHint() {
+      if (myElementHint != null && myLookup.getCurrentItem() != null) {
+        final Rectangle bounds = myLookup.getCurrentItemBounds();
+        myElementHint.setSize(myElementHint.getPreferredSize());
+
+        JScrollBar sb = myScrollPane.getVerticalScrollBar();
+        int x = bounds.x + bounds.width - myElementHint.getWidth() + (sb.isVisible() ? sb.getWidth() : 0);
+        x = Math.min(x, getWidth() - myElementHint.getWidth());
+        myElementHint.setLocation(new Point(x, bounds.y));
+      }
+    }
+  }
+
+  private class LookupHint extends JLabel {
+    private final Border INACTIVE_BORDER = BorderFactory.createEmptyBorder(2, 2, 2, 2);
+    private final Border ACTIVE_BORDER = BorderFactory.createCompoundBorder(BorderFactory.createLineBorder(Color.BLACK, 1), BorderFactory.createEmptyBorder(1, 1, 1, 1));
+    private LookupHint() {
+      setOpaque(false);
+      setBorder(INACTIVE_BORDER);
+      setIcon(AllIcons.Actions.IntentionBulb);
+      String acceleratorsText = KeymapUtil.getFirstKeyboardShortcutText(
+        ActionManager.getInstance().getAction(IdeActions.ACTION_SHOW_INTENTION_ACTIONS));
+      if (acceleratorsText.length() > 0) {
+        setToolTipText(CodeInsightBundle.message("lightbulb.tooltip", acceleratorsText));
+      }
+
+      addMouseListener(new MouseAdapter() {
+        @Override
+        public void mouseEntered(MouseEvent e) {
+          setBorder(ACTIVE_BORDER);
+        }
+
+        @Override
+        public void mouseExited(MouseEvent e) {
+          setBorder(INACTIVE_BORDER);
+        }
+        @Override
+        public void mousePressed(MouseEvent e) {
+          if (!e.isPopupTrigger() && e.getButton() == MouseEvent.BUTTON1) {
+            myLookup.showElementActions();
+          }
+        }
+      });
+    }
+  }
+
+  private class ChangeLookupSorting extends ClickListener {
+
+    @Override
+    public boolean onClick(@NotNull MouseEvent e, int clickCount) {
+      DataContext context = DataManager.getInstance().getDataContext(mySortingLabel);
+      DefaultActionGroup group = new DefaultActionGroup();
+      group.add(createSortingAction(true));
+      group.add(createSortingAction(false));
+      JBPopupFactory.getInstance().createActionGroupPopup("Change sorting", group, context, JBPopupFactory.ActionSelectionAid.SPEEDSEARCH, false).showInBestPositionFor(
+        context);
+      return true;
+    }
+
+    private AnAction createSortingAction(boolean checked) {
+      boolean currentSetting = UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY;
+      final boolean newSetting = checked ? currentSetting : !currentSetting;
+      return new DumbAwareAction(newSetting ? "Sort lexicographically" : "Sort by relevance", null, checked ? PlatformIcons.CHECK_ICON : null) {
+        @Override
+        public void actionPerformed(AnActionEvent e) {
+          FeatureUsageTracker.getInstance().triggerFeatureUsed(CodeCompletionFeatures.EDITING_COMPLETION_CHANGE_SORTING);
+          UISettings.getInstance().SORT_LOOKUP_ELEMENTS_LEXICOGRAPHICALLY = newSetting;
+          updateSorting();
+        }
+      };
+    }
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java
index 903f2cb..ebd20cf 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/lookup/impl/actions/ChooseItemAction.java
@@ -22,23 +22,21 @@
 import com.intellij.codeInsight.lookup.Lookup;
 import com.intellij.codeInsight.lookup.LookupManager;
 import com.intellij.codeInsight.lookup.impl.LookupImpl;
-import com.intellij.codeInsight.template.CustomLiveTemplate;
-import com.intellij.codeInsight.template.CustomLiveTemplateBase;
-import com.intellij.codeInsight.template.CustomTemplateCallback;
 import com.intellij.codeInsight.template.impl.*;
 import com.intellij.featureStatistics.FeatureUsageTracker;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.actionSystem.EditorAction;
 import com.intellij.openapi.editor.actionSystem.EditorActionHandler;
-import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiFile;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 
+import java.util.List;
+
 public abstract class ChooseItemAction extends EditorAction {
-  public ChooseItemAction(Handler handler){
+  public ChooseItemAction(Handler handler) {
     super(handler);
   }
 
@@ -90,7 +88,6 @@
 
       return true;
     }
-    
   }
 
   public static boolean hasTemplatePrefix(LookupImpl lookup, char shortcutChar) {
@@ -109,6 +106,7 @@
     if (file == null) return false;
 
     final Editor editor = lookup.getEditor();
+    final int offset = editor.getCaretModel().getOffset();
     PsiDocumentManager.getInstance(file.getProject()).commitDocument(editor.getDocument());
 
     final LiveTemplateLookupElement liveTemplateLookup = ContainerUtil.findInstance(lookup.getItems(), LiveTemplateLookupElement.class);
@@ -118,34 +116,14 @@
       //    in this case we should find live template with appropriate prefix (custom live templates doesn't participate in this action). 
       // - completion provider worked too long:
       //    in this case we should check custom templates that provides completion lookup.
-      
-      final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file, false);
-      for (CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) {
-        if (customLiveTemplate instanceof CustomLiveTemplateBase) {
-          final int offset = editor.getCaretModel().getOffset();
-          if (customLiveTemplate.getShortcut() == shortcutChar 
-              && TemplateManagerImpl.isApplicable(customLiveTemplate, editor, file)
-              && ((CustomLiveTemplateBase)customLiveTemplate).hasCompletionItem(file, offset)) {
-            return customLiveTemplate.computeTemplateKey(callback) != null;
-          }
-        }
+      if (LiveTemplateCompletionContributor.customTemplateAvailableAndHasCompletionItem(shortcutChar, editor, file, offset)) {
+        return true;
       }
 
-
-      final int end = editor.getCaretModel().getOffset();
-      final int start = lookup.getLookupStart();
-      final String prefix = !lookup.getItems().isEmpty()
-                            ? editor.getDocument().getText(TextRange.create(start, end))
-                            : ListTemplatesHandler.getPrefix(editor.getDocument(), end, false);
-
-      if (TemplateSettings.getInstance().getTemplates(prefix).isEmpty()) {
-        return false;
-      }
-
-      for (TemplateImpl template : SurroundWithTemplateHandler.getApplicableTemplates(editor, file, false)) {
-        if (prefix.equals(template.getKey()) && shortcutChar == TemplateSettings.getInstance().getShortcutChar(template)) {
-          return true;
-        }
+      List<TemplateImpl> templates = TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(editor, file, false);
+      TemplateImpl template = LiveTemplateCompletionContributor.findFullMatchedApplicableTemplate(editor, offset, templates);
+      if (template != null && shortcutChar == TemplateSettings.getInstance().getShortcutChar(template)) {
+        return true;
       }
       return false;
     }
@@ -158,20 +136,22 @@
       super(new Handler(true, Lookup.NORMAL_SELECT_CHAR));
     }
   }
+
   public static class Replacing extends ChooseItemAction {
     public Replacing() {
       super(new Handler(false, Lookup.REPLACE_SELECT_CHAR));
     }
   }
+
   public static class CompletingStatement extends ChooseItemAction {
     public CompletingStatement() {
       super(new Handler(true, Lookup.COMPLETE_STATEMENT_SELECT_CHAR));
     }
   }
+
   public static class ChooseWithDot extends ChooseItemAction {
     public ChooseWithDot() {
       super(new Handler(false, '.'));
     }
   }
-
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/problems/MockWolfTheProblemSolver.java b/platform/lang-impl/src/com/intellij/codeInsight/problems/MockWolfTheProblemSolver.java
index 75ad56e..eeb5e04 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/problems/MockWolfTheProblemSolver.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/problems/MockWolfTheProblemSolver.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -22,7 +22,6 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.problems.Problem;
 import com.intellij.problems.WolfTheProblemSolver;
-import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.Collection;
@@ -84,33 +83,6 @@
   }
 
   @Override
-  public void projectOpened() {
-    if (myDelegate != null) myDelegate.projectOpened();
-  }
-
-  @Override
-  public void projectClosed() {
-    if (myDelegate != null) myDelegate.projectClosed();
-  }
-
-  @Override
-  @NonNls
-  @NotNull
-  public String getComponentName() {
-    return "mockwolf";
-  }
-
-  @Override
-  public void initComponent() {
-
-  }
-
-  @Override
-  public void disposeComponent() {
-
-  }
-
-  @Override
   public void clearProblems(@NotNull VirtualFile virtualFile) {
     if (myDelegate != null) myDelegate.clearProblems(virtualFile);
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java
index 6cfbe08..45b4532 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/problems/WolfTheProblemSolverImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -44,7 +44,6 @@
 import com.intellij.util.containers.ContainerUtil;
 import gnu.trove.THashMap;
 import gnu.trove.THashSet;
-import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -218,31 +217,6 @@
     }
   }
 
-  @Override
-  public void projectOpened() {
-  }
-
-  @Override
-  public void projectClosed() {
-  }
-
-  @Override
-  @NotNull
-  @NonNls
-  public String getComponentName() {
-    return "Problems";
-  }
-
-  @Override
-  public void initComponent() {
-
-  }
-
-  @Override
-  public void disposeComponent() {
-
-  }
-
   public void startCheckingIfVincentSolvedProblemsYet(@NotNull ProgressIndicator progress,
                                                       @NotNull ProgressableTextEditorHighlightingPass pass)
     throws ProcessCanceledException {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java
index e03ae57..896dc82 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java
@@ -39,10 +39,10 @@
  */
 public class CustomTemplateCallback {
   private final TemplateManager myTemplateManager;
-  private final Editor myEditor;
-  private final PsiFile myFile;
+  @NotNull private final Editor myEditor;
+  @NotNull private final PsiFile myFile;
   private final int myOffset;
-  private final Project myProject;
+  @NotNull private final Project myProject;
   private final boolean myInInjectedFragment;
   private Set<TemplateContextType> myApplicableContextTypes;
 
@@ -58,6 +58,11 @@
     myEditor = myInInjectedFragment ? InjectedLanguageUtil.getEditorForInjectedLanguageNoCommit(editor, file, myOffset) : editor;
   }
 
+  public TemplateManager getTemplateManager() {
+    return myTemplateManager;
+  }
+
+  @NotNull
   public PsiFile getFile() {
     return myFile;
   }
@@ -71,7 +76,7 @@
     return myOffset;
   }
 
-  private static int getOffset(boolean wrapping, Editor editor) {
+  private static int getOffset(boolean wrapping, @NotNull Editor editor) {
     if (wrapping) {
       return editor.getSelectionModel().getSelectionStart();
     }
@@ -98,29 +103,21 @@
     return result;
   }
 
-  private boolean isAvailableTemplate(TemplateImpl template) {
+  private boolean isAvailableTemplate(@NotNull TemplateImpl template) {
     if (myApplicableContextTypes == null) {
       myApplicableContextTypes = TemplateManagerImpl.getApplicableContextTypes(myFile, myOffset);  
     }
     return !template.isDeactivated() && TemplateManagerImpl.isApplicable(template, myApplicableContextTypes);
   }
 
-  public void startTemplate(Template template, Map<String, String> predefinedValues, TemplateEditingListener listener) {
+  public void startTemplate(@NotNull Template template, Map<String, String> predefinedValues, TemplateEditingListener listener) {
     if(myInInjectedFragment) {
       template.setToReformat(false);
     }
     myTemplateManager.startTemplate(myEditor, template, false, predefinedValues, listener);
   }
 
-  public void startTemplate() {
-    Map<TemplateImpl, String> template2Argument =
-      ((TemplateManagerImpl)myTemplateManager).findMatchingTemplates(myFile, myEditor, null, TemplateSettings.getInstance());
-    Runnable runnable = ((TemplateManagerImpl)myTemplateManager).startNonCustomTemplates(template2Argument, myEditor, null);
-    if (runnable != null) {
-      runnable.run();
-    }
-  }
-
+  @NotNull
   private static List<TemplateImpl> getMatchingTemplates(@NotNull String templateKey) {
     TemplateSettings settings = TemplateSettings.getInstance();
     List<TemplateImpl> candidates = new ArrayList<TemplateImpl>();
@@ -142,11 +139,12 @@
     return myFile.getFileType();
   }
 
+  @NotNull
   public Project getProject() {
     return myProject;
   }
 
-  public void deleteTemplateKey(String key) {
+  public void deleteTemplateKey(@NotNull String key) {
     int caretAt = myEditor.getCaretModel().getOffset();
     myEditor.getDocument().deleteString(caretAt - key.length(), caretAt);
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java b/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java
index 5048a08..0feed37 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/actions/SaveAsTemplateAction.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -27,7 +27,10 @@
 import com.intellij.codeInsight.template.TemplateContextType;
 import com.intellij.codeInsight.template.impl.*;
 import com.intellij.lang.StdLanguages;
-import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.actionSystem.AnActionEvent;
+import com.intellij.openapi.actionSystem.CommonDataKeys;
+import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.application.AccessToken;
 import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.command.WriteCommandAction;
@@ -130,7 +133,7 @@
     PsiFile copy;
     AccessToken token = WriteAction.start();
     try {
-      copy = SurroundWithTemplateHandler.insertDummyIdentifier(editor, file);
+      copy = TemplateManagerImpl.insertDummyIdentifier(editor, file);
     }
     finally {
       token.finish();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java
index 45e2e2c..798e82c 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/ListTemplatesHandler.java
@@ -36,6 +36,7 @@
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Pair;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiFile;
 import com.intellij.util.containers.ContainerUtil;
@@ -57,50 +58,80 @@
 
     PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
     int offset = editor.getCaretModel().getOffset();
-    String prefix = getPrefix(editor.getDocument(), offset, false);
-    String prefixWithoutDots = getPrefix(editor.getDocument(), offset, true);
+    List<TemplateImpl> applicableTemplates = TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(editor, file, false);
 
-    List<TemplateImpl> matchingTemplates = new ArrayList<TemplateImpl>();
-    ArrayList<TemplateImpl> applicableTemplates = SurroundWithTemplateHandler.getApplicableTemplates(editor, file, false);
-    final Pattern prefixSearchPattern = Pattern.compile(".*\\b" + prefixWithoutDots + ".*");
-    for (TemplateImpl template : applicableTemplates) {
-      final String templateDescription = template.getDescription();
-      if (template.getKey().startsWith(prefix) ||
-          !prefixWithoutDots.isEmpty() && templateDescription != null && prefixSearchPattern.matcher(templateDescription).matches()) {
-        matchingTemplates.add(template);
+    Map<TemplateImpl, String> matchingTemplates = filterTemplatesByPrefix(applicableTemplates, editor, offset, false, true);
+    MultiMap<String, CustomLiveTemplateLookupElement> customTemplatesLookupElements = getCustomTemplatesLookupItems(editor, file, offset);
+
+    if (matchingTemplates.isEmpty()) {
+      for (TemplateImpl template : applicableTemplates) {
+        matchingTemplates.put(template, null);
       }
     }
 
-    MultiMap<String,CustomLiveTemplateLookupElement> customTemplatesLookupElements = listApplicableCustomTemplates(editor, file, offset);
-
-    if (matchingTemplates.isEmpty()) {
-      matchingTemplates.addAll(applicableTemplates);
-      prefixWithoutDots = "";
-    }
-
     if (matchingTemplates.isEmpty() && customTemplatesLookupElements.isEmpty()) {
-      String text = prefixWithoutDots.length() == 0
-                    ? CodeInsightBundle.message("templates.no.defined")
-                    : CodeInsightBundle.message("templates.no.defined.with.prefix", prefix);
-      HintManager.getInstance().showErrorHint(editor, text);
+      HintManager.getInstance().showErrorHint(editor, CodeInsightBundle.message("templates.no.defined"));
       return;
     }
 
-    Collections.sort(matchingTemplates, TemplateListPanel.TEMPLATE_COMPARATOR);
-    showTemplatesLookup(project, editor, file, prefixWithoutDots, matchingTemplates, customTemplatesLookupElements);
+    showTemplatesLookup(project, editor, file, matchingTemplates, customTemplatesLookupElements);
+  }
+
+  public static Map<TemplateImpl, String> filterTemplatesByPrefix(@NotNull Collection<TemplateImpl> templates, @NotNull Editor editor,
+                                                                  int offset, boolean fullMatch, boolean searchInDescription) {
+    CharSequence documentText = editor.getDocument().getCharsSequence().subSequence(0, offset);
+
+    String prefixWithoutDots = computeDescriptionMatchingPrefix(editor.getDocument(), offset);
+    Pattern prefixSearchPattern = Pattern.compile(".*\\b" + prefixWithoutDots + ".*");
+
+    Map<TemplateImpl, String> matchingTemplates = new TreeMap<TemplateImpl, String>(TemplateListPanel.TEMPLATE_COMPARATOR);
+    for (TemplateImpl template : templates) {
+      String templateKey = template.getKey();
+      if (fullMatch) {
+        int startOffset = documentText.length() - templateKey.length();
+        if (startOffset <= 0 || !Character.isJavaIdentifierPart(documentText.charAt(startOffset - 1))) {
+          // after non-identifier
+          if (StringUtil.endsWith(documentText, templateKey)) {
+            matchingTemplates.put(template, templateKey);
+          }
+        }
+      }
+      else {
+        for (int i = templateKey.length(); i > 0; i--) {
+          String prefix = templateKey.substring(0, i);
+          int startOffset = documentText.length() - i;
+          if (startOffset > 0 && Character.isJavaIdentifierPart(documentText.charAt(startOffset - 1))) {
+            // after java identifier
+            continue;
+          }
+          if (StringUtil.endsWith(documentText, prefix)) {
+            matchingTemplates.put(template, prefix);
+            break;
+          }
+        }
+      }
+
+      if (searchInDescription) {
+        String templateDescription = template.getDescription();
+        if (!prefixWithoutDots.isEmpty() && templateDescription != null && prefixSearchPattern.matcher(templateDescription).matches()) {
+          matchingTemplates.put(template, prefixWithoutDots);
+        }
+      }
+    }
+
+    return matchingTemplates;
   }
 
   private static void showTemplatesLookup(final Project project,
                                           final Editor editor,
                                           final PsiFile file,
-                                          @NotNull String prefix,
-                                          @NotNull List<TemplateImpl> matchingTemplates,
+                                          @NotNull Map<TemplateImpl, String> matchingTemplates,
                                           @NotNull MultiMap<String, CustomLiveTemplateLookupElement> customTemplatesLookupElements) {
 
-    final LookupImpl lookup = (LookupImpl)LookupManager.getInstance(project).createLookup(editor, LookupElement.EMPTY_ARRAY, prefix,
-                                                                                          new TemplatesArranger());
-    for (TemplateImpl template : matchingTemplates) {
-      lookup.addItem(createTemplateElement(template), new PlainPrefixMatcher(prefix));
+    LookupImpl lookup = (LookupImpl)LookupManager.getInstance(project).createLookup(editor, LookupElement.EMPTY_ARRAY, "", new TemplatesArranger());
+    for (Map.Entry<TemplateImpl, String> entry : matchingTemplates.entrySet()) {
+      TemplateImpl template = entry.getKey();
+      lookup.addItem(createTemplateElement(template), new PlainPrefixMatcher(StringUtil.notNullize(entry.getValue())));
     }
 
     for (Map.Entry<String, Collection<CustomLiveTemplateLookupElement>> entry : customTemplatesLookupElements.entrySet()) {
@@ -112,11 +143,13 @@
     showLookup(lookup, file);
   }
 
-  private static MultiMap<String, CustomLiveTemplateLookupElement> listApplicableCustomTemplates(@NotNull Editor editor, @NotNull PsiFile file, int offset) {
+  public static MultiMap<String, CustomLiveTemplateLookupElement> getCustomTemplatesLookupItems(@NotNull Editor editor,
+                                                                                                @NotNull PsiFile file,
+                                                                                                int offset) {
     final MultiMap<String, CustomLiveTemplateLookupElement> result = MultiMap.create();
     CustomTemplateCallback customTemplateCallback = new CustomTemplateCallback(editor, file, false);
-    for (CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) {
-      if (customLiveTemplate instanceof CustomLiveTemplateBase && TemplateManagerImpl.isApplicable(customLiveTemplate, editor, file)) {
+    for (CustomLiveTemplate customLiveTemplate : TemplateManagerImpl.listApplicableCustomTemplates(editor, file, false)) {
+      if (customLiveTemplate instanceof CustomLiveTemplateBase) {
         String customTemplatePrefix = ((CustomLiveTemplateBase)customLiveTemplate).computeTemplateKeyWithoutContextChecking(customTemplateCallback);
         if (customTemplatePrefix != null) {
           result.putValues(customTemplatePrefix, ((CustomLiveTemplateBase)customLiveTemplate).getLookupElements(file, editor, offset));
@@ -182,13 +215,13 @@
     return true;
   }
 
-  public static String getPrefix(Document document, int offset, boolean lettersOnly) {
+  private static String computeDescriptionMatchingPrefix(Document document, int offset) {
     CharSequence chars = document.getCharsSequence();
     int start = offset;
     while (true) {
       if (start == 0) break;
       char c = chars.charAt(start - 1);
-      if (!(Character.isJavaIdentifierPart(c) || !lettersOnly && c == '.')) break;
+      if (!(Character.isJavaIdentifierPart(c))) break;
       start--;
     }
     return chars.subSequence(start, offset).toString();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java
index 0bbe11f..d9fec79 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/LiveTemplateCompletionContributor.java
@@ -20,11 +20,10 @@
 import com.intellij.codeInsight.template.CustomLiveTemplate;
 import com.intellij.codeInsight.template.CustomLiveTemplateBase;
 import com.intellij.codeInsight.template.CustomTemplateCallback;
-import com.intellij.codeInsight.template.TemplateContextType;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.registry.Registry;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.patterns.PlatformPatterns;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.PsiPlainTextFile;
@@ -35,11 +34,13 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.ArrayList;
+import java.util.Collection;
 import java.util.List;
-import java.util.Set;
+import java.util.Map;
 import java.util.concurrent.atomic.AtomicBoolean;
 
+import static com.intellij.codeInsight.template.impl.ListTemplatesHandler.filterTemplatesByPrefix;
+
 /**
  * @author peter
  */
@@ -52,7 +53,7 @@
     }
     return Registry.is("show.live.templates.in.completion");
   }
-  
+
   public LiveTemplateCompletionContributor() {
     extend(CompletionType.BASIC, PlatformPatterns.psiElement(), new CompletionProvider<CompletionParameters>() {
       @Override
@@ -60,14 +61,14 @@
                                     ProcessingContext context,
                                     @NotNull CompletionResultSet result) {
         final PsiFile file = parameters.getPosition().getContainingFile();
-        if (file instanceof PsiPlainTextFile &&
-            parameters.getEditor().getComponent().getParent() instanceof EditorTextField) {
+        if (file instanceof PsiPlainTextFile && parameters.getEditor().getComponent().getParent() instanceof EditorTextField) {
           return;
         }
 
-        final int offset = parameters.getOffset();
-        final List<TemplateImpl> templates = listApplicableTemplates(file, offset);
+        int offset = parameters.getOffset();
+        final List<TemplateImpl> availableTemplates = TemplateManagerImpl.listApplicableTemplates(file, offset, false);
         Editor editor = parameters.getEditor();
+        final Map<TemplateImpl, String> templates = filterTemplatesByPrefix(availableTemplates, editor, offset, false, false);
         if (showAllTemplates()) {
           final AtomicBoolean templatesShown = new AtomicBoolean(false);
           final CompletionResultSet finalResult = result;
@@ -85,75 +86,74 @@
 
         if (parameters.getInvocationCount() > 0) return; //only in autopopups for now
 
-        String templatePrefix = findLiveTemplatePrefix(file, editor, result.getPrefixMatcher().getPrefix());
-        final TemplateImpl template = findApplicableTemplate(file, offset, templatePrefix);
-        if (template != null) {
-          result = result.withPrefixMatcher(template.getKey());
-          result.addElement(new LiveTemplateLookupElementImpl(template, true));
+        // custom templates should handle this situation by itself (return true from hasCompletionItems() and provide lookup element)
+        // regular templates won't be shown in this case
+        if (!customTemplateAvailableAndHasCompletionItem(null, editor, file, offset)) {
+          TemplateImpl template = findFullMatchedApplicableTemplate(editor, offset, availableTemplates);
+          if (template != null) {
+            result.withPrefixMatcher(result.getPrefixMatcher().cloneWithPrefix(template.getKey()))
+              .addElement(new LiveTemplateLookupElementImpl(template, true));
+          }
         }
-        for (final TemplateImpl possible : templates) {
-          result.restartCompletionOnPrefixChange(possible.getKey());
+        
+        for (Map.Entry<TemplateImpl, String> possible : templates.entrySet()) {
+          String templateKey = possible.getKey().getKey();
+          String currentPrefix = possible.getValue();
+          result.withPrefixMatcher(result.getPrefixMatcher().cloneWithPrefix(currentPrefix))
+            .restartCompletionOnPrefixChange(templateKey);
         }
       }
     });
   }
 
+  public static boolean customTemplateAvailableAndHasCompletionItem(@Nullable Character shortcutChar, @NotNull Editor editor, @NotNull PsiFile file, int offset) {
+    CustomTemplateCallback callback = new CustomTemplateCallback(editor, file, false);
+    for (CustomLiveTemplate customLiveTemplate : TemplateManagerImpl.listApplicableCustomTemplates(editor, file, false)) {
+      if (customLiveTemplate instanceof CustomLiveTemplateBase) {
+        if ((shortcutChar == null || customLiveTemplate.getShortcut() == shortcutChar.charValue())
+            && ((CustomLiveTemplateBase)customLiveTemplate).hasCompletionItem(file, offset)) {
+          return customLiveTemplate.computeTemplateKey(callback) != null;
+        }
+      }
+    }
+    return false;
+  }
+
   @SuppressWarnings("MethodMayBeStatic") //for Kotlin
   protected boolean showAllTemplates() {
     return shouldShowAllTemplates();
   }
 
-  private static void ensureTemplatesShown(AtomicBoolean templatesShown,
-                                           List<TemplateImpl> templates,
-                                           CompletionParameters parameters, 
-                                           CompletionResultSet result) {
+  private static void ensureTemplatesShown(AtomicBoolean templatesShown, Map<TemplateImpl, String> templates,
+                                           CompletionParameters parameters, CompletionResultSet result) {
     if (!templatesShown.getAndSet(true)) {
-      for (final TemplateImpl possible : templates) {
-        result.addElement(new LiveTemplateLookupElementImpl(possible, false));
+      for (final Map.Entry<TemplateImpl, String> entry : templates.entrySet()) {
+        result.withPrefixMatcher(result.getPrefixMatcher().cloneWithPrefix(StringUtil.notNullize(entry.getValue())))
+          .addElement(new LiveTemplateLookupElementImpl(entry.getKey(), false));
       }
 
       PsiFile file = parameters.getPosition().getContainingFile();
       Editor editor = parameters.getEditor();
-      for (CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) {
-        if (customLiveTemplate instanceof CustomLiveTemplateBase && TemplateManagerImpl.isApplicable(customLiveTemplate, editor, file)) {
+      for (CustomLiveTemplate customLiveTemplate : TemplateManagerImpl.listApplicableCustomTemplates(editor, file, false)) {
+        if (customLiveTemplate instanceof CustomLiveTemplateBase) {
           ((CustomLiveTemplateBase)customLiveTemplate).addCompletions(parameters, result);
         }
       }
     }
   }
 
-  private static List<TemplateImpl> listApplicableTemplates(PsiFile file, int offset) {
-    Set<TemplateContextType> contextTypes = TemplateManagerImpl.getApplicableContextTypes(file, offset);
-
-    final ArrayList<TemplateImpl> result = ContainerUtil.newArrayList();
-    for (final TemplateImpl template : TemplateSettings.getInstance().getTemplates()) {
-      if (!template.isDeactivated() && TemplateManagerImpl.isApplicable(template, contextTypes)) {
-        result.add(template);
-      }
-    }
-    return result;
-  }
-
   @Nullable
-  public static TemplateImpl findApplicableTemplate(final PsiFile file, int offset, @NotNull final String possiblePrefix) {
-    return ContainerUtil.find(listApplicableTemplates(file, offset), new Condition<TemplateImpl>() {
-      @Override
-      public boolean value(TemplateImpl template) {
-        return possiblePrefix.equals(template.getKey());
-      }
-    });
-  }
-
-  @NotNull
-  public static String findLiveTemplatePrefix(@NotNull PsiFile file, @NotNull Editor editor, @NotNull String defaultValue) {
-    final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file, false);
-    for (CustomLiveTemplate customLiveTemplate : CustomLiveTemplate.EP_NAME.getExtensions()) {
-      final String customKey = customLiveTemplate.computeTemplateKey(callback);
-      if (customKey != null) {
-        return customKey;
+  public static TemplateImpl findFullMatchedApplicableTemplate(@NotNull Editor editor,
+                                                               int offset,
+                                                               @NotNull Collection<TemplateImpl> availableTemplates) {
+    Map<TemplateImpl, String> templates = filterTemplatesByPrefix(availableTemplates, editor, offset, true, false);
+    if (templates.size() == 1) {
+      TemplateImpl template = ContainerUtil.getFirstItem(templates.keySet());
+      if (template != null) {
+        return template;
       }
     }
-    return defaultValue;
+    return null;
   }
 
   public static class Skipper extends CompletionPreselectSkipper {
@@ -163,5 +163,4 @@
       return element instanceof LiveTemplateLookupElement && ((LiveTemplateLookupElement)element).sudden && !Registry.is("ide.completion.autopopup.select.live.templates");
     }
   }
-
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/SurroundWithTemplateHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/SurroundWithTemplateHandler.java
index 08034b24..edfb37a 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/SurroundWithTemplateHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/SurroundWithTemplateHandler.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -33,7 +33,6 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.ArrayList;
 import java.util.HashSet;
 import java.util.List;
 import java.util.Set;
@@ -63,8 +62,8 @@
       if (!editor.getSelectionModel().hasSelection()) return null;
     }
     PsiDocumentManager.getInstance(project).commitDocument(editor.getDocument());
-    List<CustomLiveTemplate> customTemplates = getApplicableCustomTemplates(editor, file);
-    ArrayList<TemplateImpl> templates = getApplicableTemplates(editor, file, true);
+    List<CustomLiveTemplate> customTemplates = TemplateManagerImpl.listApplicableCustomTemplates(editor, file, true);
+    List<TemplateImpl> templates = TemplateManagerImpl.listApplicableTemplateWithInsertingDummyIdentifier(editor, file, true);
     if (templates.isEmpty() && customTemplates.isEmpty()) {
       HintManager.getInstance().showErrorHint(editor, CodeInsightBundle.message("templates.surround.no.defined"));
       return null;
@@ -89,45 +88,4 @@
   public boolean startInWriteAction() {
     return true;
   }
-
-  public static List<CustomLiveTemplate> getApplicableCustomTemplates(Editor editor, PsiFile file) {
-    List<CustomLiveTemplate> result = new ArrayList<CustomLiveTemplate>();
-    for (CustomLiveTemplate template : CustomLiveTemplate.EP_NAME.getExtensions()) {
-      if (template.supportsWrapping() && isApplicable(template, editor, file)) {
-        result.add(template);
-      }
-    }
-    return result;
-  }
-
-  public static boolean isApplicable(CustomLiveTemplate template, Editor editor, PsiFile file) {
-    return template.isApplicable(file, editor.getSelectionModel().getSelectionStart(), true);
-  }
-
-  public static ArrayList<TemplateImpl> getApplicableTemplates(Editor editor, PsiFile file, boolean selectionOnly) {
-
-    int startOffset = editor.getCaretModel().getOffset();
-    if (editor.getSelectionModel().hasSelection()) {
-      startOffset = editor.getSelectionModel().getSelectionStart();
-    }
-
-    file = insertDummyIdentifier(editor, file);
-
-    ArrayList<TemplateImpl> list = new ArrayList<TemplateImpl>();
-    for (TemplateImpl template : TemplateSettings.getInstance().getTemplates()) {
-      if (!template.isDeactivated() &&
-          (!selectionOnly || template.isSelectionTemplate()) &&
-          TemplateManagerImpl.isApplicable(file, startOffset, template)) {
-        list.add(template);
-      }
-    }
-    return list;
-  }
-
-  public static PsiFile insertDummyIdentifier(final Editor editor, PsiFile file) {
-    boolean selection = editor.getSelectionModel().hasSelection();
-    final int startOffset = selection ? editor.getSelectionModel().getSelectionStart() : editor.getCaretModel().getOffset();
-    final int endOffset = selection ? editor.getSelectionModel().getSelectionEnd() : startOffset;
-    return TemplateManagerImpl.insertDummyIdentifier(file, startOffset, endOffset);
-  }
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java
index 28600b7..6a11b58 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateManagerImpl.java
@@ -24,7 +24,6 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.command.WriteCommandAction;
-import com.intellij.openapi.components.ProjectComponent;
 import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.event.EditorFactoryAdapter;
 import com.intellij.openapi.editor.event.EditorFactoryEvent;
@@ -47,7 +46,7 @@
 
 import java.util.*;
 
-public class TemplateManagerImpl extends TemplateManager implements ProjectComponent, Disposable {
+public class TemplateManagerImpl extends TemplateManager implements Disposable {
   protected Project myProject;
   private boolean myTemplateTesting;
 
@@ -55,26 +54,6 @@
 
   public TemplateManagerImpl(Project project) {
     myProject = project;
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
-  public void dispose() {
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void projectClosed() {
-  }
-
-  @Override
-  public void projectOpened() {
     final EditorFactoryListener myEditorFactoryListener = new EditorFactoryAdapter() {
       @Override
       public void editorReleased(@NotNull EditorFactoryEvent event) {
@@ -91,6 +70,11 @@
     EditorFactory.getInstance().addEditorFactoryListener(myEditorFactoryListener, myProject);
   }
 
+  @Override
+  public void dispose() {
+
+  }
+
   @TestOnly
   @Deprecated
   public void setTemplateTesting(final boolean templateTesting) {
@@ -312,9 +296,8 @@
     return !(customLiveTemplate instanceof CustomLiveTemplateBase) || ((CustomLiveTemplateBase)customLiveTemplate).supportsMultiCaret();
   }
 
-  public static boolean isApplicable(CustomLiveTemplate customLiveTemplate, Editor editor, PsiFile file) {
-    int caretOffset = editor.getCaretModel().getOffset();
-    return customLiveTemplate.isApplicable(file, caretOffset > 0 ? caretOffset - 1 : 0, false);
+  public static boolean isApplicable(@NotNull CustomLiveTemplate customLiveTemplate, @NotNull Editor editor, @NotNull PsiFile file) {
+    return customLiveTemplate.isApplicable(file, Math.max(0, editor.getSelectionModel().getSelectionStart() - 1), false);
   }
 
   private static int getArgumentOffset(int caretOffset, String argument, CharSequence text) {
@@ -542,12 +525,6 @@
   }
 
   @Override
-  @NotNull
-  public String getComponentName() {
-    return "TemplateManager";
-  }
-
-  @Override
   @Nullable
   public Template getActiveTemplate(@NotNull Editor editor) {
     final TemplateState templateState = getTemplateState(editor);
@@ -567,12 +544,29 @@
     return false;
   }
 
-  public static List<TemplateImpl> listApplicableTemplates(PsiFile file, int offset) {
+  public static List<TemplateImpl> listApplicableTemplates(PsiFile file, int offset, boolean selectionOnly) {
     Set<TemplateContextType> contextTypes = getApplicableContextTypes(file, offset);
 
     final ArrayList<TemplateImpl> result = ContainerUtil.newArrayList();
     for (final TemplateImpl template : TemplateSettings.getInstance().getTemplates()) {
-      if (!template.isDeactivated() && isApplicable(template, contextTypes)) {
+      if (!template.isDeactivated() && (!selectionOnly || template.isSelectionTemplate()) && isApplicable(template, contextTypes)) {
+        result.add(template);
+      }
+    }
+    return result;
+  }
+  
+  public static List<TemplateImpl> listApplicableTemplateWithInsertingDummyIdentifier(Editor editor, PsiFile file, boolean selectionOnly) {
+    int startOffset = editor.getSelectionModel().getSelectionStart();
+    file = insertDummyIdentifier(editor, file);
+
+    return listApplicableTemplates(file, startOffset, selectionOnly);
+  }
+
+  public static List<CustomLiveTemplate> listApplicableCustomTemplates(@NotNull Editor editor, @NotNull PsiFile file, boolean selectionOnly) {
+    List<CustomLiveTemplate> result = new ArrayList<CustomLiveTemplate>();
+    for (CustomLiveTemplate template : CustomLiveTemplate.EP_NAME.getExtensions()) {
+      if ((!selectionOnly || template.supportsWrapping()) && isApplicable(template, editor, file)) {
         result.add(template);
       }
     }
@@ -602,6 +596,13 @@
 
     return result;
   }
+  
+  public static PsiFile insertDummyIdentifier(final Editor editor, PsiFile file) {
+    boolean selection = editor.getSelectionModel().hasSelection();
+    final int startOffset = selection ? editor.getSelectionModel().getSelectionStart() : editor.getCaretModel().getOffset();
+    final int endOffset = selection ? editor.getSelectionModel().getSelectionEnd() : startOffset;
+    return insertDummyIdentifier(file, startOffset, endOffset);
+  }
 
   public static PsiFile insertDummyIdentifier(PsiFile file, final int startOffset, final int endOffset) {
     file = (PsiFile)file.copy();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java
index 165e2be..548264e 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/impl/TemplateState.java
@@ -26,6 +26,7 @@
 import com.intellij.openapi.command.CommandAdapter;
 import com.intellij.openapi.command.CommandEvent;
 import com.intellij.openapi.command.CommandProcessor;
+import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.command.undo.BasicUndoableAction;
 import com.intellij.openapi.command.undo.DocumentReference;
 import com.intellij.openapi.command.undo.DocumentReferenceManager;
@@ -116,9 +117,9 @@
       public void commandStarted(CommandEvent event) {
         if (myEditor != null) {
           final int offset = myEditor.getCaretModel().getOffset();
-          myDocumentChangesTerminateTemplate = (myCurrentSegmentNumber >= 0 &&
+          myDocumentChangesTerminateTemplate = myCurrentSegmentNumber >= 0 &&
                                                (offset < mySegments.getSegmentStart(myCurrentSegmentNumber) ||
-                                                offset > mySegments.getSegmentEnd(myCurrentSegmentNumber)));
+                                                offset > mySegments.getSegmentEnd(myCurrentSegmentNumber));
         }
         started = true;
       }
@@ -393,13 +394,8 @@
   }
 
   private String getRangesDebugInfo() {
-    return myTemplateRange.toString() +
-           "\ntemplateKey: " +
-           myTemplate.getKey() +
-           "\ntemplateText: " +
-           myTemplate.getTemplateText() +
-           "\ntemplateString: " +
-           myTemplate.getString();
+    return myTemplateRange + "\ntemplateKey: " + myTemplate.getKey() + "\ntemplateText: " + myTemplate.getTemplateText() +
+           "\ntemplateString: " + myTemplate;
   }
 
   private void doReformat(final TextRange range) {
@@ -479,7 +475,7 @@
     }
 
     String message = template.getKey();
-    if (message == null || message.length() == 0) {
+    if (message == null || message.isEmpty()) {
       message = template.getString();
       if (message == null) {
         message = template.getTemplateText();
@@ -633,7 +629,7 @@
     if (myProcessor != null && myCurrentVariableNumber >= 0) {
       final String variableName = myTemplate.getVariableNameAt(myCurrentVariableNumber);
       final TextResult value = getVariableValue(variableName);
-      if (value != null && value.getText().length() > 0) {
+      if (value != null && !value.getText().isEmpty()) {
         if (!myProcessor.process(variableName, value.getText())) {
           finishTemplateEditing(false); // nextTab(); ?
           return;
@@ -643,7 +639,7 @@
 
     fixOverlappedSegments(myCurrentSegmentNumber);
 
-    ApplicationManager.getApplication().runWriteAction(new Runnable() {
+    WriteCommandAction.runWriteCommandAction(myProject, new Runnable() {
       @Override
       public void run() {
         BitSet calcedSegments = new BitSet();
@@ -1146,7 +1142,7 @@
             final int offset = mySegments.getSegmentStart(endSegmentNumber);
             final int lineStart = myDocument.getLineStartOffset(myDocument.getLineNumber(offset));
             // if $END$ is at line start, put it at correct indentation
-            if (myDocument.getCharsSequence().subSequence(lineStart, offset).toString().trim().length() == 0) {
+            if (myDocument.getCharsSequence().subSequence(lineStart, offset).toString().trim().isEmpty()) {
               final int adjustedOffset = style.adjustLineIndent(file, offset);
               mySegments.replaceSegmentAt(endSegmentNumber, adjustedOffset, adjustedOffset);
             }
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java
index 940f2de..d8a3a82 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ex/GlobalInspectionContextImpl.java
@@ -329,6 +329,7 @@
       tool.inspectionStarted(inspectionManager, this, getPresentation(toolWrapper));
     }
 
+    final boolean headlessEnvironment = ApplicationManager.getApplication().isHeadlessEnvironment();
     final Map<String, InspectionToolWrapper> map = getInspectionWrappersMap(localTools);
     scope.accept(new PsiElementVisitor() {
       @Override
@@ -336,7 +337,7 @@
         final VirtualFile virtualFile = file.getVirtualFile();
         if (virtualFile == null) return;
 
-        if (myView == null) {
+        if (myView == null && !headlessEnvironment) {
           throw new ProcessCanceledException();
         }
 
diff --git a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java
index d33cf8d..d3a1e1c 100644
--- a/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java
+++ b/platform/lang-impl/src/com/intellij/execution/impl/RunManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +20,8 @@
 import com.intellij.execution.*;
 import com.intellij.execution.configurations.*;
 import com.intellij.ide.util.PropertiesComponent;
-import com.intellij.openapi.components.ProjectComponent;
+import com.intellij.openapi.Disposable;
+import com.intellij.openapi.components.NamedComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.project.Project;
@@ -43,7 +44,7 @@
 import java.util.*;
 
 
-public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, ProjectComponent {
+public class RunManagerImpl extends RunManagerEx implements JDOMExternalizable, NamedComponent, Disposable {
   private static final Logger LOG = Logger.getInstance("#com.intellij.execution.impl.RunManagerImpl");
   private final Project myProject;
 
@@ -61,9 +62,9 @@
   @Nullable private String myLoadedSelectedConfigurationUniqueName = null;
   @Nullable private String mySelectedConfigurationId = null;
 
-  private Map<String, Icon> myIdToIcon = new HashMap<String, Icon>();
-  private Map<String, Long> myIconCheckTimes = new HashMap<String, Long>();
-  private Map<String, Long> myIconCalcTime = Collections.synchronizedMap(new HashMap<String, Long>());
+  private final Map<String, Icon> myIdToIcon = new HashMap<String, Icon>();
+  private final Map<String, Long> myIconCheckTimes = new HashMap<String, Long>();
+  private final Map<String, Long> myIconCalcTime = Collections.synchronizedMap(new HashMap<String, Long>());
 
   @NonNls
   protected static final String CONFIGURATION = "configuration";
@@ -78,7 +79,7 @@
   @NonNls private static final String OPTION = "option";
 
   private List<Element> myUnknownElements = null;
-  private JDOMExternalizableStringList myOrder = new JDOMExternalizableStringList();
+  private final JDOMExternalizableStringList myOrder = new JDOMExternalizableStringList();
   private final ArrayList<RunConfiguration> myRecentlyUsedTemporaries = new ArrayList<RunConfiguration>();
   private boolean myOrdered = true;
 
@@ -128,18 +129,6 @@
   }
 
   @Override
-  public void disposeComponent() {
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void projectOpened() {
-  }
-
-  @Override
   @NotNull
   public RunnerAndConfigurationSettings createConfiguration(@NotNull final String name, @NotNull final ConfigurationFactory factory) {
     return createConfiguration(doCreateConfiguration(name, factory, true), factory);
@@ -171,7 +160,7 @@
   }
 
   @Override
-  public void projectClosed() {
+  public void dispose() {
     myTemplateConfigurationsMap.clear();
   }
 
diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java
index bbd24f9..90d2cc6 100644
--- a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java
+++ b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectTask.java
@@ -121,10 +121,15 @@
     try {
       myProgress.setIndeterminate(true);
       myProgress.setText("Scanning indexed files...");
-      final Set<PsiFile> filesForFastWordSearch = getFilesForFastWordSearch();
+      final Set<PsiFile> filesForFastWordSearch = ApplicationManager.getApplication().runReadAction(new Computable<Set<PsiFile>>() {
+        @Override
+        public Set<PsiFile> compute() {
+          return getFilesForFastWordSearch();
+        }
+      });
       myProgress.setIndeterminate(false);
 
-      searchInFiles(consumer, processPresentation, filesForFastWordSearch);
+      searchInFiles(filesForFastWordSearch, processPresentation, consumer);
 
       myProgress.setIndeterminate(true);
       myProgress.setText("Scanning non-indexed files...");
@@ -133,7 +138,7 @@
       myProgress.setIndeterminate(false);
 
       long start = System.currentTimeMillis();
-      searchInFiles(consumer, processPresentation, otherFiles);
+      searchInFiles(otherFiles, processPresentation, consumer);
       if (skipIndexed && otherFiles.size() > 1000) {
         logStats(otherFiles, start);
       }
@@ -177,7 +182,9 @@
     LOG.info(message);
   }
 
-  private void searchInFiles(Processor<UsageInfo> consumer, FindUsagesProcessPresentation processPresentation, Collection<PsiFile> psiFiles) {
+  private void searchInFiles(@NotNull Collection<PsiFile> psiFiles,
+                             @NotNull FindUsagesProcessPresentation processPresentation,
+                             @NotNull Processor<UsageInfo> consumer) {
     int i = 0;
     long totalFilesSize = 0;
     int count = 0;
@@ -233,11 +240,12 @@
       @Override
       public boolean processFile(@NotNull final VirtualFile virtualFile) {
         ApplicationManager.getApplication().runReadAction(new Runnable() {
+          @Override
           public void run() {
             ProgressManager.checkCanceled();
             if (virtualFile.isDirectory() || !virtualFile.isValid() ||
                 !myFileMask.value(virtualFile) ||
-                (globalCustomScope != null && !globalCustomScope.contains(virtualFile))) {
+                globalCustomScope != null && !globalCustomScope.contains(virtualFile)) {
               return;
             }
 
@@ -399,7 +407,10 @@
 
         for (VirtualFile hit : hits) {
           if (myFileMask.value(hit)) {
-            resultFiles.add(findFile(hit));
+            PsiFile file = findFile(hit);
+            if (file != null) {
+              resultFiles.add(file);
+            }
           }
         }
 
@@ -419,8 +430,9 @@
     });
 
     // in case our word splitting is incorrect
-    for (PsiFile file : CacheManager.SERVICE.getInstance(myProject)
-      .getFilesWithWord(stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive())) {
+    CacheManager cacheManager = CacheManager.SERVICE.getInstance(myProject);
+    PsiFile[] filesWithWord = cacheManager.getFilesWithWord(stringToFind, UsageSearchContext.ANY, scope, myFindModel.isCaseSensitive());
+    for (PsiFile file : filesWithWord) {
       if (myFileMask.value(file.getVirtualFile())) {
         resultFiles.add(file);
       }
diff --git a/platform/lang-impl/src/com/intellij/find/ngrams/TrigramIndex.java b/platform/lang-impl/src/com/intellij/find/ngrams/TrigramIndex.java
index b4d9ff4..b572a8f 100644
--- a/platform/lang-impl/src/com/intellij/find/ngrams/TrigramIndex.java
+++ b/platform/lang-impl/src/com/intellij/find/ngrams/TrigramIndex.java
@@ -19,27 +19,35 @@
  */
 package com.intellij.find.ngrams;
 
-import com.intellij.openapi.util.ThreadLocalCachedByteArray;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.util.ThreadLocalCachedIntArray;
 import com.intellij.openapi.util.text.TrigramBuilder;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.impl.cache.impl.id.IdIndex;
+import com.intellij.util.SystemProperties;
 import com.intellij.util.indexing.*;
-import com.intellij.util.io.*;
-import com.intellij.util.io.DataOutputStream;
+import com.intellij.util.io.DataExternalizer;
+import com.intellij.util.io.DataInputOutputUtil;
+import com.intellij.util.io.EnumeratorIntegerDescriptor;
+import com.intellij.util.io.KeyDescriptor;
 import gnu.trove.THashMap;
 import gnu.trove.TIntHashSet;
 import gnu.trove.TIntProcedure;
 import org.jetbrains.annotations.NotNull;
 
-import java.io.*;
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
 import java.util.Collection;
 import java.util.Map;
-import java.util.zip.Deflater;
-import java.util.zip.DeflaterInputStream;
-import java.util.zip.DeflaterOutputStream;
 
 public class TrigramIndex extends ScalarIndexExtension<Integer> implements CustomInputsIndexFileBasedIndexExtension<Integer> {
-  public static final boolean ENABLED = "true".equals(System.getProperty("idea.internal.trigramindex.enabled"));
+  public static final boolean ENABLED = SystemProperties.getBooleanProperty("idea.internal.trigramindex.enabled",
+                                                                            ApplicationManager.getApplication().isInternal() &&
+                                                                            !ApplicationManager.getApplication().isUnitTestMode()
+  );
 
   public static final ID<Integer,Void> INDEX_ID = ID.create("Trigram.Index");
 
@@ -114,57 +122,43 @@
   public boolean hasSnapshotMapping() {
     return true;
   }
-
-  private static final ThreadLocalCachedByteArray spareBufferLocal = new ThreadLocalCachedByteArray();
+  private static final ThreadLocalCachedIntArray spareBufferLocal = new ThreadLocalCachedIntArray();
 
   @NotNull
   @Override
   public DataExternalizer<Collection<Integer>> createExternalizer() {
-    return new InputIndexDataExternalizer<Integer>(getKeyDescriptor(), INDEX_ID) {
+    return new DataExternalizer<Collection<Integer>>() {
       @Override
       public void save(@NotNull DataOutput out, @NotNull Collection<Integer> value) throws IOException {
-        final int maxSerializedLength = 4 * value.size() + 4;
-        byte[] originalBuffer = spareBufferLocal.getBuffer(maxSerializedLength);
-        UnsyncByteArrayOutputStream originalBytes = new UnsyncByteArrayOutputStream(originalBuffer);
-        DataOutputStream originalDataOutput = new DataOutputStream(originalBytes);
+        final int numberOfValues = value.size();
 
-        super.save(originalDataOutput, value);
-        final int size = originalBytes.size();
-        DataInputOutputUtil.writeINT(out, size);
+        int[] buffer = spareBufferLocal.getBuffer(numberOfValues);
+        int ptr = 0;
+        for(Integer i:value) {
+          buffer[ptr++] = i;
+        }
+        Arrays.sort(buffer,0, numberOfValues);
 
-        Deflater deflater = new Deflater(Deflater.HUFFMAN_ONLY);
-        DeflaterOutputStream compressedDeflaterOutput = new DeflaterOutputStream((OutputStream)out, deflater);
-        try {
-          compressedDeflaterOutput.write(originalBuffer, 0, size);
-        } finally {
-          try {
-            compressedDeflaterOutput.close();
-          } catch (IOException ignore) {}
-          deflater.end();
+        DataInputOutputUtil.writeINT(out, numberOfValues);
+        int prev = 0;
+        for(ptr=0; ptr< numberOfValues; ++ptr) {
+          DataInputOutputUtil.writeLONG(out, (long)buffer[ptr] - prev);
+          prev = buffer[ptr];
         }
       }
 
       @NotNull
       @Override
       public Collection<Integer> read(@NotNull DataInput in) throws IOException {
-        byte[] originalBuffer;
-        int size;
-        Deflater deflater = new Deflater(Deflater.HUFFMAN_ONLY);
-        DeflaterInputStream is = new DeflaterInputStream((DataInputStream)in, deflater);
-        try {
-          size = DataInputOutputUtil.readINT(in);
-          originalBuffer = spareBufferLocal.getBuffer(size);
-          //noinspection ResultOfMethodCallIgnored
-          is.read(originalBuffer, 0, size);
+        int size = DataInputOutputUtil.readINT(in);
+        ArrayList<Integer> result = new ArrayList<Integer>(size);
+        int prev = 0;
+        while(size -- > 0) {
+          int l = (int)(DataInputOutputUtil.readLONG(in) + prev);
+          result.add(l);
+          prev = l;
         }
-        finally {
-          try {
-            is.close();
-          } catch (IOException ignore) {}
-          deflater.end();
-        }
-
-        return super.read(new DataInputStream(new UnsyncByteArrayInputStream(originalBuffer, 0, size)));
+        return result;
       }
     };
   }
diff --git a/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java b/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java
index 7d78cf1..e136643 100644
--- a/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java
+++ b/platform/lang-impl/src/com/intellij/formatting/FormatterImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -19,7 +19,6 @@
 import com.intellij.lang.ASTNode;
 import com.intellij.openapi.application.Application;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.fileTypes.FileType;
@@ -47,13 +46,11 @@
 import java.util.concurrent.atomic.AtomicReference;
 
 public class FormatterImpl extends FormatterEx
-  implements ApplicationComponent,
-             IndentFactory,
+  implements IndentFactory,
              WrapFactory,
              AlignmentFactory,
              SpacingFactory,
-             FormattingModelFactory
-{
+             FormattingModelFactory {
   private static final Logger LOG = Logger.getInstance("#com.intellij.formatting.FormatterImpl");
 
   private final AtomicReference<FormattingProgressTask> myProgressTask = new AtomicReference<FormattingProgressTask>();
@@ -798,20 +795,6 @@
   }
 
   @Override
-  @NotNull
-  public String getComponentName() {
-    return "FormatterEx";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   public Indent getAbsoluteNoneIndent() {
     return myAbsoluteNoneIndent;
   }
diff --git a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/DataLanguageBlockWrapper.java b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/DataLanguageBlockWrapper.java
index 08ead45..7a43a18 100644
--- a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/DataLanguageBlockWrapper.java
+++ b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/DataLanguageBlockWrapper.java
@@ -104,6 +104,10 @@
 
   @Override
   public Wrap getWrap() {
+    BlockWithParent parent = getParent();
+    if (parent instanceof TemplateLanguageBlock) {
+      return ((TemplateLanguageBlock)parent).substituteTemplateChildWrap(this, myOriginal.getWrap());
+    }
     return myOriginal.getWrap();
   }
 
diff --git a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java
index e4c8f40..261cdea 100644
--- a/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java
+++ b/platform/lang-impl/src/com/intellij/formatting/templateLanguages/TemplateLanguageBlock.java
@@ -137,7 +137,7 @@
   }
 
   protected Wrap createChildWrap(ASTNode child) {
-    return Wrap.createWrap(Wrap.NONE, false);
+    return Wrap.createWrap(WrapType.NONE, false);
   }
 
   protected Alignment createChildAlignment(ASTNode child) {
@@ -152,5 +152,9 @@
     return myForeignChildren;
   }
 
+  @Nullable
+  public Wrap substituteTemplateChildWrap(@NotNull DataLanguageBlockWrapper child, @Nullable Wrap childWrap) {
+    return childWrap;
+  }
 }
 
diff --git a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java
index 9393ed6..39de59e 100644
--- a/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java
+++ b/platform/lang-impl/src/com/intellij/ide/actions/CreateDirectoryOrPackageHandler.java
@@ -40,6 +40,7 @@
 import javax.swing.*;
 import java.awt.*;
 import java.io.File;
+import java.util.List;
 
 public class CreateDirectoryOrPackageHandler implements InputValidatorEx {
   @Nullable private final Project myProject;
@@ -75,11 +76,14 @@
 
   @Override
   public String getErrorText(String inputString) {
-    if (FileTypeManager.getInstance().isFileIgnored(inputString)) {
-      return "Trying to create a " + (myIsDirectory ? "directory" : "package") + " with ignored name, result will not be visible";
-    }
-    if (!myIsDirectory && inputString.length() > 0 && !PsiDirectoryFactory.getInstance(myProject).isValidPackageName(inputString)) {
-      return "Not a valid package name, it would be impossible to create a class inside";
+    List<String> strings = StringUtil.split(inputString, ".");
+    for (String part : strings) {
+      if (FileTypeManager.getInstance().isFileIgnored(part)) {
+        return "Trying to create a " + (myIsDirectory ? "directory" : "package") + " with ignored name, result will not be visible";
+      }
+      if (!myIsDirectory && part.length() > 0 && !PsiDirectoryFactory.getInstance(myProject).isValidPackageName(part)) {
+        return "Not a valid package name, it would be impossible to create a class inside";
+      }
     }
     return null;
   }
diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/CreateFromTemplateHandler.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/CreateFromTemplateHandler.java
index b0ceafd..dc728e6 100644
--- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/CreateFromTemplateHandler.java
+++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/CreateFromTemplateHandler.java
@@ -21,6 +21,7 @@
 import com.intellij.psi.PsiDirectory;
 import com.intellij.psi.PsiElement;
 import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
 
 import java.util.Map;
 
@@ -31,8 +32,10 @@
   ExtensionPointName<CreateFromTemplateHandler> EP_NAME = ExtensionPointName.create("com.intellij.createFromTemplateHandler");
 
   boolean handlesTemplate(FileTemplate template);
+
+  @NotNull
   PsiElement createFromTemplate(Project project, PsiDirectory directory, final String fileName, FileTemplate template, String templateText,
-                                Map<String, Object> props) throws IncorrectOperationException;
+                                @NotNull Map<String, Object> props) throws IncorrectOperationException;
 
   boolean canCreate(final PsiDirectory[] dirs);
   boolean isNameRequired();
diff --git a/platform/lang-impl/src/com/intellij/ide/fileTemplates/DefaultCreateFromTemplateHandler.java b/platform/lang-impl/src/com/intellij/ide/fileTemplates/DefaultCreateFromTemplateHandler.java
index a97351f..d12e887 100644
--- a/platform/lang-impl/src/com/intellij/ide/fileTemplates/DefaultCreateFromTemplateHandler.java
+++ b/platform/lang-impl/src/com/intellij/ide/fileTemplates/DefaultCreateFromTemplateHandler.java
@@ -27,6 +27,7 @@
 import com.intellij.psi.PsiFileFactory;
 import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
 
 import java.util.Map;
 
@@ -39,10 +40,11 @@
     return true;
   }
 
+  @NotNull
   @Override
   public PsiElement createFromTemplate(final Project project, final PsiDirectory directory, String fileName, final FileTemplate template,
                                        final String templateText,
-                                       final Map<String, Object> props) throws IncorrectOperationException {
+                                       @NotNull final Map<String, Object> props) throws IncorrectOperationException {
     fileName = checkAppendExtension(fileName, template);
 
     if (FileTypeManager.getInstance().isFileIgnored(fileName)) {
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 9e3152f..5fa991f 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
@@ -949,7 +949,7 @@
     final Runnable request = new Runnable() {
       @Override
       public void run() {
-        scheduleCalcElements(text, myCheckBox.isSelected(), postRunnable == null, modalityState, new Consumer<Set<?>>() {
+        scheduleCalcElements(text, myCheckBox.isSelected(), modalityState, new Consumer<Set<?>>() {
           @Override
           public void consume(Set<?> elements) {
             synchronized (myRebuildMutex) {
@@ -986,10 +986,9 @@
 
   public void scheduleCalcElements(String text,
                                    boolean checkboxState,
-                                   boolean canCancel,
                                    ModalityState modalityState,
                                    Consumer<Set<?>> callback) {
-    scheduleCalcElements(new CalcElementsThread(text, checkboxState, callback, modalityState, canCancel, false));
+    scheduleCalcElements(new CalcElementsThread(text, checkboxState, callback, modalityState, false));
   }
 
   private void scheduleCalcElements(final CalcElementsThread thread) {
@@ -1471,25 +1470,23 @@
     private final ModalityState myModalityState;
 
     private final ProgressIndicator myCancelled = new ProgressIndicatorBase();
-    private final boolean myCanCancel;
 
     CalcElementsThread(String pattern,
                        boolean checkboxState,
                        Consumer<Set<?>> callback,
                        @NotNull ModalityState modalityState,
-                       boolean canCancel, boolean scopeExpanded) {
+                       boolean scopeExpanded) {
       myPattern = pattern;
       myCheckboxState = checkboxState;
       myCallback = callback;
       myModalityState = modalityState;
-      myCanCancel = canCancel;
       myScopeExpanded = scopeExpanded;
     }
 
     private final Alarm myShowCardAlarm = new Alarm();
 
     private void scheduleRestart() {
-      scheduleCalcElements(new CalcElementsThread(myPattern, myCheckboxState, myCallback, myModalityState, myCanCancel, myScopeExpanded));
+      scheduleCalcElements(new CalcElementsThread(myPattern, myCheckboxState, myCallback, myModalityState, myScopeExpanded));
     }
 
     @Override
@@ -1608,9 +1605,7 @@
     }
 
     private void cancel() {
-      if (myCanCancel) {
-        myCancelled.cancel();
-      }
+      myCancelled.cancel();
     }
 
   }
@@ -1703,7 +1698,7 @@
               @Override
               public void run() {
                 final boolean[] overFlow = {false};
-                myCalcElementsThread = new CalcElementsThread(text, everywhere, null, ModalityState.NON_MODAL, true, false) {
+                myCalcElementsThread = new CalcElementsThread(text, everywhere, null, ModalityState.NON_MODAL, false) {
                   private final AtomicBoolean userAskedToAbort = new AtomicBoolean();
                   @Override
                   protected boolean isOverflow(@NotNull Set<Object> elementsArray) {
diff --git a/platform/lang-impl/src/com/intellij/lang/customFolding/NetBeansCustomFoldingProvider.java b/platform/lang-impl/src/com/intellij/lang/customFolding/NetBeansCustomFoldingProvider.java
index 4ce8a5a..44f619f 100644
--- a/platform/lang-impl/src/com/intellij/lang/customFolding/NetBeansCustomFoldingProvider.java
+++ b/platform/lang-impl/src/com/intellij/lang/customFolding/NetBeansCustomFoldingProvider.java
@@ -34,7 +34,7 @@
 
   @Override
   public String getPlaceholderText(String elementText) {
-    String customText = elementText.replaceFirst(".*desc\\s*=\\s*\"(.*)\".*", "$1").trim();
+    String customText = elementText.replaceFirst(".*desc\\s*=\\s*\"([^\"]*)\".*", "$1").trim();
     return customText.isEmpty() ? "..." : customText;
   }
 
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/BaseTextWithMarkupCopyPasteProcessor.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/BaseTextWithMarkupCopyPasteProcessor.java
index 434dbec..8132487 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/BaseTextWithMarkupCopyPasteProcessor.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/BaseTextWithMarkupCopyPasteProcessor.java
@@ -16,32 +16,24 @@
 package com.intellij.openapi.editor.richcopy;
 
 import com.intellij.codeInsight.editorActions.CopyPastePostProcessor;
+import com.intellij.codeInsight.editorActions.CopyPastePreProcessor;
 import com.intellij.codeInsight.editorActions.TextBlockTransferableData;
-import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.RangeMarker;
+import com.intellij.openapi.editor.RawText;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import com.intellij.openapi.editor.richcopy.view.RawTextHolder;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.psi.PsiFile;
-import com.intellij.util.StringBuilderSpinAllocator;
-import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.awt.*;
 import java.awt.datatransfer.Transferable;
 
-public abstract class BaseTextWithMarkupCopyPasteProcessor<T extends TextBlockTransferableData> implements CopyPastePostProcessor<T>, TextWithMarkupBuilder {
-  private static final Logger LOG = Logger.getInstance("#" + BaseTextWithMarkupCopyPasteProcessor.class.getName());
-  private static final String TRUNCATED_MESSAGE = "... truncated ...";
-
+public abstract class BaseTextWithMarkupCopyPasteProcessor<T extends RawTextHolder & TextBlockTransferableData>
+  implements CopyPastePostProcessor<T>, TextWithMarkupBuilder {
   private T myData;
-  private int mySizeLimit;
-  protected StringBuilder myBuilder;
-  protected String myDefaultFontFamily;
-  protected Color myDefaultForeground;
-  protected Color myDefaultBackground;
-  protected int myFontSize;
 
   protected BaseTextWithMarkupCopyPasteProcessor(TextWithMarkupProcessor processor) {
     processor.addBuilder(this);
@@ -53,10 +45,7 @@
     if (!Registry.is("editor.richcopy.enable")) {
       return null;
     }
-    releaseBuilder(); // to avoid leakage in case 'complete' method wasn't called due to some exception
-    T data = myData;
-    myData = null;
-    return data;
+    return myData;
   }
 
   @Nullable
@@ -76,58 +65,38 @@
   }
 
   @Override
-  public void init(Color defaultForeground, Color defaultBackground, String defaultFontFamily, int fontSize) {
+  public void build(SyntaxInfo syntaxInfo) {
+    myData = doBuild(syntaxInfo);
+  }
+
+  @Override
+  public void reset() {
     myData = null;
-    myDefaultForeground = defaultForeground;
-    myDefaultBackground = defaultBackground;
-    myDefaultFontFamily = defaultFontFamily;
-    myFontSize = fontSize;
-    allocateBuilder();
-    mySizeLimit = Registry.intValue("editor.richcopy.max.size.megabytes") * 1048576;
-    doInit();
   }
 
-  @Override
-  public boolean isOverflowed() {
-    boolean overflowed = myBuilder.length() > mySizeLimit;
-    if (overflowed) {
-      setFontFamily(myDefaultFontFamily);
-      setForeground(myDefaultForeground);
-      setBackground(myDefaultBackground);
-      addTextFragment(TRUNCATED_MESSAGE, 0, TRUNCATED_MESSAGE.length());
+  protected abstract T doBuild(SyntaxInfo info);
+
+  public static class RawTextSetter implements CopyPastePreProcessor {
+    private final BaseTextWithMarkupCopyPasteProcessor myProcessor;
+
+    public RawTextSetter(BaseTextWithMarkupCopyPasteProcessor processor) {
+      myProcessor = processor;
     }
-    return overflowed;
-  }
 
-  @Override
-  public void complete() {
-    try {
-      doComplete();
-      String data = myBuilder.toString();
-      if (Registry.is("editor.richcopy.debug")) {
-        LOG.info("Resulting text: \n" + data);
+    @Override
+    @Nullable
+    public String preprocessOnCopy(final PsiFile file, final int[] startOffsets, final int[] endOffsets, String text) {
+      if (myProcessor.myData != null) {
+        myProcessor.myData.setRawText(text);
+        myProcessor.myData = null;
       }
-      myData = createTransferable(data);
+      return null; // noop
     }
-    finally {
-      releaseBuilder();
+
+    @Override
+    public String preprocessOnPaste(final Project project, final PsiFile file, final Editor editor, String text, final RawText rawText) {
+      return text; // noop
     }
   }
 
-  protected abstract T createTransferable(@NotNull String data);
-  protected abstract void doInit();
-  protected abstract void doComplete();
-
-  private void allocateBuilder() {
-    if (myBuilder == null) {
-      myBuilder = StringBuilderSpinAllocator.alloc();
-    }
-  }
-
-  private void releaseBuilder() {
-    if (myBuilder != null) {
-      StringBuilderSpinAllocator.dispose(myBuilder);
-      myBuilder = null;
-    }
-  }
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/HtmlCopyPasteProcessor.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/HtmlCopyPasteProcessor.java
index 9456947..4805568 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/HtmlCopyPasteProcessor.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/HtmlCopyPasteProcessor.java
@@ -15,184 +15,27 @@
  */
 package com.intellij.openapi.editor.richcopy;
 
-import com.intellij.openapi.editor.richcopy.view.ReaderTransferableData;
-import com.intellij.util.StringBuilderSpinAllocator;
-import com.intellij.util.ui.UIUtil;
-import org.jetbrains.annotations.NotNull;
-
-import java.awt.*;
-import java.awt.datatransfer.DataFlavor;
-import java.util.HashMap;
-import java.util.Map;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import com.intellij.openapi.editor.richcopy.view.HtmlTransferableData;
 
 /**
  * @author Denis Zhdanov
  * @since 3/28/13 1:05 PM
  */
-public class HtmlCopyPasteProcessor extends BaseTextWithMarkupCopyPasteProcessor<ReaderTransferableData> {
-  @NotNull public static final DataFlavor FLAVOR = new DataFlavor("text/html;class=java.io.Reader", "HTML text");
-
-  private Map<Color, String> myRenderedColors = new HashMap<Color, String>();
-
-  private Color   myForeground;
-  private Color   myBackground;
-  private String  myFontFamily;
-  private boolean myBold;
-  private boolean myItalic;
-
+public class HtmlCopyPasteProcessor extends BaseTextWithMarkupCopyPasteProcessor<HtmlTransferableData> {
   public HtmlCopyPasteProcessor(TextWithMarkupProcessor processor) {
     super(processor);
   }
 
   @Override
-  protected void doInit() {
-    myForeground = null;
-    myBackground = null;
-    myFontFamily = null;
-    myBold = false;
-    myItalic = false;
-    myBuilder.append("<div style=\"border:1px inset;padding:2%;\"><pre style=\"margin:0;padding:6px;background-color:");
-    appendColor(myBuilder, myDefaultBackground);
-    myBuilder.append(';');
-    appendFontFamilyRule(myBuilder, myDefaultFontFamily);
-    myBuilder.append("font-size:").append(myFontSize).append("pt;");
-    myBuilder.append("\" bgcolor=\"");
-    appendColor(myBuilder, myDefaultBackground);
-    myBuilder.append("\">");
+  protected HtmlTransferableData doBuild(SyntaxInfo info) {
+    return new HtmlTransferableData(info);
   }
 
-  @Override
-  protected void doComplete() {
-    myBuilder.append("</pre></div>");
-  }
-
-  @Override
-  public void setFontFamily(String fontFamily) {
-    myFontFamily = myDefaultFontFamily.equals(fontFamily) ? null : fontFamily;
-  }
-
-  @Override
-  public void setFontStyle(int fontStyle) {
-    myBold = (Font.BOLD & fontStyle) != 0;
-    myItalic = (Font.ITALIC & fontStyle) != 0;
-  }
-
-  @Override
-  public void setForeground(Color foreground) {
-    myForeground = foreground;
-  }
-
-  @Override
-  public void setBackground(Color background) {
-    myBackground = myDefaultBackground.equals(background) ? null : background;
-  }
-
-  @Override
-  public void addTextFragment(CharSequence charSequence, int startOffset, int endOffset) {
-    boolean formattedText = myForeground != null || myBackground != null || myFontFamily != null || myBold || myItalic;
-    if (!formattedText) {
-      escapeAndAdd(charSequence, startOffset, endOffset);
-      return;
+  @SuppressWarnings("ClassNameSameAsAncestorName")
+  public static class RawTextSetter extends BaseTextWithMarkupCopyPasteProcessor.RawTextSetter {
+    public RawTextSetter(HtmlCopyPasteProcessor processor) {
+      super(processor);
     }
-
-    StringBuilder styleBuffer = StringBuilderSpinAllocator.alloc();
-    StringBuilder closeTagBuffer = StringBuilderSpinAllocator.alloc();
-    try {
-      if (myForeground != null) {
-        defineForeground(myForeground, styleBuffer, closeTagBuffer);
-      }
-      if (myBackground != null) {
-        defineBackground(myBackground, styleBuffer, closeTagBuffer);
-      }
-      if (myBold) {
-        defineBold(styleBuffer, closeTagBuffer);
-      }
-      if (myItalic) {
-        defineItalic(styleBuffer, closeTagBuffer);
-      }
-      if (myFontFamily != null) {
-        appendFontFamilyRule(styleBuffer, myFontFamily);
-      }
-      myBuilder.append("<span style=\"");
-      myBuilder.append(styleBuffer);
-      myBuilder.append("\">");
-      escapeAndAdd(charSequence, startOffset, endOffset);
-      myBuilder.append("</span>");
-      myBuilder.append(closeTagBuffer);
-    }
-    finally {
-      StringBuilderSpinAllocator.dispose(styleBuffer);
-      StringBuilderSpinAllocator.dispose(closeTagBuffer);
-    }
-  }
-
-  private void defineForeground(Color foreground, @NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
-    myBuilder.append("<font color=\"");
-    appendColor(myBuilder, foreground);
-    myBuilder.append("\">");
-    styleBuffer.append("color:");
-    appendColor(styleBuffer, foreground);
-    styleBuffer.append(";");
-    closeTagBuffer.insert(0, "</font>");
-  }
-
-  private void defineBackground(Color background, @NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
-    myBuilder.append("<font bgcolor=\"");
-    appendColor(myBuilder, background);
-    myBuilder.append("\">");
-    styleBuffer.append("background-color:");
-    appendColor(styleBuffer, background);
-    styleBuffer.append(";");
-    closeTagBuffer.insert(0, "</font>");
-  }
-
-  private void defineBold(@NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
-    myBuilder.append("<b>");
-    styleBuffer.append("font-weight:bold;");
-    closeTagBuffer.insert(0, "</b>");
-  }
-
-  private void defineItalic(@NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
-    myBuilder.append("<i>");
-    styleBuffer.append("font-style:italic;");
-    closeTagBuffer.insert(0, "</i>");
-  }
-
-  private void appendColor(StringBuilder builder, Color color) {
-    String colorAsString = myRenderedColors.get(color);
-    if (colorAsString == null) {
-      StringBuilder b = StringBuilderSpinAllocator.alloc();
-      try {
-        b.append('#');
-        UIUtil.appendColor(color, b);
-        colorAsString = b.toString();
-        myRenderedColors.put(color, colorAsString);
-      }
-      finally {
-        StringBuilderSpinAllocator.dispose(b);
-      }
-    }
-    builder.append(colorAsString);
-  }
-
-  private static void appendFontFamilyRule(@NotNull StringBuilder styleBuffer, String fontFamily) {
-    styleBuffer.append("font-family:'").append(fontFamily).append("';");
-  }
-
-  private void escapeAndAdd(CharSequence charSequence, int start, int end) {
-    for (int i = start; i < end; i++) {
-      char c = charSequence.charAt(i);
-      switch (c) {
-        case '<': myBuilder.append("&lt;"); break;
-        case '>': myBuilder.append("&gt;"); break;
-        case '&': myBuilder.append("&amp;"); break;
-        default: myBuilder.append(c);
-      }
-    }
-  }
-
-  @Override
-  protected ReaderTransferableData createTransferable(@NotNull String data) {
-    return new ReaderTransferableData(data, FLAVOR);
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/RtfCopyPasteProcessor.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/RtfCopyPasteProcessor.java
index 2a59e40..be559b5 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/RtfCopyPasteProcessor.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/RtfCopyPasteProcessor.java
@@ -15,184 +15,27 @@
  */
 package com.intellij.openapi.editor.richcopy;
 
-import com.intellij.openapi.editor.richcopy.model.*;
-import com.intellij.openapi.editor.richcopy.view.InputStreamTransferableData;
-import com.intellij.util.StringBuilderSpinAllocator;
-import org.jetbrains.annotations.NotNull;
-
-import java.awt.*;
-import java.awt.datatransfer.DataFlavor;
-import java.io.UnsupportedEncodingException;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import com.intellij.openapi.editor.richcopy.view.RtfTransferableData;
 
 /**
  * @author Denis Zhdanov
  * @since 3/25/13 2:18 PM
  */
-public class RtfCopyPasteProcessor extends BaseTextWithMarkupCopyPasteProcessor<InputStreamTransferableData> {
-  @NotNull public static final DataFlavor FLAVOR = new DataFlavor("text/rtf;class=java.io.InputStream", "RTF text");
-
-  private static final String CHARSET = "US-ASCII";
-
-  @NotNull private static final String HEADER_PREFIX = "{\\rtf1\\ansi\\deff0";
-  @NotNull private static final String HEADER_SUFFIX = "}";
-  @NotNull private static final String TAB           = "\\tab\n";
-  @NotNull private static final String NEW_LINE      = "\\line\n";
-  @NotNull private static final String BOLD          = "\\b";
-  @NotNull private static final String ITALIC        = "\\i";
-  @NotNull private static final String PLAIN         = "\\plain\n";
-
-  private int myBackgroundId;
-  private int myForegroundId;
-  private int myFontNameId;
-  private ColorRegistry myColorRegistry;
-  private FontNameRegistry myFontNameRegistry;
-
+public class RtfCopyPasteProcessor extends BaseTextWithMarkupCopyPasteProcessor<RtfTransferableData> {
   public RtfCopyPasteProcessor(TextWithMarkupProcessor processor) {
     super(processor);
   }
 
   @Override
-  protected void doInit() {
-    myBackgroundId = -1;
-    myForegroundId = -1;
-    myFontNameId   = -1;
-    myColorRegistry = new ColorRegistry();
-    myFontNameRegistry = new FontNameRegistry();
-
-    int defaultForegroundId = myColorRegistry.getId(myDefaultForeground);
-    int defaultBackgroundId = myColorRegistry.getId(myDefaultBackground);
-
-    myBuilder.append("\n\\s0\\box\\brdrhair\\brdrcf").append(defaultForegroundId).append("\\brsp317").append("\\cbpat").append(defaultBackgroundId);
-    saveBackground(defaultBackgroundId);
+  protected RtfTransferableData doBuild(SyntaxInfo info) {
+    return new RtfTransferableData(info);
   }
 
-  @Override
-  protected void doComplete() {
-    StringBuilder builder = StringBuilderSpinAllocator.alloc();
-    try {
-      builder.append(HEADER_PREFIX);
-
-      // Color table.
-      builder.append("{\\colortbl;");
-      for (int id : myColorRegistry.getAllIds()) {
-        Color color = myColorRegistry.dataById(id);
-        builder.append(String.format("\\red%d\\green%d\\blue%d;", color.getRed(), color.getGreen(), color.getBlue()));
-      }
-      builder.append("}\n");
-
-      // Font table.
-      builder.append("{\\fonttbl");
-      for (int id : myFontNameRegistry.getAllIds()) {
-        String fontName = myFontNameRegistry.dataById(id);
-        builder.append(String.format("{\\f%d %s;}", id, fontName));
-      }
-      builder.append("}\n");
-
-      myBuilder.insert(0, builder);
+  @SuppressWarnings("ClassNameSameAsAncestorName")
+  public static class RawTextSetter extends BaseTextWithMarkupCopyPasteProcessor.RawTextSetter {
+    public RawTextSetter(RtfCopyPasteProcessor processor) {
+      super(processor);
     }
-    finally {
-      StringBuilderSpinAllocator.dispose(builder);
-    }
-    myBuilder.append("\\par");
-    myBuilder.append(HEADER_SUFFIX);
-  }
-
-  @Override
-  public void setFontFamily(String fontFamily) {
-    int id = myFontNameRegistry.getId(fontFamily);
-    saveFontName(id);
-    myFontNameId = id;
-  }
-
-  @Override
-  public void setFontStyle(int fontStyle) {
-    // Reset formatting settings
-    myBuilder.append(PLAIN);
-
-    // Restore target formatting settings.
-    if (myForegroundId >= 0) {
-      saveForeground(myForegroundId);
-    }
-    if (myBackgroundId >= 0) {
-      saveBackground(myBackgroundId);
-    }
-    if (myFontNameId >= 0) {
-      saveFontName(myFontNameId);
-    }
-    saveFontSize(myFontSize);
-
-    if ((fontStyle & Font.ITALIC) > 0) {
-      myBuilder.append(ITALIC);
-    }
-    if ((fontStyle & Font.BOLD) > 0) {
-      myBuilder.append(BOLD);
-    }
-  }
-
-  @Override
-  public void setForeground(Color foreground) {
-    int id = myColorRegistry.getId(foreground);
-    saveForeground(id);
-    myForegroundId = id;
-  }
-
-  @Override
-  public void setBackground(Color background) {
-    int id = myColorRegistry.getId(background);
-    saveBackground(id);
-    myBackgroundId = id;
-  }
-
-  @Override
-  public void addTextFragment(CharSequence charSequence, int startOffset, int endOffset) {
-    myBuilder.append("\n");
-    for (int i = startOffset; i < endOffset; i++) {
-      char c = charSequence.charAt(i);
-      if (c > 127) {
-        // Escape non-ascii symbols.
-        myBuilder.append(String.format("\\u%04d?", (int)c));
-        continue;
-      }
-
-      switch (c) {
-        case '\t':
-          myBuilder.append(TAB);
-          continue;
-        case '\n':
-          myBuilder.append(NEW_LINE);
-          continue;
-        case '\\':
-        case '{':
-        case '}':
-          myBuilder.append('\\');
-      }
-      myBuilder.append(c);
-    }
-  }
-
-  @Override
-  protected InputStreamTransferableData createTransferable(@NotNull String data) {
-    try {
-      return new InputStreamTransferableData(data.getBytes(CHARSET), FLAVOR);
-    }
-    catch (UnsupportedEncodingException e) {
-      throw new RuntimeException(e); // shouldn't happen
-    }
-  }
-
-  private void saveBackground(int id) {
-    myBuilder.append("\\cb").append(id);
-  }
-
-  private void saveForeground(int id) {
-    myBuilder.append("\\cf").append(id);
-  }
-
-  private void saveFontName(int id) {
-    myBuilder.append("\\f").append(id);
-  }
-
-  private void saveFontSize(int size) {
-    myBuilder.append("\\fs").append(size * 2);
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupBuilder.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupBuilder.java
index 813a62a..063d7d9 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupBuilder.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupBuilder.java
@@ -15,17 +15,9 @@
  */
 package com.intellij.openapi.editor.richcopy;
 
-import java.awt.*;
-import java.util.EventListener;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
 
-// we're extending EventListener to be able to use EventDispatcher in TextWithMarkupProcessor
-public interface TextWithMarkupBuilder extends EventListener {
-  void init(Color defaultForeground, Color defaultBackground, String defaultFontFamily, int fontSize);
-  boolean isOverflowed();
-  void setFontFamily(String fontFamily);
-  void setFontStyle(int fontStyle);
-  void setForeground(Color foreground);
-  void setBackground(Color background);
-  void addTextFragment(CharSequence charSequence, int startOffset, int endOffset);
-  void complete();
+public interface TextWithMarkupBuilder {
+  void reset();
+  void build(SyntaxInfo syntaxInfo);
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupProcessor.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupProcessor.java
index 7829c92..da8c1f0 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupProcessor.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/TextWithMarkupProcessor.java
@@ -21,9 +21,7 @@
 import com.intellij.codeInsight.editorActions.TextBlockTransferableData;
 import com.intellij.ide.highlighter.HighlighterFactory;
 import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.editor.RangeMarker;
+import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.colors.EditorColorsScheme;
 import com.intellij.openapi.editor.colors.TextAttributesKey;
 import com.intellij.openapi.editor.ex.DisposableIterator;
@@ -33,9 +31,11 @@
 import com.intellij.openapi.editor.highlighter.HighlighterIterator;
 import com.intellij.openapi.editor.impl.ComplementaryFontsRegistry;
 import com.intellij.openapi.editor.impl.DocumentMarkupModel;
+import com.intellij.openapi.editor.impl.FontInfo;
 import com.intellij.openapi.editor.markup.HighlighterLayer;
 import com.intellij.openapi.editor.markup.MarkupModel;
 import com.intellij.openapi.editor.markup.TextAttributes;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
 import com.intellij.openapi.editor.richcopy.settings.RichCopySettings;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Pair;
@@ -43,24 +43,24 @@
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.TokenType;
-import com.intellij.util.EventDispatcher;
-import com.intellij.util.containers.ContainerUtilRt;
+import com.intellij.util.text.CharArrayUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.awt.*;
 import java.awt.datatransfer.Transferable;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Comparator;
 import java.util.List;
-import java.util.Queue;
 
 public class TextWithMarkupProcessor implements CopyPastePostProcessor<TextBlockTransferableData> {
   private static final Logger LOG = Logger.getInstance("#" + TextWithMarkupProcessor.class.getName());
 
-  private final EventDispatcher<TextWithMarkupBuilder> myBuilders = EventDispatcher.create(TextWithMarkupBuilder.class);
+  private final List<TextWithMarkupBuilder> myBuilders = new ArrayList<TextWithMarkupBuilder>();
 
   public void addBuilder(TextWithMarkupBuilder builder) {
-    myBuilders.addListener(builder);
+    myBuilders.add(builder);
   }
 
   @Nullable
@@ -71,78 +71,82 @@
     }
 
     try {
+      for (TextWithMarkupBuilder builder : myBuilders) {
+        builder.reset();
+      }
+      SelectionModel selectionModel = editor.getSelectionModel();
+      if (selectionModel.hasBlockSelection()) {
+        return null; // unsupported legacy mode
+      }
+
       RichCopySettings settings = RichCopySettings.getInstance();
-      Document document = editor.getDocument();
+      List<Caret> carets = editor.getCaretModel().getAllCarets();
+      Caret firstCaret = carets.get(0);
       final int indentSymbolsToStrip;
       final int firstLineStartOffset;
-      if (settings.isStripIndents() && startOffsets.length == 1) {
-        Pair<Integer, Integer> p = calcIndentSymbolsToStrip(document, startOffsets[0], endOffsets[0]);
+      if (Registry.is("editor.richcopy.strip.indents") && carets.size() == 1) {
+        Pair<Integer, Integer> p = calcIndentSymbolsToStrip(editor.getDocument(), firstCaret.getSelectionStart(), firstCaret.getSelectionEnd());
         firstLineStartOffset = p.first;
         indentSymbolsToStrip = p.second;
       }
       else {
-        firstLineStartOffset = startOffsets[0];
+        firstLineStartOffset = firstCaret.getSelectionStart();
         indentSymbolsToStrip = 0;
       }
-      logInitial(document, startOffsets, endOffsets, indentSymbolsToStrip, firstLineStartOffset);
-      CharSequence text = document.getCharsSequence();
+      logInitial(editor, startOffsets, endOffsets, indentSymbolsToStrip, firstLineStartOffset);
+      CharSequence text = editor.getDocument().getCharsSequence();
       EditorColorsScheme schemeToUse = settings.getColorsScheme(editor.getColorsScheme());
       EditorHighlighter highlighter = HighlighterFactory.createHighlighter(file.getVirtualFile(), schemeToUse, file.getProject());
       highlighter.setText(text);
-      MarkupModel markupModel = DocumentMarkupModel.forDocument(document, file.getProject(), false);
+      MarkupModel markupModel = DocumentMarkupModel.forDocument(editor.getDocument(), file.getProject(), false);
+      Context context = new Context(text, schemeToUse, indentSymbolsToStrip);
+      int shift = 0;
+      int endOffset = 0;
+      Caret prevCaret = null;
 
-      myBuilders.getMulticaster().init(schemeToUse.getDefaultForeground(),
-                                       schemeToUse.getDefaultBackground(),
-                                       FontMapper.getPhysicalFontName(schemeToUse.getEditorFontName()),
-                                       schemeToUse.getEditorFontSize());
-
-      EventDispatcher<TextWithMarkupBuilder> activeBuilders = EventDispatcher.create(TextWithMarkupBuilder.class);
-      activeBuilders.getListeners().addAll(myBuilders.getListeners());
-      Context context = new Context(activeBuilders.getMulticaster(), text, schemeToUse, indentSymbolsToStrip);
-
-      outer:
-      for (int i = 0; i < startOffsets.length; i++) {
+      for (Caret caret : carets) {
+        int caretSelectionStart = caret.getSelectionStart();
+        int caretSelectionEnd = caret.getSelectionEnd();
         int startOffsetToUse;
-        if (i == 0) {
+        if (caret == firstCaret) {
           startOffsetToUse = firstLineStartOffset;
         }
         else {
-          startOffsetToUse = startOffsets[i];
-          activeBuilders.getMulticaster().addTextFragment("\n", 0, 1);
+          startOffsetToUse = caretSelectionStart;
+          assert prevCaret != null;
+          String prevCaretSelectedText = prevCaret.getSelectedText();
+          // Block selection fills short lines by white spaces.
+          int fillStringLength = prevCaretSelectedText == null ? 0 : prevCaretSelectedText.length() - (prevCaret.getSelectionEnd() - prevCaret.getSelectionStart());
+          int endLineOffset = endOffset + shift + fillStringLength;
+          context.builder.addText(endLineOffset, endLineOffset + 1);
+          shift++; // Block selection ends '\n' at line end
+          shift += fillStringLength;
         }
-        int endOffsetToUse = endOffsets[i];
-        context.reset();
-        if (endOffsetToUse <= startOffsetToUse) {
+        shift += endOffset - caretSelectionStart;
+        endOffset = caretSelectionEnd;
+        context.reset(shift);
+        prevCaret = caret;
+        if (endOffset <= startOffsetToUse) {
           continue;
         }
-        DisposableIterator<SegmentInfo> it = aggregateSyntaxInfo(schemeToUse,
-                                                                 wrap(highlighter, text, schemeToUse, startOffsetToUse, endOffsetToUse),
-                                                                 wrap(markupModel, text, schemeToUse, startOffsetToUse, endOffsetToUse));
+        MarkupIterator markupIterator = new MarkupIterator(text,
+                                                           new CompositeRangeIterator(schemeToUse,
+                                                                                      new HighlighterRangeIterator(highlighter, startOffsetToUse, endOffset),
+                                                                                      new MarkupModelRangeIterator(markupModel, schemeToUse, startOffsetToUse, endOffset)),
+                                                           schemeToUse);
         try {
-          while (it.hasNext()) {
-            Iterator<TextWithMarkupBuilder> builderIterator = activeBuilders.getListeners().iterator();
-            while (builderIterator.hasNext()) {
-              if (builderIterator.next().isOverflowed()) {
-                builderIterator.remove();
-                if (activeBuilders.getListeners().isEmpty()) {
-                  break outer;
-                }
-              }
-            }
-            SegmentInfo info = it.next();
-            if (info.startOffset >= endOffsetToUse) {
-              break;
-            }
-            context.onNewData(info);
-          }
+          context.iterate(markupIterator, endOffset);
         }
         finally {
-          it.dispose();
+          markupIterator.dispose();
         }
-        context.onIterationEnd(endOffsetToUse);
       }
+      SyntaxInfo syntaxInfo = context.finish();
+      logSyntaxInfo(syntaxInfo);
 
-      myBuilders.getMulticaster().complete();
+      for (TextWithMarkupBuilder builder : myBuilders) {
+        builder.build(syntaxInfo);
+      }
     }
     catch (Exception e) {
       // catching the exception so that the rest of copy/paste functionality can still work fine
@@ -167,7 +171,7 @@
 
   }
 
-  private static void logInitial(@NotNull Document document,
+  private static void logInitial(@NotNull Editor editor,
                                  @NotNull int[] startOffsets,
                                  @NotNull int[] endOffsets,
                                  int indentSymbolsToStrip,
@@ -178,6 +182,7 @@
     }
 
     StringBuilder buffer = new StringBuilder();
+    Document document = editor.getDocument();
     CharSequence text = document.getCharsSequence();
     for (int i = 0; i < startOffsets.length; i++) {
       int start = startOffsets[i];
@@ -196,6 +201,13 @@
     ));
   }
 
+  private static void logSyntaxInfo(@NotNull SyntaxInfo info) {
+    if (!Registry.is("editor.richcopy.debug")) {
+      return;
+    }
+    LOG.info("Constructed syntax info: " + info);
+  }
+
   private static Pair<Integer/* start offset to use */, Integer /* indent symbols to strip */> calcIndentSymbolsToStrip(
     @NotNull Document document, int startOffset, int endOffset)
   {
@@ -233,267 +245,10 @@
     return Pair.create(startOffsetToUse, maximumCommonIndent);
   }
 
-  private static DisposableIterator<SegmentInfo> aggregateSyntaxInfo(@NotNull EditorColorsScheme colorsScheme,
-                                                                     @NotNull final DisposableIterator<List<SegmentInfo>>... iterators)
-  {
-    final Color defaultForeground = colorsScheme.getDefaultForeground();
-    final Color defaultBackground = colorsScheme.getDefaultBackground();
-    return new DisposableIterator<SegmentInfo>() {
-
-      @NotNull private final Queue<SegmentInfo> myInfos = new PriorityQueue<SegmentInfo>();
-      @NotNull private final Map<SegmentInfo, DisposableIterator<List<SegmentInfo>>> myEndMarkers
-        = new IdentityHashMap<SegmentInfo, DisposableIterator<List<SegmentInfo>>>();
-
-      {
-        for (DisposableIterator<List<SegmentInfo>> iterator : iterators) {
-          extract(iterator);
-        }
-      }
-
-      @Override
-      public boolean hasNext() {
-        return !myInfos.isEmpty();
-      }
-
-      @Override
-      public SegmentInfo next() {
-        SegmentInfo result = myInfos.remove();
-        DisposableIterator<List<SegmentInfo>> iterator = myEndMarkers.remove(result);
-        if (iterator != null) {
-          extract(iterator);
-        }
-        while (!myInfos.isEmpty()) {
-          SegmentInfo toMerge = myInfos.peek();
-          if (toMerge.endOffset > result.endOffset) {
-            break;
-          }
-          myInfos.remove();
-          result = merge(result, toMerge);
-          DisposableIterator<List<SegmentInfo>> it = myEndMarkers.remove(toMerge);
-          if (it != null) {
-            extract(it);
-          }
-        }
-        return result;
-      }
-
-      @NotNull
-      private SegmentInfo merge(@NotNull SegmentInfo info1, @NotNull SegmentInfo info2) {
-        Color background = info1.background;
-        if (background == null || defaultBackground.equals(background)) {
-          background = info2.background;
-        }
-
-        Color foreground = info1.foreground;
-        if (foreground == null || defaultForeground.equals(foreground)) {
-          foreground = info2.foreground;
-        }
-
-        int fontStyle = info1.fontStyle;
-        if (fontStyle == Font.PLAIN) {
-          fontStyle = info2.fontStyle;
-        }
-        return new SegmentInfo(foreground, background, info1.fontFamilyName, fontStyle, info1.startOffset, info1.endOffset);
-      }
-
-      @Override
-      public void remove() {
-        throw new UnsupportedOperationException();
-      }
-
-      @Override
-      public void dispose() {
-        for (DisposableIterator<List<SegmentInfo>> iterator : iterators) {
-          iterator.dispose();
-        }
-      }
-
-      private void extract(@NotNull DisposableIterator<List<SegmentInfo>> iterator) {
-        while (iterator.hasNext()) {
-          List<SegmentInfo> infos = iterator.next();
-          if (infos.isEmpty()) {
-            continue;
-          }
-          myInfos.addAll(infos);
-          myEndMarkers.put(infos.get(infos.size() - 1), iterator);
-          break;
-        }
-      }
-    };
-  }
-
-  @NotNull
-  private static DisposableIterator<List<SegmentInfo>> wrap(@NotNull final EditorHighlighter highlighter,
-                                                            @NotNull final CharSequence text,
-                                                            @NotNull final EditorColorsScheme colorsScheme,
-                                                            final int startOffset,
-                                                            final int endOffset)
-  {
-    final HighlighterIterator highlighterIterator = highlighter.createIterator(startOffset);
-    return new DisposableIterator<List<SegmentInfo>>() {
-
-      @Nullable private List<SegmentInfo> myCached;
-
-      @Override
-      public boolean hasNext() {
-        return myCached != null || updateCached();
-      }
-
-      @Override
-      public List<SegmentInfo> next() {
-        if (myCached != null) {
-          List<SegmentInfo> result = myCached;
-          myCached = null;
-          return result;
-        }
-
-        if (!updateCached()) {
-          throw new UnsupportedOperationException();
-        }
-        return myCached;
-      }
-
-      @Override
-      public void remove() {
-        throw new UnsupportedOperationException();
-      }
-
-      @Override
-      public void dispose() {
-      }
-
-      private boolean updateCached() {
-        if (highlighterIterator.atEnd()) {
-          return false;
-        }
-        int tokenStart = Math.max(highlighterIterator.getStart(), startOffset);
-        if (tokenStart >= endOffset) {
-          return false;
-        }
-
-        if (highlighterIterator.getTokenType() == TokenType.BAD_CHARACTER) {
-          // Skip syntax errors.
-          highlighterIterator.advance();
-          return updateCached();
-        }
-        TextAttributes attributes = highlighterIterator.getTextAttributes();
-        int tokenEnd = Math.min(highlighterIterator.getEnd(), endOffset);
-        myCached = SegmentInfo.produce(attributes, text, colorsScheme, tokenStart, tokenEnd);
-        highlighterIterator.advance();
-        return true;
-      }
-    };
-  }
-
-  @SuppressWarnings("unchecked")
-  @NotNull
-  private static DisposableIterator<List<SegmentInfo>> wrap(@NotNull MarkupModel model,
-                                                            @NotNull final CharSequence charSequence,
-                                                            @NotNull final EditorColorsScheme colorsScheme,
-                                                            final int startOffset,
-                                                            final int endOffset)
-  {
-    if (!(model instanceof MarkupModelEx)) {
-      return DisposableIterator.EMPTY;
-    }
-    final DisposableIterator<RangeHighlighterEx> iterator = ((MarkupModelEx)model).overlappingIterator(startOffset, endOffset);
-    final Color defaultForeground = colorsScheme.getDefaultForeground();
-    final Color defaultBackground = colorsScheme.getDefaultBackground();
-    return new DisposableIterator<List<SegmentInfo>>() {
-
-      @Nullable private List<SegmentInfo> myCached;
-
-      @Override
-      public boolean hasNext() {
-        return myCached != null || updateCached();
-      }
-
-      @Override
-      public List<SegmentInfo> next() {
-        if (myCached != null) {
-          List<SegmentInfo> result = myCached;
-          myCached = null;
-          return result;
-        }
-
-        if (!updateCached()) {
-          throw new UnsupportedOperationException();
-        }
-        return myCached;
-      }
-
-      @Override
-      public void remove() {
-        throw new UnsupportedOperationException();
-      }
-
-      @Override
-      public void dispose() {
-        iterator.dispose();
-      }
-
-      private boolean updateCached() {
-        if (!iterator.hasNext()) {
-          return false;
-        }
-
-        RangeHighlighterEx highlighter = iterator.next();
-        while (highlighter == null
-               || !highlighter.isValid()
-               || !isInterestedHighlightLayer(highlighter.getLayer()))
-        {
-          if (!iterator.hasNext()) {
-            return false;
-          }
-          highlighter = iterator.next();
-        }
-
-        int tokenStart = Math.max(highlighter.getStartOffset(), startOffset);
-        if (tokenStart >= endOffset) {
-          return false;
-        }
-
-        TextAttributes attributes = null;
-        Object tooltip = highlighter.getErrorStripeTooltip();
-        if (tooltip instanceof HighlightInfo) {
-          HighlightInfo info = (HighlightInfo)tooltip;
-          TextAttributesKey key = info.forcedTextAttributesKey;
-          if (key == null) {
-            HighlightInfoType type = info.type;
-            key = type.getAttributesKey();
-          }
-          if (key != null) {
-            attributes = colorsScheme.getAttributes(key);
-          }
-        }
-
-        if (attributes == null) {
-          return updateCached();
-        }
-        Color foreground = attributes.getForegroundColor();
-        Color background = attributes.getBackgroundColor();
-        if ((foreground == null || defaultForeground.equals(foreground))
-            && (background == null || defaultBackground.equals(background))
-            && attributes.getFontType() == Font.PLAIN)
-        {
-          return updateCached();
-        }
-
-        int tokenEnd = Math.min(highlighter.getEndOffset(), endOffset);
-        //noinspection ConstantConditions
-        myCached = SegmentInfo.produce(attributes, charSequence, colorsScheme, tokenStart, tokenEnd);
-        return true;
-      }
-
-      private boolean isInterestedHighlightLayer(int layer) {
-        return layer != HighlighterLayer.CARET_ROW && layer != HighlighterLayer.SELECTION && layer != HighlighterLayer.ERROR
-               && layer != HighlighterLayer.WARNING;
-      }
-    };
-  }
-
   private static class Context {
-    @NotNull private final TextWithMarkupBuilder myBuilder;
+
+    private final SyntaxInfo.Builder builder;
+
     @NotNull private final CharSequence myText;
     @NotNull private final Color        myDefaultForeground;
     @NotNull private final Color        myDefaultBackground;
@@ -506,91 +261,91 @@
 
     private int myFontStyle   = -1;
     private int myStartOffset = -1;
+    private int myOffsetShift = -1;
 
     private int myIndentSymbolsToStripAtCurrentLine;
 
-    Context(@NotNull TextWithMarkupBuilder builder, @NotNull CharSequence charSequence, @NotNull EditorColorsScheme scheme, int indentSymbolsToStrip) {
-      myBuilder = builder;
+    Context(@NotNull CharSequence charSequence, @NotNull EditorColorsScheme scheme, int indentSymbolsToStrip) {
       myText = charSequence;
       myDefaultForeground = scheme.getDefaultForeground();
       myDefaultBackground = scheme.getDefaultBackground();
+      builder = new SyntaxInfo.Builder(myDefaultForeground, myDefaultBackground, scheme.getEditorFontSize());
       myIndentSymbolsToStrip = indentSymbolsToStrip;
     }
 
-    public void reset() {
+    public void reset(int offsetShift) {
       myStartOffset = -1;
+      myOffsetShift = offsetShift;
       myIndentSymbolsToStripAtCurrentLine = 0;
     }
 
-    public void onNewData(@NotNull SegmentInfo info) {
-      if (myStartOffset < 0) {
-        myStartOffset = info.startOffset;
-      }
+    public void iterate(MarkupIterator iterator, int endOffset) {
+      while (!iterator.atEnd()) {
+        iterator.advance();
+        int startOffset = iterator.getStartOffset();
+        if (startOffset >= endOffset) {
+          break;
+        }
+        if (myStartOffset < 0) {
+          myStartOffset = startOffset;
+        }
 
-      boolean whiteSpacesOnly = containsWhiteSpacesOnly(info);
+        boolean whiteSpacesOnly = CharArrayUtil.isEmptyOrSpaces(myText, startOffset, iterator.getEndOffset());
 
-      processBackground(info);
-      if (!whiteSpacesOnly) {
-        processForeground(info);
-        processFontFamilyName(info);
-        processFontStyle(info);
-      }
-    }
-
-    private boolean containsWhiteSpacesOnly(@NotNull SegmentInfo info) {
-      for (int i = info.startOffset, limit = info.endOffset; i < limit; i++) {
-        char c = myText.charAt(i);
-        if (c != ' ' && c != '\t' && c != '\n') {
-          return false;
+        processBackground(startOffset, iterator.getBackgroundColor());
+        if (!whiteSpacesOnly) {
+          processForeground(startOffset, iterator.getForegroundColor());
+          processFontFamilyName(startOffset, iterator.getFontFamilyName());
+          processFontStyle(startOffset, iterator.getFontStyle());
         }
       }
-      return true;
+      addTextIfPossible(endOffset);
     }
 
-    private void processFontStyle(@NotNull SegmentInfo info) {
-      if (info.fontStyle != myFontStyle) {
-        addTextIfPossible(info.startOffset);
-        myBuilder.setFontStyle(info.fontStyle);
-        myFontStyle = info.fontStyle;
+    private void processFontStyle(int startOffset, int fontStyle) {
+      if (fontStyle != myFontStyle) {
+        addTextIfPossible(startOffset);
+        builder.addFontStyle(fontStyle);
+        myFontStyle = fontStyle;
       }
     }
 
-    private void processFontFamilyName(@NotNull SegmentInfo info) {
-      String fontFamilyName = FontMapper.getPhysicalFontName(info.fontFamilyName);
+    private void processFontFamilyName(int startOffset, String fontName) {
+      String fontFamilyName = FontMapper.getPhysicalFontName(fontName);
       if (!fontFamilyName.equals(myFontFamilyName)) {
-        addTextIfPossible(info.startOffset);
-        myBuilder.setFontFamily(fontFamilyName);
+        addTextIfPossible(startOffset);
+        builder.addFontFamilyName(fontFamilyName);
         myFontFamilyName = fontFamilyName;
       }
     }
 
-    private void processForeground(@NotNull SegmentInfo info) {
-      if (myForeground == null && info.foreground != null) {
-        addTextIfPossible(info.startOffset);
-        myForeground = info.foreground;
-        myBuilder.setForeground(info.foreground);
+    private void processForeground(int startOffset, Color foreground) {
+      if (myForeground == null && foreground != null) {
+        addTextIfPossible(startOffset);
+        myForeground = foreground;
+        builder.addForeground(foreground);
       }
       else if (myForeground != null) {
-        Color c = info.foreground == null ? myDefaultForeground : info.foreground;
+        Color c = foreground == null ? myDefaultForeground : foreground;
         if (!myForeground.equals(c)) {
-          addTextIfPossible(info.startOffset);
-          myBuilder.setForeground(c);
+          addTextIfPossible(startOffset);
+          builder.addForeground(c);
           myForeground = c;
         }
       }
     }
 
-    private void processBackground(@NotNull SegmentInfo info) {
-      if (myBackground == null && info.background != null && !myDefaultBackground.equals(info.background)) {
-        addTextIfPossible(info.startOffset);
-        myBackground = info.background;
-        myBuilder.setBackground(info.background);
+    private void processBackground(int startOffset, Color background) {
+      if (myBackground == null && background != null && !myDefaultBackground.equals(background)) {
+        addTextIfPossible(startOffset);
+        myBackground = background;
+        builder.addBackground(background);
       }
       else if (myBackground != null) {
-        Color c = info.background == null ? myDefaultBackground : info.background;
+        Color c = background == null ? myDefaultBackground : background;
         if (!myBackground.equals(c)) {
-          addTextIfPossible(info.startOffset);
-          myBuilder.setBackground(c);
+          addTextIfPossible(startOffset);
+          builder.addBackground(c);
           myBackground = c;
         }
       }
@@ -606,7 +361,7 @@
         switch (c) {
           case '\n':
             myIndentSymbolsToStripAtCurrentLine = myIndentSymbolsToStrip;
-            myBuilder.addTextFragment(myText, myStartOffset, i + 1);
+            builder.addText(myStartOffset + myOffsetShift, i + myOffsetShift + 1);
             myStartOffset = i + 1;
             break;
           // Intended fall-through.
@@ -622,143 +377,485 @@
       }
 
       if (myStartOffset < endOffset) {
-        myBuilder.addTextFragment(myText, myStartOffset, endOffset);
+        builder.addText(myStartOffset + myOffsetShift, endOffset + myOffsetShift);
         myStartOffset = endOffset;
       }
     }
 
-    public void onIterationEnd(int endOffset) {
-      addTextIfPossible(endOffset);
+    @NotNull
+    public SyntaxInfo finish() {
+      return builder.build();
     }
   }
 
-  private static class SegmentInfo implements Comparable<SegmentInfo> {
+  private static class MarkupIterator {
+    private final SegmentIterator mySegmentIterator;
+    private final RangeIterator myRangeIterator;
+    private int myCurrentFontStyle;
+    private Color myCurrentForegroundColor;
+    private Color myCurrentBackgroundColor;
 
-    @Nullable public final Color  foreground;
-    @Nullable public final Color  background;
-    @NotNull public final  String fontFamilyName;
+    private MarkupIterator(@NotNull CharSequence charSequence, @NotNull RangeIterator rangeIterator, @NotNull EditorColorsScheme colorsScheme) {
+      myRangeIterator = rangeIterator;
+      mySegmentIterator = new SegmentIterator(charSequence, colorsScheme.getEditorFontName(), colorsScheme.getEditorFontSize());
+    }
 
-    public final int fontStyle;
-    public final int startOffset;
-    public final int endOffset;
+    public boolean atEnd() {
+      return myRangeIterator.atEnd() && mySegmentIterator.atEnd();
+    }
 
-    SegmentInfo(@Nullable Color foreground,
-                @Nullable Color background,
-                @NotNull String fontFamilyName,
-                int fontStyle,
-                int startOffset,
-                int endOffset)
-    {
-      this.foreground = foreground;
-      this.background = background;
-      this.fontFamilyName = fontFamilyName;
-      this.fontStyle = fontStyle;
-      this.startOffset = startOffset;
-      this.endOffset = endOffset;
+    public void advance() {
+      if (mySegmentIterator.atEnd()) {
+        myRangeIterator.advance();
+        TextAttributes textAttributes = myRangeIterator.getTextAttributes();
+        myCurrentFontStyle = textAttributes == null ? Font.PLAIN : textAttributes.getFontType();
+        myCurrentForegroundColor = textAttributes == null ? null : textAttributes.getForegroundColor();
+        myCurrentBackgroundColor = textAttributes == null ? null : textAttributes.getBackgroundColor();
+        mySegmentIterator.reset(myRangeIterator.getRangeStart(), myRangeIterator.getRangeEnd(), myCurrentFontStyle);
+      }
+      mySegmentIterator.advance();
+    }
+
+    public int getStartOffset() {
+      return mySegmentIterator.getCurrentStartOffset();
+    }
+
+    public int getEndOffset() {
+      return mySegmentIterator.getCurrentEndOffset();
+    }
+
+    public int getFontStyle() {
+      return myCurrentFontStyle;
     }
 
     @NotNull
-    public static List<SegmentInfo> produce(@NotNull TextAttributes attribute,
-                                            @NotNull CharSequence text,
-                                            @NotNull EditorColorsScheme colorsScheme,
-                                            int start,
-                                            int end)
-    {
-      if (end <= start) {
-        return Collections.emptyList();
-      }
-      List<SegmentInfo> result = ContainerUtilRt.newArrayList();
-      int currentStart = start;
-      int fontSize = colorsScheme.getEditorFontSize();
-      int fontStyle = attribute.getFontType();
-      String defaultFontFamily = colorsScheme.getEditorFontName();
-      Font font = ComplementaryFontsRegistry.getFontAbleToDisplay(text.charAt(start), fontSize, fontStyle, defaultFontFamily).getFont();
-      String currentFontFamilyName = font.getFamily();
-      String candidateFontFamilyName;
-      for (int i = start + 1; i < end; i++) {
-        font = ComplementaryFontsRegistry.getFontAbleToDisplay(text.charAt(i), fontSize, fontStyle, defaultFontFamily).getFont();
-        candidateFontFamilyName = font.getFamily();
-        if (!candidateFontFamilyName.equals(currentFontFamilyName)) {
-          result.add(new SegmentInfo(attribute.getForegroundColor(),
-                                     attribute.getBackgroundColor(),
-                                     currentFontFamilyName,
-                                     fontStyle,
-                                     currentStart,
-                                     i
-          ));
-          currentStart = i;
-          currentFontFamilyName = candidateFontFamilyName;
-        }
-      }
-
-      if (currentStart < end) {
-        result.add(new SegmentInfo(attribute.getForegroundColor(),
-                                   attribute.getBackgroundColor(),
-                                   currentFontFamilyName,
-                                   fontStyle,
-                                   currentStart,
-                                   end
-        ));
-      }
-
-      return result;
+    public String getFontFamilyName() {
+      return mySegmentIterator.getCurrentFontFamilyName();
     }
 
-    @Override
-    public int compareTo(@NotNull SegmentInfo o) {
-      return startOffset - o.startOffset;
+    @Nullable
+    public Color getForegroundColor() {
+      return myCurrentForegroundColor;
     }
 
-    @Override
-    public int hashCode() {
-      int result = foreground != null ? foreground.hashCode() : 0;
-      result = 31 * result + (background != null ? background.hashCode() : 0);
-      result = 31 * result + fontFamilyName.hashCode();
-      result = 31 * result + fontStyle;
-      result = 31 * result + startOffset;
-      result = 31 * result + endOffset;
-      return result;
+    @Nullable
+    public Color getBackgroundColor() {
+      return myCurrentBackgroundColor;
     }
 
-    @SuppressWarnings("RedundantIfStatement")
-    @Override
-    public boolean equals(Object o) {
-      if (this == o) return true;
-      if (o == null || getClass() != o.getClass()) return false;
-
-      SegmentInfo info = (SegmentInfo)o;
-
-      if (endOffset != info.endOffset) return false;
-      if (fontStyle != info.fontStyle) return false;
-      if (startOffset != info.startOffset) return false;
-      if (background != null ? !background.equals(info.background) : info.background != null) return false;
-      if (!fontFamilyName.equals(info.fontFamilyName)) return false;
-      if (foreground != null ? !foreground.equals(info.foreground) : info.foreground != null) return false;
-
-      return true;
-    }
-
-    @Override
-    public String toString() {
-      StringBuilder fontStyleAsString = new StringBuilder();
-      if (fontStyle == Font.PLAIN) {
-        fontStyleAsString.append("plain");
-      }
-      else {
-        if ((fontStyle & Font.BOLD) != 0) {
-          fontStyleAsString.append("bold ");
-        }
-        if ((fontStyle & Font.ITALIC) != 0) {
-          fontStyleAsString.append("italic ");
-        }
-        if (fontStyleAsString.length() > 0) {
-          fontStyleAsString.setLength(fontStyleAsString.length() - 1);
-        }
-        else {
-          fontStyleAsString.append("unknown font style");
-        }
-      }
-      return String.format("%d-%d: %s, %s", startOffset, endOffset, fontFamilyName, fontStyleAsString);
+    public void dispose() {
+      myRangeIterator.dispose();
     }
   }
+
+  private static class CompositeRangeIterator implements RangeIterator {
+    private final @NotNull Color myDefaultForeground;
+    private final @NotNull Color myDefaultBackground;
+    private final IteratorWrapper[] myIterators;
+    private final TextAttributes myMergedAttributes = new TextAttributes();
+    private int overlappingRangesCount;
+    private int myCurrentStart;
+    private int myCurrentEnd;
+
+    // iterators have priority corresponding to their order in the parameter list - rightmost having the largest priority
+    public CompositeRangeIterator(@NotNull EditorColorsScheme colorsScheme, RangeIterator... iterators) {
+      myDefaultForeground = colorsScheme.getDefaultForeground();
+      myDefaultBackground = colorsScheme.getDefaultBackground();
+      myIterators = new IteratorWrapper[iterators.length];
+      for (int i = 0; i < iterators.length; i++) {
+        myIterators[i] = new IteratorWrapper(iterators[i], i);
+      }
+    }
+
+    @Override
+    public boolean atEnd() {
+      boolean validIteratorExists = false;
+      for (int i = 0; i < myIterators.length; i++) {
+        IteratorWrapper wrapper = myIterators[i];
+        if (wrapper == null) {
+          continue;
+        }
+        RangeIterator iterator = wrapper.iterator;
+        if (!iterator.atEnd() || overlappingRangesCount > 0 && (i >= overlappingRangesCount || iterator.getRangeEnd() > myCurrentEnd)) {
+          validIteratorExists = true;
+        }
+      }
+      return !validIteratorExists;
+    }
+
+    @Override
+    public void advance() {
+      int max = overlappingRangesCount == 0 ? myIterators.length : overlappingRangesCount;
+      for (int i = 0; i < max; i++) {
+        IteratorWrapper wrapper = myIterators[i];
+        if (wrapper == null) {
+          continue;
+        }
+        RangeIterator iterator = wrapper.iterator;
+        if (overlappingRangesCount > 0 && iterator.getRangeEnd() > myCurrentEnd) {
+          continue;
+        }
+        if (iterator.atEnd()) {
+          iterator.dispose();
+          myIterators[i] = null;
+        }
+        else {
+          iterator.advance();
+        }
+      }
+      Arrays.sort(myIterators, RANGE_SORTER);
+      myCurrentStart = Math.max(myIterators[0].iterator.getRangeStart(), myCurrentEnd);
+      myCurrentEnd = Integer.MAX_VALUE;
+      //noinspection ForLoopReplaceableByForEach
+      for (int i = 0; i < myIterators.length; i++) {
+        IteratorWrapper wrapper = myIterators[i];
+        if (wrapper == null) {
+          break;
+        }
+        RangeIterator iterator = wrapper.iterator;
+        int nearestBound;
+        if (iterator.getRangeStart() > myCurrentStart) {
+          nearestBound = iterator.getRangeStart();
+        }
+        else {
+          nearestBound = iterator.getRangeEnd();
+        }
+        myCurrentEnd = Math.min(myCurrentEnd, nearestBound);
+      }
+      myCurrentEnd = getRangeEnd();
+      for (overlappingRangesCount = 1; overlappingRangesCount < myIterators.length; overlappingRangesCount++) {
+        IteratorWrapper wrapper = myIterators[overlappingRangesCount];
+        if (wrapper == null || wrapper.iterator.getRangeStart() > myCurrentStart) {
+          break;
+        }
+      }
+    }
+
+    private final Comparator<IteratorWrapper> RANGE_SORTER  = new Comparator<IteratorWrapper>() {
+      @Override
+      public int compare(IteratorWrapper o1, IteratorWrapper o2) {
+        if (o1 == null) {
+          return 1;
+        }
+        if (o2 == null) {
+          return -1;
+        }
+        int startDiff = Math.max(o1.iterator.getRangeStart(), myCurrentEnd) - Math.max(o2.iterator.getRangeStart(), myCurrentEnd);
+        if (startDiff != 0) {
+          return startDiff;
+        }
+        return o2.order - o1.order;
+      }
+    };
+
+    @Override
+    public int getRangeStart() {
+      return myCurrentStart;
+    }
+
+    @Override
+    public int getRangeEnd() {
+      return myCurrentEnd;
+    }
+
+    @Override
+    public TextAttributes getTextAttributes() {
+      TextAttributes ta = myIterators[0].iterator.getTextAttributes();
+      myMergedAttributes.setAttributes(ta.getForegroundColor(), ta.getBackgroundColor(), null, null, null, ta.getFontType());
+      for (int i = 1; i < overlappingRangesCount; i++) {
+        merge(myIterators[i].iterator.getTextAttributes());
+      }
+      return myMergedAttributes;
+    }
+
+    private void merge(TextAttributes attributes) {
+      Color myBackground = myMergedAttributes.getBackgroundColor();
+      if (myBackground == null || myDefaultBackground.equals(myBackground)) {
+        myMergedAttributes.setBackgroundColor(attributes.getBackgroundColor());
+      }
+      Color myForeground = myMergedAttributes.getForegroundColor();
+      if (myForeground == null || myDefaultForeground.equals(myForeground)) {
+        myMergedAttributes.setForegroundColor(attributes.getForegroundColor());
+      }
+      if (myMergedAttributes.getFontType() == Font.PLAIN) {
+        myMergedAttributes.setFontType(attributes.getFontType());
+      }
+    }
+
+    @Override
+    public void dispose() {
+      for (IteratorWrapper wrapper : myIterators) {
+        if (wrapper != null) {
+          wrapper.iterator.dispose();
+        }
+      }
+    }
+
+    private static class IteratorWrapper {
+      private final RangeIterator iterator;
+      private final int order;
+
+      private IteratorWrapper(RangeIterator iterator, int order) {
+        this.iterator = iterator;
+        this.order = order;
+      }
+    }
+  }
+
+  private static class MarkupModelRangeIterator implements RangeIterator {
+    private final boolean myUnsupportedModel;
+    private final int myStartOffset;
+    private final int myEndOffset;
+    private final EditorColorsScheme myColorsScheme;
+    private final Color myDefaultForeground;
+    private final Color myDefaultBackground;
+    private final DisposableIterator<RangeHighlighterEx> myIterator;
+
+    private int myCurrentStart;
+    private int myCurrentEnd;
+    private TextAttributes myCurrentAttributes;
+    private int myNextStart;
+    private int myNextEnd;
+    private TextAttributes myNextAttributes;
+
+    private MarkupModelRangeIterator(@Nullable MarkupModel markupModel,
+                                     @NotNull EditorColorsScheme colorsScheme,
+                                     int startOffset,
+                                     int endOffset) {
+      myStartOffset = startOffset;
+      myEndOffset = endOffset;
+      myColorsScheme = colorsScheme;
+      myDefaultForeground = colorsScheme.getDefaultForeground();
+      myDefaultBackground = colorsScheme.getDefaultBackground();
+      myUnsupportedModel = !(markupModel instanceof MarkupModelEx);
+      if (myUnsupportedModel) {
+        myIterator = null;
+        return;
+      }
+      myIterator = ((MarkupModelEx)markupModel).overlappingIterator(startOffset, endOffset);
+      findNextSuitableRange();
+    }
+
+    @Override
+    public boolean atEnd() {
+      return myUnsupportedModel || myNextAttributes == null;
+    }
+
+    @Override
+    public void advance() {
+      myCurrentStart = myNextStart;
+      myCurrentEnd = myNextEnd;
+      myCurrentAttributes = myNextAttributes;
+      findNextSuitableRange();
+    }
+
+    private void findNextSuitableRange() {
+      myNextAttributes = null;
+      while(myIterator.hasNext()) {
+        RangeHighlighterEx highlighter = myIterator.next();
+        if (highlighter == null || !highlighter.isValid() || !isInterestedInLayer(highlighter.getLayer())) {
+          continue;
+        }
+        // LINES_IN_RANGE highlighters are not supported currently
+        myNextStart = Math.max(highlighter.getStartOffset(), myStartOffset);
+        myNextEnd = Math.min(highlighter.getEndOffset(), myEndOffset);
+        if (myNextStart >= myEndOffset) {
+          break;
+        }
+        if (myNextStart < myCurrentEnd) {
+          continue; // overlapping ranges withing document markup model are not supported currently
+        }
+        TextAttributes attributes = null;
+        Object tooltip = highlighter.getErrorStripeTooltip();
+        if (tooltip instanceof HighlightInfo) {
+          HighlightInfo info = (HighlightInfo)tooltip;
+          TextAttributesKey key = info.forcedTextAttributesKey;
+          if (key == null) {
+            HighlightInfoType type = info.type;
+            key = type.getAttributesKey();
+          }
+          if (key != null) {
+            attributes = myColorsScheme.getAttributes(key);
+          }
+        }
+        if (attributes == null) {
+          continue;
+        }
+        Color foreground = attributes.getForegroundColor();
+        Color background = attributes.getBackgroundColor();
+        if ((foreground == null || myDefaultForeground.equals(foreground))
+            && (background == null || myDefaultBackground.equals(background))
+            && attributes.getFontType() == Font.PLAIN) {
+          continue;
+        }
+        myNextAttributes = attributes;
+        break;
+      }
+    }
+
+    private static boolean isInterestedInLayer(int layer) {
+      return layer != HighlighterLayer.CARET_ROW
+             && layer != HighlighterLayer.SELECTION
+             && layer != HighlighterLayer.ERROR
+             && layer != HighlighterLayer.WARNING;
+    }
+
+    @Override
+    public int getRangeStart() {
+      return myCurrentStart;
+    }
+
+    @Override
+    public int getRangeEnd() {
+      return myCurrentEnd;
+    }
+
+    @Override
+    public TextAttributes getTextAttributes() {
+      return myCurrentAttributes;
+    }
+
+    @Override
+    public void dispose() {
+      if (myIterator != null) {
+        myIterator.dispose();
+      }
+    }
+  }
+
+  private static class HighlighterRangeIterator implements RangeIterator {
+    private final HighlighterIterator myIterator;
+    private final int myStartOffset;
+    private final int myEndOffset;
+
+    private int myCurrentStart;
+    private int myCurrentEnd;
+    private TextAttributes myCurrentAttributes;
+
+    public HighlighterRangeIterator(@NotNull EditorHighlighter highlighter, int startOffset, int endOffset) {
+      myStartOffset = startOffset;
+      myEndOffset = endOffset;
+      myIterator = highlighter.createIterator(startOffset);
+      skipBadCharacters();
+    }
+
+    @Override
+    public boolean atEnd() {
+      return myIterator.atEnd() || getCurrentStart() >= myEndOffset;
+    }
+
+    private int getCurrentStart() {
+      return Math.max(myIterator.getStart(), myStartOffset);
+    }
+
+    private int getCurrentEnd() {
+      return Math.min(myIterator.getEnd(), myEndOffset);
+    }
+
+    private void skipBadCharacters() {
+      while (!myIterator.atEnd() && myIterator.getTokenType() == TokenType.BAD_CHARACTER) {
+        myIterator.advance();
+      }
+    }
+
+    @Override
+    public void advance() {
+      myCurrentStart = getCurrentStart();
+      myCurrentEnd = getCurrentEnd();
+      myCurrentAttributes = myIterator.getTextAttributes();
+      myIterator.advance();
+      skipBadCharacters();
+    }
+
+    @Override
+    public int getRangeStart() {
+      return myCurrentStart;
+    }
+
+    @Override
+    public int getRangeEnd() {
+      return myCurrentEnd;
+    }
+
+    @Override
+    public TextAttributes getTextAttributes() {
+      return myCurrentAttributes;
+    }
+
+    @Override
+    public void dispose() {
+    }
+  }
+
+  private interface RangeIterator {
+    boolean atEnd();
+    void advance();
+    int getRangeStart();
+    int getRangeEnd();
+    TextAttributes getTextAttributes();
+    void dispose();
+  }
+
+  private static class SegmentIterator {
+    private final CharSequence myCharSequence;
+    private final String myDefaultFontFamilyName;
+    private final int myFontSize;
+
+    private int myCurrentStartOffset;
+    private int myCurrentOffset;
+    private int myEndOffset;
+    private int myFontStyle;
+    private String myCurrentFontFamilyName;
+    private String myNextFontFamilyName;
+
+    private SegmentIterator(CharSequence charSequence, String defaultFontFamilyName, int fontSize) {
+      myCharSequence = charSequence;
+      myDefaultFontFamilyName = defaultFontFamilyName;
+      myFontSize = fontSize;
+    }
+
+    public void reset(int startOffset, int endOffset, int fontStyle) {
+      myCurrentOffset = startOffset;
+      myEndOffset = endOffset;
+      myFontStyle = fontStyle;
+    }
+
+    public boolean atEnd() {
+      return myCurrentOffset >= myEndOffset;
+    }
+
+    public void advance() {
+      myCurrentFontFamilyName = myNextFontFamilyName;
+      myCurrentStartOffset = myCurrentOffset;
+      for (; myCurrentOffset < myEndOffset; myCurrentOffset++) {
+        FontInfo fontInfo = ComplementaryFontsRegistry.getFontAbleToDisplay(myCharSequence.charAt(myCurrentOffset),
+                                                                            myFontSize,
+                                                                            myFontStyle,
+                                                                            myDefaultFontFamilyName);
+        String fontFamilyName = fontInfo.getFont().getFamily();
+
+        if (myCurrentFontFamilyName == null) {
+          myCurrentFontFamilyName = fontFamilyName;
+        }
+        else if (!myCurrentFontFamilyName.equals(fontFamilyName)) {
+          myNextFontFamilyName = fontFamilyName;
+          break;
+        }
+      }
+    }
+
+    public int getCurrentStartOffset() {
+      return myCurrentStartOffset;
+    }
+
+    public int getCurrentEndOffset() {
+      return myCurrentOffset;
+    }
+
+    public String getCurrentFontFamilyName() {
+      return myCurrentFontFamilyName;
+    }
+  }
+
+
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/AbstractRegistry.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/AbstractRegistry.java
index 23c0c01..0435235 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/AbstractRegistry.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/AbstractRegistry.java
@@ -19,14 +19,13 @@
 import gnu.trove.TObjectIntHashMap;
 import org.jetbrains.annotations.NotNull;
 
-import java.io.Serializable;
 import java.util.Arrays;
 
 /**
  * @author Denis Zhdanov
  * @since 3/23/13 3:17 PM
  */
-public abstract class AbstractRegistry<T> implements Serializable {
+public abstract class AbstractRegistry<T> {
 
   @NotNull private final TIntObjectHashMap<T> myDataById = new TIntObjectHashMap<T>();
 
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaForkOptions.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/MarkupHandler.java
similarity index 61%
copy from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaForkOptions.java
copy to platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/MarkupHandler.java
index 9dd0cef..cdd01c4 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaForkOptions.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/MarkupHandler.java
@@ -13,19 +13,12 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model;
+package com.intellij.openapi.editor.richcopy.model;
 
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * @author Vladislav.Soroka
- * @since 1/31/14
- */
-public interface ScalaForkOptions extends Serializable {
-  String getMemoryInitialSize();
-
-  String getMemoryMaximumSize();
-
-  List<String> getJvmArgs();
+public interface MarkupHandler {
+  void handleText(int startOffset, int endOffset) throws Exception;
+  void handleForeground(int foregroundId)  throws Exception;
+  void handleBackground(int backgroundId)  throws Exception;
+  void handleFont(int fontNameId)  throws Exception;
+  void handleStyle(int style)  throws Exception;
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/OutputInfoSerializer.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/OutputInfoSerializer.java
new file mode 100644
index 0000000..75ae376
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/OutputInfoSerializer.java
@@ -0,0 +1,123 @@
+/*
+ * Copyright 2000-2014 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.editor.richcopy.model;
+
+import com.intellij.util.io.CompactDataInput;
+import com.intellij.util.io.CompactDataOutput;
+import org.iq80.snappy.SnappyInputStream;
+import org.iq80.snappy.SnappyOutputStream;
+
+import java.io.IOException;
+
+/**
+ * Not synchronized, stream implementations must be used from one thread at a time only
+ */
+public class OutputInfoSerializer {
+  private static final int TEXT_ID = 0;
+  private static final int STYLE_ID = 1;
+  private static final int FOREGROUND_ID = 2;
+  private static final int BACKGROUND_ID = 3;
+  private static final int FONT_ID = 4;
+
+  public static class OutputStream implements MarkupHandler {
+    private final CompactDataOutput myOutputStream;
+    private final java.io.OutputStream myUnderlyingOutputStream;
+    private int myCurrentOffset;
+
+    public OutputStream(java.io.OutputStream stream) throws IOException {
+      myUnderlyingOutputStream = new SnappyOutputStream(stream);
+      myOutputStream = new CompactDataOutput(myUnderlyingOutputStream);
+    }
+
+    public void close() throws IOException {
+      myUnderlyingOutputStream.close();
+    }
+
+    @Override
+    public void handleText(int startOffset, int endOffset) throws IOException {
+      myOutputStream.write(TEXT_ID);
+      myOutputStream.writeInt(startOffset - myCurrentOffset);
+      myOutputStream.writeInt(endOffset - startOffset);
+      myCurrentOffset = endOffset;
+    }
+
+    @Override
+    public void handleForeground(int foregroundId) throws IOException {
+      myOutputStream.write(FOREGROUND_ID);
+      myOutputStream.writeInt(foregroundId);
+    }
+
+    @Override
+    public void handleBackground(int backgroundId) throws IOException {
+      myOutputStream.write(BACKGROUND_ID);
+      myOutputStream.writeInt(backgroundId);
+    }
+
+    @Override
+    public void handleFont(int fontNameId) throws IOException {
+      myOutputStream.write(FONT_ID);
+      myOutputStream.writeInt(fontNameId);
+    }
+
+    @Override
+    public void handleStyle(int style) throws IOException {
+      myOutputStream.write(STYLE_ID);
+      myOutputStream.writeInt(style);
+    }
+  }
+
+  public static class InputStream {
+    private final CompactDataInput myInputStream;
+    private final java.io.InputStream myUnderlyingInputStream;
+    private int myCurrentOffset;
+
+    public InputStream(java.io.InputStream stream) throws IOException {
+      myUnderlyingInputStream = new SnappyInputStream(stream);
+      myInputStream = new CompactDataInput(myUnderlyingInputStream);
+    }
+
+    public void read(MarkupHandler handler) throws Exception {
+      int id = myInputStream.readByte();
+      switch (id) {
+        case TEXT_ID:
+          int startOffset = myCurrentOffset + myInputStream.readInt();
+          myCurrentOffset = startOffset;
+          int endOffset = myCurrentOffset + myInputStream.readInt();
+          myCurrentOffset = endOffset;
+          handler.handleText(startOffset, endOffset);
+          break;
+        case STYLE_ID:
+          handler.handleStyle(myInputStream.readInt());
+          break;
+        case FOREGROUND_ID:
+          handler.handleForeground(myInputStream.readInt());
+          break;
+        case BACKGROUND_ID:
+          handler.handleBackground(myInputStream.readInt());
+          break;
+        case FONT_ID:
+          handler.handleFont(myInputStream.readInt());
+          break;
+        default:
+          throw new IllegalStateException("Unknown tag id: " + id);
+      }
+    }
+
+    public void close() throws IOException {
+      myUnderlyingInputStream.close();
+    }
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/SyntaxInfo.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/SyntaxInfo.java
new file mode 100644
index 0000000..7bd88c5
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/model/SyntaxInfo.java
@@ -0,0 +1,252 @@
+/*
+ * Copyright 2000-2014 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.editor.richcopy.model;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.awt.*;
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+
+/**
+ * @author Denis Zhdanov
+ * @since 3/25/13 1:19 PM
+ */
+public class SyntaxInfo {
+  private final int myOutputInfoCount;
+  private final byte[] myOutputInfosSerialized;
+  @NotNull private final ColorRegistry    myColorRegistry;
+  @NotNull private final FontNameRegistry myFontNameRegistry;
+
+  private final int myDefaultForeground;
+  private final int myDefaultBackground;
+  private final int mySingleFontSize;
+
+  private SyntaxInfo(int outputInfoCount,
+                     byte[] outputInfosSerialized,
+                    int defaultForeground,
+                    int defaultBackground,
+                    int singleFontSize,
+                    @NotNull FontNameRegistry fontNameRegistry,
+                    @NotNull ColorRegistry colorRegistry)
+  {
+    myOutputInfoCount = outputInfoCount;
+    myOutputInfosSerialized = outputInfosSerialized;
+    myDefaultForeground = defaultForeground;
+    myDefaultBackground = defaultBackground;
+    mySingleFontSize = singleFontSize;
+    myFontNameRegistry = fontNameRegistry;
+    myColorRegistry = colorRegistry;
+  }
+
+  @NotNull
+  public ColorRegistry getColorRegistry() {
+    return myColorRegistry;
+  }
+
+  @NotNull
+  public FontNameRegistry getFontNameRegistry() {
+    return myFontNameRegistry;
+  }
+
+  public int getDefaultForeground() {
+    return myDefaultForeground;
+  }
+
+  public int getDefaultBackground() {
+    return myDefaultBackground;
+  }
+
+  /**
+   * @return    positive value if all tokens have the same font size (returned value);
+   *            non-positive value otherwise
+   */
+  public int getSingleFontSize() {
+    return mySingleFontSize;
+  }
+
+  @Override
+  public String toString() {
+    final StringBuilder b = new StringBuilder();
+    b.append("default colors: foreground=").append(myDefaultForeground).append(", background=").append(myDefaultBackground).append("; output infos: ");
+    boolean first = true;
+    MarkupIterator it = new MarkupIterator();
+    try {
+      while(it.hasNext()) {
+        if (first) {
+          b.append(',');
+        }
+        it.processNext(new MarkupHandler() {
+          @Override
+          public void handleText(int startOffset, int endOffset) throws Exception {
+            b.append("text(").append(startOffset).append(",").append(endOffset).append(")");
+          }
+
+          @Override
+          public void handleForeground(int foregroundId) throws Exception {
+            b.append("foreground(").append(foregroundId).append(")");
+          }
+
+          @Override
+          public void handleBackground(int backgroundId) throws Exception {
+            b.append("background(").append(backgroundId).append(")");
+          }
+
+          @Override
+          public void handleFont(int fontNameId) throws Exception {
+            b.append("font(").append(fontNameId).append(")");
+          }
+
+          @Override
+          public void handleStyle(int style) throws Exception {
+            b.append("style(").append(style).append(")");
+          }
+        });
+        first = false;
+      }
+      return b.toString();
+    }
+    finally {
+      it.dispose();
+    }
+  }
+
+  public static class Builder {
+    private final ColorRegistry myColorRegistry = new ColorRegistry();
+    private final FontNameRegistry myFontNameRegistry = new FontNameRegistry();
+    private final int myDefaultForeground;
+    private final int myDefaultBackground;
+    private final int myFontSize;
+    private final ByteArrayOutputStream myStream = new ByteArrayOutputStream();
+    private final OutputInfoSerializer.OutputStream myOutputInfoStream;
+    private int myOutputInfoCount;
+
+    public Builder(Color defaultForeground, Color defaultBackground, int fontSize) {
+      myDefaultForeground = myColorRegistry.getId(defaultForeground);
+      myDefaultBackground = myColorRegistry.getId(defaultBackground);
+      myFontSize = fontSize;
+      try {
+        myOutputInfoStream = new OutputInfoSerializer.OutputStream(myStream);
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    public void addFontStyle(int fontStyle) {
+      try {
+        myOutputInfoStream.handleStyle(fontStyle);
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      myOutputInfoCount++;
+    }
+
+    public void addFontFamilyName(String fontFamilyName) {
+      try {
+        myOutputInfoStream.handleFont(myFontNameRegistry.getId(fontFamilyName));
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      myOutputInfoCount++;
+    }
+
+    public void addForeground(Color foreground) {
+      try {
+        myOutputInfoStream.handleForeground(myColorRegistry.getId(foreground));
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      myOutputInfoCount++;
+    }
+
+    public void addBackground(Color background) {
+      try {
+        myOutputInfoStream.handleBackground(myColorRegistry.getId(background));
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      myOutputInfoCount++;
+    }
+
+    public void addText(int startOffset, int endOffset) {
+      try {
+        myOutputInfoStream.handleText(startOffset, endOffset);
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      myOutputInfoCount++;
+    }
+
+    public SyntaxInfo build() {
+      myColorRegistry.seal();
+      myFontNameRegistry.seal();
+      try {
+        myOutputInfoStream.close();
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+      return new SyntaxInfo(myOutputInfoCount, myStream.toByteArray(), myDefaultForeground, myDefaultBackground, myFontSize, myFontNameRegistry, myColorRegistry);
+    }
+  }
+
+  public class MarkupIterator {
+    private int pos;
+    private final OutputInfoSerializer.InputStream myOutputInfoStream;
+
+    public MarkupIterator() {
+      try {
+        myOutputInfoStream = new OutputInfoSerializer.InputStream(new ByteArrayInputStream(myOutputInfosSerialized));
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    public boolean hasNext() {
+      return pos < myOutputInfoCount;
+    }
+
+    public void processNext(MarkupHandler handler) {
+      if (!hasNext()) {
+        throw new IllegalStateException();
+      }
+      pos++;
+      try {
+        myOutputInfoStream.read(handler);
+      }
+      catch (Exception e) {
+        throw new RuntimeException(e);
+      }
+    }
+
+    public void dispose() {
+      try {
+        myOutputInfoStream.close();
+      }
+      catch (IOException e) {
+        throw new RuntimeException(e);
+      }
+    }
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/settings/RichCopySettings.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/settings/RichCopySettings.java
index ec99560b..77c2687 100644
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/settings/RichCopySettings.java
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/settings/RichCopySettings.java
@@ -15,7 +15,6 @@
  */
 package com.intellij.openapi.editor.richcopy.settings;
 
-import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.components.*;
 import com.intellij.openapi.editor.colors.EditorColorsManager;
 import com.intellij.openapi.editor.colors.EditorColorsScheme;
@@ -31,16 +30,15 @@
   name = "EditorRichCopySettings",
   storages = {@Storage(file = StoragePathMacros.APP_CONFIG + "/editor.rich.copy.xml")}
 )
-public class RichCopySettings implements PersistentStateComponent<RichCopySettings>, ApplicationComponent {
+public class RichCopySettings implements PersistentStateComponent<RichCopySettings> {
 
   @NotNull public static final String ACTIVE_GLOBAL_SCHEME_MARKER = "__ACTIVE_GLOBAL_SCHEME__";
 
   private String  mySchemeName = ACTIVE_GLOBAL_SCHEME_MARKER;
-  private boolean myStripIndents = true;
 
   @NotNull
   public static RichCopySettings getInstance() {
-    return ApplicationManager.getApplication().getComponent(RichCopySettings.class);
+    return ServiceManager.getService(RichCopySettings.class);
   }
 
   @NotNull
@@ -63,20 +61,6 @@
     XmlSerializerUtil.copyBean(state, this);
   }
 
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @NotNull
-  @Override
-  public String getComponentName() {
-    return getClass().getName();
-  }
-
   @NotNull
   public String getSchemeName() {
     return mySchemeName == null ? ACTIVE_GLOBAL_SCHEME_MARKER : mySchemeName;
@@ -85,12 +69,4 @@
   public void setSchemeName(@Nullable String schemeName) {
     mySchemeName = schemeName;
   }
-
-  public boolean isStripIndents() {
-    return myStripIndents;
-  }
-
-  public void setStripIndents(boolean stripIndents) {
-    myStripIndents = stripIndents;
-  }
 }
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/AbstractSyntaxAwareInputStreamTransferableData.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/AbstractSyntaxAwareInputStreamTransferableData.java
new file mode 100644
index 0000000..bb15a20
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/AbstractSyntaxAwareInputStreamTransferableData.java
@@ -0,0 +1,130 @@
+/*
+ * Copyright 2000-2014 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.editor.richcopy.view;
+
+import com.intellij.codeInsight.editorActions.TextBlockTransferableData;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import com.intellij.openapi.util.registry.Registry;
+import com.intellij.util.StringBuilderSpinAllocator;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.awt.datatransfer.DataFlavor;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.UnsupportedEncodingException;
+
+/**
+ * @author Denis Zhdanov
+ * @since 3/28/13 1:20 PM
+ */
+public abstract class AbstractSyntaxAwareInputStreamTransferableData extends InputStream implements TextBlockTransferableData, RawTextHolder
+{
+
+  private static final Logger LOG = Logger.getInstance("#" + AbstractSyntaxAwareInputStreamTransferableData.class.getName());
+
+  protected String myRawText;
+  @NotNull
+  protected final SyntaxInfo mySyntaxInfo;
+  @NotNull
+  private final DataFlavor myDataFlavor;
+
+  @Nullable private transient InputStream myDelegate;
+
+  public AbstractSyntaxAwareInputStreamTransferableData(@NotNull SyntaxInfo syntaxInfo, @NotNull DataFlavor flavor) {
+    mySyntaxInfo = syntaxInfo;
+    myDataFlavor = flavor;
+  }
+
+  @Override
+  public DataFlavor getFlavor() {
+    return myDataFlavor;
+  }
+
+  @Override
+  public int getOffsetCount() {
+    return 0;
+  }
+
+  @Override
+  public int getOffsets(int[] offsets, int index) {
+    return index;
+  }
+
+  @Override
+  public int setOffsets(int[] offsets, int index) {
+    return index;
+  }
+
+  @Override
+  public int read() throws IOException {
+    return getDelegate().read();
+  }
+
+  @Override
+  public int read(@NotNull byte[] b, int off, int len) throws IOException {
+    return getDelegate().read(b, off, len);
+  }
+
+  @Override
+  public void close() throws IOException {
+    myDelegate = null;
+  }
+
+  @Override
+  public void setRawText(String rawText) {
+    myRawText = rawText;
+  }
+
+  @NotNull
+  private InputStream getDelegate() {
+    if (myDelegate != null) {
+      return myDelegate;
+    }
+
+    int maxLength = Registry.intValue("editor.richcopy.max.size.megabytes") * 1048576;
+    final StringBuilder buffer = StringBuilderSpinAllocator.alloc();
+    try {
+      try {
+        build(buffer, maxLength);
+      }
+      catch (Exception e) {
+        LOG.error(e);
+      }
+      String s = buffer.toString();
+      if (Registry.is("editor.richcopy.debug")) {
+        LOG.info("Resulting text: \n" + s);
+      }
+      try {
+        myDelegate = new ByteArrayInputStream(s.getBytes(getCharset()));
+      }
+      catch (UnsupportedEncodingException e) {
+        throw new RuntimeException(e);
+      }
+      return myDelegate;
+    }
+    finally {
+      StringBuilderSpinAllocator.dispose(buffer);
+    }
+  }
+  
+  protected abstract void build(@NotNull StringBuilder holder, int maxLength);
+
+  @NotNull
+  protected abstract String getCharset();
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/AbstractSyntaxAwareReaderTransferableData.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/AbstractSyntaxAwareReaderTransferableData.java
new file mode 100644
index 0000000..b4de6e5
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/AbstractSyntaxAwareReaderTransferableData.java
@@ -0,0 +1,121 @@
+/*
+ * Copyright 2000-2014 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.editor.richcopy.view;
+
+import com.intellij.codeInsight.editorActions.TextBlockTransferableData;
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import com.intellij.openapi.util.registry.Registry;
+import com.intellij.util.StringBuilderSpinAllocator;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.awt.datatransfer.DataFlavor;
+import java.io.IOException;
+import java.io.Reader;
+import java.io.StringReader;
+
+/**
+ * @author Denis Zhdanov
+ * @since 3/28/13 7:09 PM
+ */
+public abstract class AbstractSyntaxAwareReaderTransferableData extends Reader implements TextBlockTransferableData, RawTextHolder
+{
+
+  private static final Logger LOG = Logger.getInstance("#" + AbstractSyntaxAwareReaderTransferableData.class.getName());
+
+  protected String myRawText;
+  @NotNull
+  protected final SyntaxInfo mySyntaxInfo;
+  @NotNull
+  private final DataFlavor myDataFlavor;
+
+  @Nullable private transient Reader myDelegate;
+
+  public AbstractSyntaxAwareReaderTransferableData(@NotNull SyntaxInfo syntaxInfo, @NotNull DataFlavor dataFlavor) {
+    mySyntaxInfo = syntaxInfo;
+    myDataFlavor = dataFlavor;
+  }
+
+  @Override
+  public DataFlavor getFlavor() {
+    return myDataFlavor;
+  }
+
+  @Override
+  public int getOffsetCount() {
+    return 0;
+  }
+
+  @Override
+  public int getOffsets(int[] offsets, int index) {
+    return index;
+  }
+
+  @Override
+  public int setOffsets(int[] offsets, int index) {
+    return index;
+  }
+
+  @Override
+  public int read() throws IOException {
+    return getDelegate().read();
+  }
+
+  @Override
+  public int read(@NotNull char[] cbuf, int off, int len) throws IOException {
+    return getDelegate().read(cbuf, off, len);
+  }
+
+  @Override
+  public void close() throws IOException {
+    myDelegate = null;
+  }
+
+  @Override
+  public void setRawText(String rawText) {
+    myRawText = rawText;
+  }
+
+  @NotNull
+  private Reader getDelegate() {
+    if (myDelegate != null) {
+      return myDelegate;
+    }
+
+    int maxLength = Registry.intValue("editor.richcopy.max.size.megabytes") * 1048576;
+    final StringBuilder buffer = StringBuilderSpinAllocator.alloc();
+    try {
+      try {
+        build(buffer, maxLength);
+      }
+      catch (Exception e) {
+        LOG.error(e);
+      }
+      String s = buffer.toString();
+      if (Registry.is("editor.richcopy.debug")) {
+        LOG.info("Resulting text: \n" + s);
+      }
+      myDelegate = new StringReader(s);
+      return myDelegate;
+    }
+    finally {
+      StringBuilderSpinAllocator.dispose(buffer);
+    }
+  }
+
+  protected abstract void build(@NotNull StringBuilder holder, int maxLength);
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/HtmlTransferableData.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/HtmlTransferableData.java
new file mode 100644
index 0000000..ea200c2
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/HtmlTransferableData.java
@@ -0,0 +1,221 @@
+/*
+ * Copyright 2000-2014 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.editor.richcopy.view;
+
+import com.intellij.openapi.editor.richcopy.model.ColorRegistry;
+import com.intellij.openapi.editor.richcopy.model.FontNameRegistry;
+import com.intellij.openapi.editor.richcopy.model.MarkupHandler;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import com.intellij.util.StringBuilderSpinAllocator;
+import com.intellij.util.ui.UIUtil;
+import gnu.trove.TIntObjectHashMap;
+import org.jetbrains.annotations.NotNull;
+
+import java.awt.*;
+import java.awt.datatransfer.DataFlavor;
+
+/**
+ * @author Denis Zhdanov
+ * @since 3/28/13 1:06 PM
+ */
+public class HtmlTransferableData extends AbstractSyntaxAwareReaderTransferableData implements MarkupHandler {
+
+  @NotNull public static final DataFlavor FLAVOR = new DataFlavor("text/html;class=java.io.Reader", "HTML text");
+
+  private StringBuilder    myResultBuffer;
+  private ColorRegistry    myColorRegistry;
+  private FontNameRegistry myFontNameRegistry;
+
+  private int     myForeground;
+  private int     myBackground;
+  private int     myFontFamily;
+  private boolean myBold;
+  private boolean myItalic;
+
+  private final TIntObjectHashMap<String> myColors = new TIntObjectHashMap<String>();
+
+  public HtmlTransferableData(@NotNull SyntaxInfo syntaxInfo) {
+    super(syntaxInfo, FLAVOR);
+  }
+
+  @Override
+  protected void build(@NotNull StringBuilder holder, int maxLength) {
+    myResultBuffer = holder;
+    myColorRegistry = mySyntaxInfo.getColorRegistry();
+    myFontNameRegistry = mySyntaxInfo.getFontNameRegistry();
+    try {
+      buildColorMap();
+      myResultBuffer.append("<pre style=\"background-color:");
+      appendColor(myResultBuffer, mySyntaxInfo.getDefaultBackground());
+      myResultBuffer.append(';');
+      if (myFontNameRegistry.size() == 1) {
+        appendFontFamilyRule(myResultBuffer, myFontNameRegistry.getAllIds()[0]);
+        myFontNameRegistry = null;
+      }
+      appendFontSizeRule(myResultBuffer, mySyntaxInfo.getSingleFontSize());
+      myResultBuffer.append("\" bgcolor=\"");
+      appendColor(myResultBuffer, mySyntaxInfo.getDefaultBackground());
+      myResultBuffer.append("\">");
+
+      SyntaxInfo.MarkupIterator it = mySyntaxInfo.new MarkupIterator();
+      try {
+        while(it.hasNext()) {
+          it.processNext(this);
+          if (myResultBuffer.length() > maxLength) {
+            myResultBuffer.append("... truncated ...");
+            break;
+          }
+        }
+      }
+      finally {
+        it.dispose();
+      }
+      myResultBuffer.append("</pre>");
+    }
+    finally {
+      myResultBuffer = null;
+      myColorRegistry = null;
+      myFontNameRegistry = null;
+      myColors.clear();
+    }
+  }
+
+  private void defineForeground(int id, @NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
+    myResultBuffer.append("<font color=\"");
+    appendColor(myResultBuffer, id);
+    myResultBuffer.append("\">");
+    styleBuffer.append("color:");
+    appendColor(styleBuffer, id);
+    styleBuffer.append(";");
+    closeTagBuffer.insert(0, "</font>");
+  }
+
+  private void defineBackground(int id, @NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
+    myResultBuffer.append("<font bgcolor=\"");
+    appendColor(myResultBuffer, id);
+    myResultBuffer.append("\">");
+    styleBuffer.append("background-color:");
+    appendColor(styleBuffer, id);
+    styleBuffer.append(";");
+    closeTagBuffer.insert(0, "</font>");
+  }
+
+  private void defineBold(@NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
+    myResultBuffer.append("<b>");
+    styleBuffer.append("font-weight:bold;");
+    closeTagBuffer.insert(0, "</b>");
+  }
+
+  private void defineItalic(@NotNull StringBuilder styleBuffer, @NotNull StringBuilder closeTagBuffer) {
+    myResultBuffer.append("<i>");
+    styleBuffer.append("font-style:italic;");
+    closeTagBuffer.insert(0, "</i>");
+  }
+  
+  private void appendColor(StringBuilder builder, int id) {
+    builder.append(myColors.get(id));
+  }
+
+  private void buildColorMap() {
+    for (int id : myColorRegistry.getAllIds()) {
+      StringBuilder b = new StringBuilder("#");
+      UIUtil.appendColor(myColorRegistry.dataById(id), b);
+      myColors.put(id, b.toString());
+    }
+  }
+
+  private void appendFontFamilyRule(@NotNull StringBuilder styleBuffer, int fontFamilyId) {
+    styleBuffer.append("font-family:'").append(myFontNameRegistry.dataById(fontFamilyId)).append("';");
+  }
+
+  private static void appendFontSizeRule(@NotNull StringBuilder styleBuffer, int fontSize) {
+    styleBuffer.append("font-size:").append(fontSize).append("pt;");
+  }
+
+  @Override
+  public void handleText(int startOffset, int endOffset) {
+    boolean formattedText = myForeground > 0 || myBackground > 0 || myFontFamily > 0 || myBold || myItalic;
+    if (!formattedText) {
+      escapeAndAdd(startOffset, endOffset);
+      return;
+    }
+
+    StringBuilder styleBuffer = StringBuilderSpinAllocator.alloc();
+    StringBuilder closeTagBuffer = StringBuilderSpinAllocator.alloc();
+    try {
+      if (myForeground > 0) {
+        defineForeground(myForeground, styleBuffer, closeTagBuffer);
+      }
+      if (myBackground > 0) {
+        defineBackground(myBackground, styleBuffer, closeTagBuffer);
+      }
+      if (myBold) {
+        defineBold(styleBuffer, closeTagBuffer);
+      }
+      if (myItalic) {
+        defineItalic(styleBuffer, closeTagBuffer);
+      }
+      if (myFontFamily > 0) {
+        appendFontFamilyRule(styleBuffer, myFontFamily);
+      }
+      myResultBuffer.append("<span style=\"");
+      myResultBuffer.append(styleBuffer);
+      myResultBuffer.append("\">");
+      escapeAndAdd(startOffset, endOffset);
+      myResultBuffer.append("</span>");
+      myResultBuffer.append(closeTagBuffer);
+    }
+    finally {
+      StringBuilderSpinAllocator.dispose(styleBuffer);
+      StringBuilderSpinAllocator.dispose(closeTagBuffer);
+    }
+  }
+
+  private void escapeAndAdd(int start, int end) {
+    for (int i = start; i < end; i++) {
+      char c = myRawText.charAt(i);
+      switch (c) {
+        case '<': myResultBuffer.append("&lt;"); break;
+        case '>': myResultBuffer.append("&gt;"); break;
+        case '&': myResultBuffer.append("&amp;"); break;
+        default: myResultBuffer.append(c);
+      }
+    }
+  }
+
+  @Override
+  public void handleForeground(int foregroundId) throws Exception {
+    myForeground = foregroundId;
+  }
+
+  @Override
+  public void handleBackground(int backgroundId) throws Exception {
+    myBackground = backgroundId;
+  }
+
+  @Override
+  public void handleFont(int fontNameId) throws Exception {
+    if (myFontNameRegistry != null) {
+      myFontFamily = fontNameId;
+    }
+  }
+
+  @Override
+  public void handleStyle(int style) throws Exception {
+    myBold = (Font.BOLD & style) != 0;
+    myItalic = (Font.ITALIC & style) != 0;
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/InputStreamTransferableData.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/InputStreamTransferableData.java
deleted file mode 100644
index 29ee172..0000000
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/InputStreamTransferableData.java
+++ /dev/null
@@ -1,83 +0,0 @@
-/*
- * Copyright 2000-2014 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.editor.richcopy.view;
-
-import com.intellij.codeInsight.editorActions.TextBlockTransferableData;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.awt.datatransfer.DataFlavor;
-import java.io.ByteArrayInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-
-/**
- * @author Denis Zhdanov
- * @since 3/28/13 1:20 PM
- */
-public class InputStreamTransferableData extends InputStream implements TextBlockTransferableData
-{
-  @NotNull
-  private final DataFlavor myDataFlavor;
-  @Nullable
-  private InputStream myDelegate;
-
-  public InputStreamTransferableData(@NotNull byte[] data, @NotNull DataFlavor flavor) {
-    myDataFlavor = flavor;
-    myDelegate = new ByteArrayInputStream(data);
-  }
-
-  @Override
-  public DataFlavor getFlavor() {
-    return myDelegate == null ? null : myDataFlavor;
-  }
-
-  @Override
-  public int getOffsetCount() {
-    return 0;
-  }
-
-  @Override
-  public int getOffsets(int[] offsets, int index) {
-    return index;
-  }
-
-  @Override
-  public int setOffsets(int[] offsets, int index) {
-    return index;
-  }
-
-  @Override
-  public int read() throws IOException {
-    if (myDelegate == null) {
-      return -1;
-    }
-    return myDelegate.read();
-  }
-
-  @Override
-  public int read(@NotNull byte[] b, int off, int len) throws IOException {
-    if (myDelegate == null) {
-      return -1;
-    }
-    return myDelegate.read(b, off, len);
-  }
-
-  @Override
-  public void close() throws IOException {
-    myDelegate = null;
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/RawTextHolder.java
similarity index 77%
copy from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
copy to platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/RawTextHolder.java
index 91140f2..f24d780 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/RawTextHolder.java
@@ -13,13 +13,8 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package com.intellij.openapi.editor.richcopy.view;
 
-allprojects { project ->
-  if(project.name == 'buildSrc') {
-    apply plugin: 'groovy'
-    dependencies {
-      compile gradleApi()
-      compile localGroovy()
-    }
-  }
-}
\ No newline at end of file
+public interface RawTextHolder {
+  void setRawText(String rawText);
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/ReaderTransferableData.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/ReaderTransferableData.java
deleted file mode 100644
index 6deea2c..0000000
--- a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/ReaderTransferableData.java
+++ /dev/null
@@ -1,84 +0,0 @@
-/*
- * Copyright 2000-2014 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.editor.richcopy.view;
-
-import com.intellij.codeInsight.editorActions.TextBlockTransferableData;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.awt.datatransfer.DataFlavor;
-import java.io.IOException;
-import java.io.Reader;
-import java.io.StringReader;
-
-/**
- * @author Denis Zhdanov
- * @since 3/28/13 7:09 PM
- */
-public class ReaderTransferableData extends Reader implements TextBlockTransferableData
-{
-  @NotNull
-  private final DataFlavor myDataFlavor;
-  @Nullable
-  private Reader myDelegate;
-
-  @SuppressWarnings("AbstractMethodCallInConstructor")
-  public ReaderTransferableData(@NotNull String data, @NotNull DataFlavor dataFlavor) {
-    myDataFlavor = dataFlavor;
-    myDelegate = new StringReader(data);
-  }
-
-  @Override
-  public DataFlavor getFlavor() {
-    return myDelegate == null ? null : myDataFlavor;
-  }
-
-  @Override
-  public int getOffsetCount() {
-    return 0;
-  }
-
-  @Override
-  public int getOffsets(int[] offsets, int index) {
-    return index;
-  }
-
-  @Override
-  public int setOffsets(int[] offsets, int index) {
-    return index;
-  }
-
-  @Override
-  public int read() throws IOException {
-    if (myDelegate == null) {
-      return -1;
-    }
-    return myDelegate.read();
-  }
-
-  @Override
-  public int read(@NotNull char[] cbuf, int off, int len) throws IOException {
-    if (myDelegate == null) {
-      return -1;
-    }
-    return myDelegate.read(cbuf, off, len);
-  }
-
-  @Override
-  public void close() throws IOException {
-    myDelegate = null;
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/RtfTransferableData.java b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/RtfTransferableData.java
new file mode 100644
index 0000000..d37da66
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/editor/richcopy/view/RtfTransferableData.java
@@ -0,0 +1,218 @@
+/*
+ * Copyright 2000-2014 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.editor.richcopy.view;
+
+import com.intellij.openapi.editor.richcopy.model.ColorRegistry;
+import com.intellij.openapi.editor.richcopy.model.FontNameRegistry;
+import com.intellij.openapi.editor.richcopy.model.MarkupHandler;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
+import org.jetbrains.annotations.NotNull;
+
+import java.awt.*;
+import java.awt.datatransfer.DataFlavor;
+
+public class RtfTransferableData extends AbstractSyntaxAwareInputStreamTransferableData {
+
+  @NotNull public static final DataFlavor FLAVOR = new DataFlavor("text/rtf;class=java.io.InputStream", "RTF text");
+
+  @NotNull private static final String HEADER_PREFIX = "{\\rtf1\\ansi\\deff0";
+  @NotNull private static final String HEADER_SUFFIX = "}";
+  @NotNull private static final String TAB           = "\\tab\n";
+  @NotNull private static final String NEW_LINE      = "\\line\n";
+  @NotNull private static final String BOLD          = "\\b";
+  @NotNull private static final String ITALIC        = "\\i";
+  @NotNull private static final String PLAIN         = "\\plain\n";
+
+  public RtfTransferableData(@NotNull SyntaxInfo syntaxInfo) {
+    super(syntaxInfo, FLAVOR);
+  }
+
+  @Override
+  protected void build(@NotNull final StringBuilder holder, final int maxLength) {
+    header(mySyntaxInfo, holder, new Runnable() {
+      @Override
+      public void run() {
+        rectangularBackground(mySyntaxInfo, holder, new Runnable() {
+          @Override
+          public void run() {
+            content(mySyntaxInfo, holder, myRawText, maxLength);
+          }
+        });
+      }
+    });
+  }
+
+  @NotNull
+  @Override
+  protected String getCharset() {
+    return "US-ASCII";
+  }
+
+  private static void header(@NotNull SyntaxInfo syntaxInfo, @NotNull StringBuilder buffer, @NotNull Runnable next) {
+    buffer.append(HEADER_PREFIX);
+
+    // Color table.
+    buffer.append("{\\colortbl;");
+    ColorRegistry colorRegistry = syntaxInfo.getColorRegistry();
+    for (int id : colorRegistry.getAllIds()) {
+      Color color = colorRegistry.dataById(id);
+      buffer.append(String.format("\\red%d\\green%d\\blue%d;", color.getRed(), color.getGreen(), color.getBlue()));
+    }
+    buffer.append("}\n");
+    
+    // Font table.
+    buffer.append("{\\fonttbl");
+    FontNameRegistry fontNameRegistry = syntaxInfo.getFontNameRegistry();
+    for (int id : fontNameRegistry.getAllIds()) {
+      String fontName = fontNameRegistry.dataById(id);
+      buffer.append(String.format("{\\f%d %s;}", id, fontName));
+    }
+    buffer.append("}\n");
+
+    next.run();
+    buffer.append(HEADER_SUFFIX);
+  }
+
+  private static void rectangularBackground(@NotNull SyntaxInfo syntaxInfo, @NotNull StringBuilder buffer, @NotNull Runnable next) {
+    buffer.append("\n\\s0\\box").append("\\cbpat").append(syntaxInfo.getDefaultBackground());
+    saveBackground(buffer, syntaxInfo.getDefaultBackground());
+    next.run();
+  }
+
+  private static void content(@NotNull SyntaxInfo syntaxInfo, @NotNull StringBuilder buffer, @NotNull String rawText, int maxLength) {
+    MyVisitor visitor = new MyVisitor(buffer, rawText, syntaxInfo.getSingleFontSize());
+    SyntaxInfo.MarkupIterator it = syntaxInfo.new MarkupIterator();
+    try {
+      while(it.hasNext()) {
+        it.processNext(visitor);
+        if (buffer.length() > maxLength) {
+          buffer.append("... truncated ...");
+          break;
+        }
+      }
+    }
+    finally {
+      it.dispose();
+    }
+  }
+
+  private static void saveBackground(@NotNull StringBuilder buffer, int id) {
+    buffer.append("\\cb").append(id);
+  }
+
+  private static void saveForeground(@NotNull StringBuilder buffer, int id) {
+    buffer.append("\\cf").append(id);
+  }
+
+  private static void saveFontName(@NotNull StringBuilder buffer, int id) {
+    buffer.append("\\f").append(id);
+  }
+
+  private static void saveFontSize(@NotNull StringBuilder buffer, int size) {
+    buffer.append("\\fs").append(size * 2);
+  }
+
+  private static class MyVisitor implements MarkupHandler {
+
+    @NotNull private final StringBuilder myBuffer;
+    @NotNull private final String        myRawText;
+
+    private int myBackgroundId = -1;
+    private int myForegroundId = -1;
+    private int myFontNameId   = -1;
+    private int myFontStyle    = -1;
+    private int myFontSize     = -1;
+
+    MyVisitor(@NotNull StringBuilder buffer, @NotNull String rawText, int fontSize) {
+      myBuffer = buffer;
+      myRawText = rawText;
+      myFontSize = fontSize;
+    }
+
+    @Override
+    public void handleText(int startOffset, int endOffset) throws Exception {
+      myBuffer.append("\n");
+      for (int i = startOffset; i < endOffset; i++) {
+        char c = myRawText.charAt(i);
+        if (c > 127) {
+          // Escape non-ascii symbols.
+          myBuffer.append(String.format("\\u%04d?", (int)c));
+          continue;
+        }
+
+        switch (c) {
+          case '\t':
+            myBuffer.append(TAB);
+            continue;
+          case '\n':
+            myBuffer.append(NEW_LINE);
+            continue;
+          case '\\':
+          case '{':
+          case '}':
+            myBuffer.append('\\');
+        }
+        myBuffer.append(c);
+      }
+    }
+
+    @Override
+    public void handleForeground(int foregroundId) throws Exception {
+      saveForeground(myBuffer, foregroundId);
+      myForegroundId = foregroundId;
+    }
+
+    @Override
+    public void handleBackground(int backgroundId) throws Exception {
+      saveBackground(myBuffer, backgroundId);
+      myBackgroundId = backgroundId;
+    }
+
+    @Override
+    public void handleFont(int fontNameId) throws Exception {
+      saveFontName(myBuffer, fontNameId);
+      myFontNameId = fontNameId;
+    }
+
+    @Override
+    public void handleStyle(int style) throws Exception {
+      // Reset formatting settings
+      myBuffer.append(PLAIN);
+
+      // Restore target formatting settings.
+      if (myForegroundId >= 0) {
+        saveForeground(myBuffer, myForegroundId);
+      }
+      if (myBackgroundId >= 0) {
+        saveBackground(myBuffer, myBackgroundId);
+      }
+      if (myFontNameId >= 0) {
+        saveFontName(myBuffer, myFontNameId);
+      }
+      if (myFontSize > 0) {
+        saveFontSize(myBuffer, myFontSize);
+      }
+
+      myFontStyle = style;
+      if ((myFontStyle & Font.ITALIC) > 0) {
+        myBuffer.append(ITALIC);
+      }
+      if ((myFontStyle & Font.BOLD) > 0) {
+        myBuffer.append(BOLD);
+      }
+    }
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.form b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.form
index 6edeb8f..858b072 100644
--- a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.form
+++ b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.form
@@ -3,7 +3,7 @@
   <grid id="27dc6" binding="myPanel" layout-manager="GridLayoutManager" row-count="4" column-count="1" 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="86" width="466" height="334"/>
+      <xy x="20" y="86" width="500" height="334"/>
     </constraints>
     <properties/>
     <clientProperties>
@@ -87,16 +87,6 @@
             <border type="none"/>
             <children/>
           </grid>
-          <component id="29b05" class="javax.swing.JCheckBox" binding="myAutodetectUTFEncodedFilesCheckBox" default-binding="true">
-            <constraints>
-              <grid row="0" column="2" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
-            </constraints>
-            <properties>
-              <horizontalAlignment value="2"/>
-              <horizontalTextPosition value="11"/>
-              <text resource-bundle="messages/IdeBundle" key="checkbox.autodetect.utf"/>
-            </properties>
-          </component>
           <component id="6435b" class="javax.swing.JLabel">
             <constraints>
               <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
diff --git a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java
index 196b861..e6c1ae9 100644
--- a/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java
+++ b/platform/lang-impl/src/com/intellij/openapi/vfs/encoding/FileEncodingConfigurable.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -49,7 +49,6 @@
   private EncodingFileTreeTable myTreeView;
   private JScrollPane myTreePanel;
   private JPanel myPanel;
-  private JCheckBox myAutodetectUTFEncodedFilesCheckBox;
   private JCheckBox myTransparentNativeToAsciiCheckBox;
   private JPanel myPropertiesFilesEncodingCombo;
   private final Ref<Charset> mySelectedCharsetForPropertiesFiles = new Ref<Charset>();
@@ -145,7 +144,6 @@
     Map<VirtualFile, Charset> mapping = EncodingProjectManager.getInstance(myProject).getAllMappings();
     boolean same = editing.equals(mapping)
        && Comparing.equal(encodingManager.getDefaultCharsetForPropertiesFiles(null), mySelectedCharsetForPropertiesFiles.get())
-       && encodingManager.isUseUTFGuessing(null) == myAutodetectUTFEncodedFilesCheckBox.isSelected()
        && encodingManager.isNative2AsciiForPropertiesFiles() == myTransparentNativeToAsciiCheckBox.isSelected()
       ;
     return !same;
@@ -179,7 +177,6 @@
     encodingManager.setMapping(result);
     encodingManager.setDefaultCharsetForPropertiesFiles(null, mySelectedCharsetForPropertiesFiles.get());
     encodingManager.setNative2AsciiForPropertiesFiles(null, myTransparentNativeToAsciiCheckBox.isSelected());
-    encodingManager.setUseUTFGuessing(null, myAutodetectUTFEncodedFilesCheckBox.isSelected());
 
     Charset ideCharset = mySelectedIdeCharset.get();
     EncodingManager.getInstance().setDefaultCharsetName(ideCharset == null ? "" : ideCharset.name());
@@ -189,7 +186,6 @@
   public void reset() {
     EncodingProjectManager encodingManager = EncodingProjectManager.getInstance(myProject);
     myTreeView.reset(encodingManager.getAllMappings());
-    myAutodetectUTFEncodedFilesCheckBox.setSelected(encodingManager.isUseUTFGuessing(null));
     myTransparentNativeToAsciiCheckBox.setSelected(encodingManager.isNative2AsciiForPropertiesFiles());
     mySelectedCharsetForPropertiesFiles.set(encodingManager.getDefaultCharsetForPropertiesFiles(null));
 
diff --git a/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java b/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java
index 73c7b4a..355e8a46 100644
--- a/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java
+++ b/platform/lang-impl/src/com/intellij/platform/templates/github/ZipUtil.java
@@ -131,9 +131,9 @@
       else {
         dirToMove = unzipToDir;
       }
-      if (!FileUtil.moveDirWithContent(dirToMove, targetDir)) {
-        FileUtil.copyDirContent(dirToMove, targetDir);
-      }
+      // Don't "FileUtil.moveDirWithContent(dirToMove, targetDir)"
+      // because a file moved with "java.io.File.renameTo" won't inherit its new parent's permissions
+      FileUtil.copyDirContent(dirToMove, targetDir);
       FileUtil.delete(unzipToDir);
     }
   }
diff --git a/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java
new file mode 100644
index 0000000..537d997
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/psi/impl/cache/impl/id/IdIndexImpl.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2000-2014 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.cache.impl.id;
+
+import com.intellij.openapi.util.ThreadLocalCachedIntArray;
+import com.intellij.util.indexing.CustomInputsIndexFileBasedIndexExtension;
+import com.intellij.util.io.DataExternalizer;
+import com.intellij.util.io.DataInputOutputUtil;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.DataInput;
+import java.io.DataOutput;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Collection;
+
+public class IdIndexImpl extends IdIndex implements CustomInputsIndexFileBasedIndexExtension<IdIndexEntry> {
+  private static final ThreadLocalCachedIntArray spareBufferLocal = new ThreadLocalCachedIntArray();
+
+  @NotNull
+  @Override
+  public DataExternalizer<Collection<IdIndexEntry>> createExternalizer() {
+    return new DataExternalizer<Collection<IdIndexEntry>>() {
+      @Override
+      public void save(@NotNull DataOutput out, @NotNull Collection<IdIndexEntry> value) throws IOException {
+        int size = value.size();
+        final int[] values = spareBufferLocal.getBuffer(size);
+        int ptr = 0;
+        for(IdIndexEntry ie:value) {
+          values[ptr++] = ie.getWordHashCode();
+        }
+        Arrays.sort(values, 0, size);
+        DataInputOutputUtil.writeINT(out, size);
+        int prev = 0;
+        for(int i = 0; i < size; ++i) {
+          DataInputOutputUtil.writeLONG(out, (long)values[i] - prev);
+          prev = values[i];
+        }
+      }
+
+      @Override
+      public Collection<IdIndexEntry> read(@NotNull DataInput in) throws IOException {
+        int length = DataInputOutputUtil.readINT(in);
+        ArrayList<IdIndexEntry> entries = new ArrayList<IdIndexEntry>(length);
+        int prev = 0;
+        while(length-- > 0) {
+          final int l = (int)(DataInputOutputUtil.readLONG(in) + prev);
+          entries.add(new IdIndexEntry(l));
+          prev = l;
+        }
+        return entries;
+      }
+    };
+  }
+}
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java
index 5693e3a..5035378 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureGestureDetector.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +18,6 @@
 import com.intellij.codeInsight.template.TemplateManager;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.command.CommandProcessor;
-import com.intellij.openapi.components.ProjectComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
@@ -56,7 +55,7 @@
  * User: anna
  * Date: Sep 6, 2010
  */
-public class ChangeSignatureGestureDetector extends PsiTreeChangeAdapter implements ProjectComponent, EditorFactoryListener {
+public class ChangeSignatureGestureDetector extends PsiTreeChangeAdapter implements EditorFactoryListener, Disposable {
   private final Map<VirtualFile, MyDocumentChangeAdapter> myListenerMap = new HashMap<VirtualFile, MyDocumentChangeAdapter>();
   private static final Logger LOG = Logger.getInstance("#" + ChangeSignatureGestureDetector.class.getName());
   private boolean myDeaf = false;
@@ -79,6 +78,14 @@
     myFileEditorManager = fileEditorManager;
     myProject = project;
     myTemplateManager = templateManager;
+    myPsiManager.addPsiTreeChangeListener(this, this);
+    EditorFactory.getInstance().addEditorFactoryListener(this, this);
+    Disposer.register(this, new Disposable() {
+      @Override
+      public void dispose() {
+        LOG.assertTrue(myListenerMap.isEmpty(), myListenerMap);
+      }
+    });
   }
 
   public static ChangeSignatureGestureDetector getInstance(Project project){
@@ -138,37 +145,6 @@
   }
 
   @Override
-  public void projectOpened() {
-    myPsiManager.addPsiTreeChangeListener(this);
-    EditorFactory.getInstance().addEditorFactoryListener(this, myProject);
-    Disposer.register(myProject, new Disposable() {
-      @Override
-      public void dispose() {
-        myPsiManager.removePsiTreeChangeListener(ChangeSignatureGestureDetector.this);
-        LOG.assertTrue(myListenerMap.isEmpty(), myListenerMap);
-      }
-    });
-  }
-
-  @Override
-  public void projectClosed() {
-  }
-
-  @NotNull
-  @Override
-  public String getComponentName() {
-    return "ChangeSignatureGestureDetector";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   public void beforeChildRemoval(@NotNull PsiTreeChangeEvent event) {
     final PsiElement child = event.getChild();
     if (child instanceof PsiFile) {
@@ -396,4 +372,9 @@
       myCurrentInfo = null;
     }
   }
+
+  @Override
+  public void dispose() {
+
+  }
 }
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 f739815..f3afcf2 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
@@ -1792,6 +1792,9 @@
     final UpdatableIndex<?, ?, FileContent> index = getIndex(indexId);
     assert index != null;
 
+    if (currentFC != null && currentFC.getUserData(ourPhysicalContentKey) == null) {
+      currentFC.putUserData(ourPhysicalContentKey, Boolean.TRUE);
+    }
     // important: no hard referencing currentFC to avoid OOME, the methods introduced for this purpose!
     final Computable<Boolean> update = index.update(inputId, currentFC);
 
@@ -1801,6 +1804,8 @@
     );
   }
 
+  static final Key<Boolean> ourPhysicalContentKey = Key.create("physical.content.flag");
+
   @NotNull
   private Runnable createIndexedStampUpdateRunnable(@NotNull final ID<?, ?> indexId,
                                                     @NotNull final VirtualFile file,
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 1405551..ad21d38 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
@@ -277,7 +277,7 @@
 
   @NotNull
   @Override
-  public final Computable<Boolean> update(final int inputId, @Nullable final Input content) {
+  public final Computable<Boolean> update(final int inputId, @Nullable Input content) {
 
     final Map<Key, Value> data = content != null ? myIndexer.map(content) : Collections.<Key, Value>emptyMap();
 
@@ -286,24 +286,41 @@
     final NotNullComputable<Collection<Key>> oldKeysGetter;
     final int savedInputId;
 
-    if (myHasSnapshotMapping && !((MemoryIndexStorage)getStorage()).isBufferingEnabled()) {
-      oldKeysGetter = new NotNullComputable<Collection<Key>>() {
+    boolean weProcessPhysicalContent = content == null ||
+                                       (content instanceof FileContent &&
+                                        ((FileContent)content).getUserData(FileBasedIndexImpl.ourPhysicalContentKey) != null);
+
+    if (myHasSnapshotMapping && weProcessPhysicalContent) {
+      try { // optimistically (out of index update write section) read current snapshot keys for file
+        final Integer hashId = myInputsSnapshotMapping.get(inputId);
+        final Collection<Key> keys = hashId != null ? mySnapshotMapping.get(hashId): null;
+
+        oldKeysGetter = new NotNullComputable<Collection<Key>>() {
         @NotNull
         @Override
         public Collection<Key> compute() {
-          try {
-            Integer hashId = myInputsSnapshotMapping.get(inputId);
-            Collection<Key> keys = hashId != null ? mySnapshotMapping.get(hashId): null;
-            return keys == null ? Collections.<Key>emptyList() : keys;
-          } catch (IOException e) {
-            throw new RuntimeException(e);
+            try {
+              Integer currentHashId = myInputsSnapshotMapping.get(inputId);
+              Collection<Key> currentKeys;
+              if ((currentHashId == null && hashId == null)  || (currentHashId != null && currentHashId.equals(hashId))) {
+                currentKeys = keys;
+              } else { // optimistic reading file's current keys failed
+                currentKeys = currentHashId != null ? mySnapshotMapping.get(currentHashId): null;
+              }
+
+              return currentKeys == null ? Collections.<Key>emptyList() : currentKeys;
+            } catch (IOException e) {
+              throw new RuntimeException(e);
+            }
           }
-        }
-      };
-      try {
+        };
+
         if (content instanceof FileContent) {
           FileContent fileContent = (FileContent)content;
           savedInputId = ContentHashesSupport.calcContentHashIdWithFileType(fileContent.getContent(), fileContent.getFileType());
+          if (!mySnapshotMapping.containsMapping(savedInputId)) { // save current snapshot keys out of index update write section
+            mySnapshotMapping.put(savedInputId, data.keySet());
+          }
         } else {
           savedInputId = NULL_MAPPING;
         }
@@ -395,9 +412,6 @@
 
       try {
         if (myHasSnapshotMapping && !((MemoryIndexStorage)getStorage()).isBufferingEnabled()) {
-          if (savedInputId != NULL_MAPPING && !mySnapshotMapping.containsMapping(savedInputId)) {
-            mySnapshotMapping.put(savedInputId, newData.keySet());
-          }
           myInputsSnapshotMapping.put(inputId, savedInputId);
         } else if (myInputsIndex != null) {
           final Set<Key> newKeys = newData.keySet();
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerMap.java b/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerMap.java
index 3bf0ece..8c3c675 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerMap.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/ValueContainerMap.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.util.indexing;
 
+import com.intellij.openapi.util.ThreadLocalCachedIntArray;
 import com.intellij.openapi.util.io.BufferExposingByteArrayOutputStream;
 import com.intellij.util.io.*;
 import com.intellij.util.io.DataOutputStream;
@@ -91,20 +92,52 @@
     }
 
     public static void saveInvalidateCommand(final DataOutput out, int inputId) throws IOException {
-      DataInputOutputUtil.writeSINT(out, -inputId);
+      DataInputOutputUtil.writeINT(out, -inputId);
     }
+    private static final ThreadLocalCachedIntArray ourSpareBuffer = new ThreadLocalCachedIntArray();
 
     private void saveImpl(@NotNull DataOutput out, @NotNull final ValueContainer<T> container) throws IOException {
-      DataInputOutputUtil.writeSINT(out, container.size());
+      DataInputOutputUtil.writeINT(out, container.size());
+
       for (final Iterator<T> valueIterator = container.getValueIterator(); valueIterator.hasNext();) {
         final T value = valueIterator.next();
         myExternalizer.save(out, value);
+        ValueContainer.IntIterator ids = container.getInputIdsIterator(value);
+        DataInputOutputUtil.writeINT(out, ids.size());
+        if (ids.size() == 1) {
+          DataInputOutputUtil.writeINT(out, ids.next()); // most common 90% case during index building
+        } else {
+          // serialize positive file ids with delta encoding after sorting numbers via bitset
+          // todo it would be nice to have compressed random access serializable bitset or at least file ids sorted
+          int max = 0, min = Integer.MAX_VALUE;
 
-        final ValueContainer.IntIterator ids = container.getInputIdsIterator(value);
-        DataInputOutputUtil.writeSINT(out, ids.size());
-        while (ids.hasNext()) {
-          final int id = ids.next();
-          DataInputOutputUtil.writeSINT(out, id);
+          while (ids.hasNext()) {
+            final int id = ids.next();
+            max = Math.max(id, max);
+            min = Math.min(id, min);
+          }
+
+          assert min > 0;
+
+          final int offset = (min >> INT_BITS_SHIFT) << INT_BITS_SHIFT;
+          final int bitsLength = ((max - offset) >> INT_BITS_SHIFT) + 1;
+          final int[] bits = ourSpareBuffer.getBuffer(bitsLength);
+          for(int i = 0; i < bitsLength; ++i) bits[i] = 0;
+
+          ids = container.getInputIdsIterator(value);
+          while (ids.hasNext()) {
+            final int id = ids.next() - offset;
+            bits[id >> INT_BITS_SHIFT] |= (1 << (id));
+          }
+
+          int pos = nextSetBit(0, bits, bitsLength);
+          int prev = 0;
+
+          while (pos != -1) {
+            DataInputOutputUtil.writeINT(out, pos + offset - prev);
+            prev = pos + offset;
+            pos = nextSetBit(pos + 1, bits, bitsLength);
+          }
         }
       }
     }
@@ -116,7 +149,7 @@
       final ValueContainerImpl<T> valueContainer = new ValueContainerImpl<T>();
 
       while (stream.available() > 0) {
-        final int valueCount = DataInputOutputUtil.readSINT(in);
+        final int valueCount = DataInputOutputUtil.readINT(in);
         if (valueCount < 0) {
           valueContainer.removeAssociatedValue(-valueCount);
           valueContainer.setNeedsCompacting(true);
@@ -124,17 +157,39 @@
         else {
           for (int valueIdx = 0; valueIdx < valueCount; valueIdx++) {
             final T value = myExternalizer.read(in);
-            final int idCount = DataInputOutputUtil.readSINT(in);
+            final int idCount = DataInputOutputUtil.readINT(in);
             valueContainer.ensureFileSetCapacityForValue(value, idCount);
+            int prev = 0;
             for (int i = 0; i < idCount; i++) {
-              final int id = DataInputOutputUtil.readSINT(in);
-              valueContainer.addValue(id, value);
+              final int id = DataInputOutputUtil.readINT(in);
+              valueContainer.addValue(prev + id, value);
+              prev += id;
             }
           }
         }
       }
       return valueContainer;
     }
+
+    private static final int INT_BITS_SHIFT = 5;
+    private static int nextSetBit(int bitIndex, int[] bits, int bitsLength) {
+      int wordIndex = bitIndex >> INT_BITS_SHIFT;
+      if (wordIndex >= bitsLength) {
+        return -1;
+      }
+
+      int word = bits[wordIndex] & (-1 << bitIndex);
+
+      while (true) {
+        if (word != 0) {
+          return (wordIndex << INT_BITS_SHIFT) + Long.numberOfTrailingZeros(word);
+        }
+        if (++wordIndex == bitsLength) {
+          return -1;
+        }
+        word = bits[wordIndex];
+      }
+    }
   }
 
 }
diff --git a/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java b/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java
index 5f5fecf..eb2936a 100644
--- a/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java
+++ b/platform/lang-impl/src/com/intellij/webcore/packaging/InstalledPackagesPanel.java
@@ -44,7 +44,8 @@
 
   protected final JBTable myPackagesTable;
   private DefaultTableModel myPackagesTableModel;
-  protected PackageManagementService myPackageManagementService;
+  // can be accessed from any thread
+  protected volatile PackageManagementService myPackageManagementService;
   protected final Project myProject;
   protected final PackagesNotificationPanel myNotificationArea;
   protected final List<Consumer<Sdk>> myPathChangedListeners = ContainerUtil.createLockFreeCopyOnWriteList();
@@ -424,7 +425,7 @@
           final boolean shouldFetchLatestVersionsForOnlyInstalledPackages = shouldFetchLatestVersionsForOnlyInstalledPackages();
           if (cache.isEmpty()) {
             if (!shouldFetchLatestVersionsForOnlyInstalledPackages) {
-              refreshLatestVersions();
+              refreshLatestVersions(packageManagementService);
             }
           }
           UIUtil.invokeLaterIfNeeded(new Runnable() {
@@ -514,28 +515,30 @@
     return false;
   }
 
-  private void refreshLatestVersions() {
+  private void refreshLatestVersions(@NotNull final PackageManagementService packageManagementService) {
     final Application application = ApplicationManager.getApplication();
     application.executeOnPooledThread(new Runnable() {
       @Override
       public void run() {
-        try {
-          List<RepoPackage> packages = myPackageManagementService.reloadAllPackages();
-          final Map<String, RepoPackage> packageMap = buildNameToPackageMap(packages);
-          application.invokeLater(new Runnable() {
-            @Override
-            public void run() {
-              for (int i = 0; i != myPackagesTableModel.getRowCount(); ++i) {
-                final InstalledPackage pyPackage = (InstalledPackage)myPackagesTableModel.getValueAt(i, 0);
-                final RepoPackage repoPackage = packageMap.get(pyPackage.getName());
-                myPackagesTableModel.setValueAt(repoPackage == null ? null : repoPackage.getLatestVersion(), i, 2);
+        if (packageManagementService == myPackageManagementService) {
+          try {
+            List<RepoPackage> packages = packageManagementService.reloadAllPackages();
+            final Map<String, RepoPackage> packageMap = buildNameToPackageMap(packages);
+            application.invokeLater(new Runnable() {
+              @Override
+              public void run() {
+                for (int i = 0; i != myPackagesTableModel.getRowCount(); ++i) {
+                  final InstalledPackage pyPackage = (InstalledPackage)myPackagesTableModel.getValueAt(i, 0);
+                  final RepoPackage repoPackage = packageMap.get(pyPackage.getName());
+                  myPackagesTableModel.setValueAt(repoPackage == null ? null : repoPackage.getLatestVersion(), i, 2);
+                }
+                myPackagesTable.setPaintBusy(false);
               }
-              myPackagesTable.setPaintBusy(false);
-            }
-          }, ModalityState.stateForComponent(myPackagesTable));
-        }
-        catch (IOException ignored) {
-          myPackagesTable.setPaintBusy(false);
+            }, ModalityState.stateForComponent(myPackagesTable));
+          }
+          catch (IOException ignored) {
+            myPackagesTable.setPaintBusy(false);
+          }
         }
       }
     });
diff --git a/platform/lang-impl/src/com/intellij/webcore/packaging/PackagesNotificationPanel.java b/platform/lang-impl/src/com/intellij/webcore/packaging/PackagesNotificationPanel.java
index 6796745..0795c482 100644
--- a/platform/lang-impl/src/com/intellij/webcore/packaging/PackagesNotificationPanel.java
+++ b/platform/lang-impl/src/com/intellij/webcore/packaging/PackagesNotificationPanel.java
@@ -22,7 +22,7 @@
  * @author yole
  */
 public class PackagesNotificationPanel {
-  private final JEditorPane myEditorPane = new JEditorPane();
+  private final JEditorPane myEditorPane = new MyNotificationPane();
   private final Project myProject;
   private final Map<String, Runnable> myLinkHandlers = new HashMap<String, Runnable>();
   private String myErrorTitle;
@@ -91,6 +91,10 @@
     myLinkHandlers.put(key, handler);
   }
 
+  public void removeAllLinkHandlers() {
+    myLinkHandlers.clear();
+  }
+
   public JComponent getComponent() {
     return myEditorPane;
   }
@@ -101,7 +105,8 @@
 
   private void showContent(String text, final Color background) {
     myEditorPane.removeAll();
-    myEditorPane.setText(UIUtil.toHtml(text));
+    String htmlText = text.startsWith("<html>") ? text : UIUtil.toHtml(text);
+    myEditorPane.setText(htmlText);
     myEditorPane.setBackground(background);
     myEditorPane.setVisible(true);
     myErrorTitle = null;
@@ -125,4 +130,15 @@
   public boolean hasLinkHandler(String key) {
     return myLinkHandlers.containsKey(key);
   }
+
+  private static class MyNotificationPane extends JEditorPane {
+    @Override
+    public Dimension getPreferredSize() {
+      // This trick makes text component to carry text over to the next line
+      // iff the text line width exceeds parent's width
+      Dimension dimension = super.getPreferredSize();
+      dimension.width = 0;
+      return dimension;
+    }
+  }
 }
diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java b/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java
index 632f549..5d3d7e2 100644
--- a/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java
+++ b/platform/lvcs-impl/src/com/intellij/history/integration/LocalHistoryImpl.java
@@ -128,7 +128,7 @@
   public void disposeComponent() {
     if (!isInitialized.getAndSet(false)) return;
 
-    int period = Registry.intValue("localHistory.daysToKeep") * 1000 * 60 * 60 * 24;
+    long period = Registry.intValue("localHistory.daysToKeep") * 1000L * 60L * 60L * 24L;
 
     VirtualFileManager fm = VirtualFileManager.getInstance();
     fm.removeVirtualFileListener(myEventDispatcher);
diff --git a/platform/platform-api/src/com/intellij/ide/GeneralSettings.java b/platform/platform-api/src/com/intellij/ide/GeneralSettings.java
index 3758a2a..f60ec2cd 100644
--- a/platform/platform-api/src/com/intellij/ide/GeneralSettings.java
+++ b/platform/platform-api/src/com/intellij/ide/GeneralSettings.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2014 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,8 +20,6 @@
 import com.intellij.openapi.components.ExportableApplicationComponent;
 import com.intellij.openapi.util.NamedJDOMExternalizable;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.vfs.CharsetToolkit;
-import com.intellij.openapi.vfs.encoding.EncodingManager;
 import org.intellij.lang.annotations.MagicConstant;
 import org.jdom.Element;
 import org.jetbrains.annotations.NonNls;
@@ -30,7 +28,6 @@
 import java.beans.PropertyChangeListener;
 import java.beans.PropertyChangeSupport;
 import java.io.File;
-import java.nio.charset.Charset;
 import java.util.List;
 
 public class GeneralSettings implements NamedJDOMExternalizable, ExportableApplicationComponent {
@@ -69,11 +66,6 @@
   @NonNls private static final String OPTION_AUTO_SAVE_IF_INACTIVE = "autoSaveIfInactive";
   @NonNls private static final String OPTION_USE_SAFE_WRITE = "useSafeWrite";
 
-  @Deprecated
-  @NonNls private static final String OPTION_CHARSET = "charset";
-  @Deprecated
-  @NonNls private static final String OPTION_UTFGUESSING = "UTFGuessing";
-
   @NonNls private static final String OPTION_USE_DEFAULT_BROWSER = "useDefaultBrowser";
   @NonNls private static final String OPTION_CONFIRM_EXTRACT_FILES = "confirmExtractFiles";
   @NonNls private static final String OPTION_USE_CYCLIC_BUFFER = "useCyclicBuffer";
@@ -83,13 +75,6 @@
   @NonNls private static final String OPTION_CYCLIC_BUFFER_SIZE = "cyclicBufferSize";
   @NonNls private static final String OPTION_LAST_PROJECT_LOCATION = "lastProjectLocation";
 
-  @Deprecated
-  private Charset myCharset;
-  @Deprecated
-  private boolean myUseUTFGuessing;
-  @Deprecated
-  private boolean oldCharsetSettingsHaveBeenRead;
-
   public static GeneralSettings getInstance(){
     return ApplicationManager.getApplication().getComponent(GeneralSettings.class);
   }
@@ -294,16 +279,6 @@
         safeWriteSettingRead = true;
       }
 
-      if (OPTION_CHARSET.equals(name)) {
-        //for migration
-        myCharset = CharsetToolkit.forName(value);
-        oldCharsetSettingsHaveBeenRead = true;
-      }
-      if (OPTION_UTFGUESSING.equals(name)) {
-        myUseUTFGuessing = Boolean.valueOf(value).booleanValue();
-        oldCharsetSettingsHaveBeenRead = true;
-      }
-
       if (OPTION_USE_DEFAULT_BROWSER.equals(name)) {
         try {
           myUseDefaultBrowser = Boolean.valueOf(value).booleanValue();
@@ -528,13 +503,4 @@
   public void setSearchInBackground(final boolean searchInBackground) {
     mySearchInBackground = searchInBackground;
   }
-
-  // returns true if something has been migrated
-  public boolean migrateCharsetSettingsTo(EncodingManager encodingProjectManager) {
-    if (oldCharsetSettingsHaveBeenRead) {
-      encodingProjectManager.setEncoding(null, myCharset);
-      encodingProjectManager.setUseUTFGuessing(null, myUseUTFGuessing);
-    }
-    return oldCharsetSettingsHaveBeenRead;
-  }
 }
\ No newline at end of file
diff --git a/platform/platform-api/src/com/intellij/ide/dnd/DnDSupport.java b/platform/platform-api/src/com/intellij/ide/dnd/DnDSupport.java
index 38f2eaf..cb4302a 100644
--- a/platform/platform-api/src/com/intellij/ide/dnd/DnDSupport.java
+++ b/platform/platform-api/src/com/intellij/ide/dnd/DnDSupport.java
@@ -271,8 +271,8 @@
                           disposable.get(),
                           dropActionHandler.get(),
                           cleanUp.get(),
-                          asSource.get(),
                           asTarget.get(),
+                          asSource.get(),
                           asNativeTarget.get());
       }
     };
diff --git a/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java b/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java
index 5260b97..8c38dfd 100644
--- a/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java
+++ b/platform/platform-api/src/com/intellij/openapi/MnemonicHelper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -15,6 +15,7 @@
  */
 package com.intellij.openapi;
 
+import com.intellij.openapi.actionSystem.CustomShortcutSet;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.util.registry.Registry;
@@ -111,4 +112,17 @@
     }
     myMnemonics.put(Integer.valueOf(mnemonic), text);
   }
+
+  /**
+   * Creates shortcut for mnemonic replacing standard Alt+Letter to Ctrl+Alt+Letter on Mac with jdk version newer than 6
+   * @param ch mnemonic letter
+   * @return shortcut for mnemonic
+   */
+  public static CustomShortcutSet createShortcut(char ch) {
+    Character mnemonic = Character.valueOf(ch);
+    String shortcut = SystemInfo.isMac && SystemInfo.isJavaVersionAtLeast("1.7") ?
+                      "control alt pressed " + mnemonic :
+                      "alt pressed " + mnemonic;
+    return CustomShortcutSet.fromString(shortcut);
+  }
 }
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 0f19ff2..0144cf4 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/DialogWrapper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -664,16 +664,14 @@
       final Set<JBOptionButton.OptionInfo> infos = eachOptionsButton.getOptionInfos();
       for (final JBOptionButton.OptionInfo eachInfo : infos) {
         if (eachInfo.getMnemonic() >= 0) {
-          final CustomShortcutSet sc =
-            new CustomShortcutSet(KeyStroke.getKeyStroke("alt pressed " + Character.valueOf((char)eachInfo.getMnemonic())));
-
+          final char mnemonic = (char)eachInfo.getMnemonic();
           new AnAction() {
             @Override
             public void actionPerformed(AnActionEvent e) {
               final JBOptionButton buttonToActivate = eachInfo.getButton();
               buttonToActivate.showPopup(eachInfo.getAction(), true);
             }
-          }.registerCustomShortcutSet(sc, getPeer().getRootPane());
+          }.registerCustomShortcutSet(MnemonicHelper.createShortcut(mnemonic), getPeer().getRootPane());
         }
       }
     }
diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java b/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java
index 44b8dcf..a8e353c 100644
--- a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java
+++ b/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingManager.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -42,6 +42,7 @@
   @NotNull
   public abstract Collection<Charset> getFavorites();
 
+  @Deprecated // does nothing
   public abstract void setUseUTFGuessing(VirtualFile virtualFile, boolean useUTFGuessing);
 
   public abstract boolean isNative2AsciiForPropertiesFiles();
diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java b/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java
index 2282163..93fe729 100644
--- a/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java
+++ b/platform/platform-api/src/com/intellij/openapi/vfs/encoding/EncodingProjectManager.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -15,11 +15,8 @@
  */
 package com.intellij.openapi.vfs.encoding;
 
-import com.intellij.openapi.components.PersistentStateComponent;
-import com.intellij.openapi.components.ProjectComponent;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.vfs.VirtualFile;
-import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
 
 import java.nio.charset.Charset;
@@ -28,7 +25,7 @@
 /**
  * @author cdr
  */
-public abstract class EncodingProjectManager extends EncodingManager implements ProjectComponent, PersistentStateComponent<Element> {
+public abstract class EncodingProjectManager extends EncodingManager {
   public static EncodingProjectManager getInstance(Project project) {
     return project.getComponent(EncodingProjectManager.class);
   }
diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/FileSystemInterface.java b/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/FileSystemInterface.java
index de808a9..4f57a0f 100644
--- a/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/FileSystemInterface.java
+++ b/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/FileSystemInterface.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -52,12 +52,17 @@
   /** @deprecated use PersistentFS interface if needed (to remove in IDEA 14) */
   boolean isSpecialFile(@NotNull VirtualFile file);
 
+  @NotNull
   VirtualFile createChildDirectory(@Nullable Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException;
+
+  @NotNull
   VirtualFile createChildFile(@Nullable Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException;
 
   void deleteFile(final Object requestor, @NotNull VirtualFile file) throws IOException;
   void moveFile(final Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile newParent) throws IOException;
   void renameFile(final Object requestor, @NotNull VirtualFile file, @NotNull String newName) throws IOException;
+
+  @NotNull
   VirtualFile copyFile(final Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile newParent, @NotNull String copyName) throws IOException;
 
   @NotNull
diff --git a/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java b/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java
index e5c056c..d0dc842 100644
--- a/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java
+++ b/platform/platform-api/src/com/intellij/openapi/vfs/newvfs/NewVirtualFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -21,19 +21,19 @@
 import com.intellij.openapi.vfs.VirtualFileListener;
 import com.intellij.openapi.vfs.VirtualFileManager;
 import com.intellij.openapi.vfs.VirtualFileSystem;
+import com.intellij.util.containers.ConcurrentHashMap;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.io.IOException;
-import java.util.HashMap;
 import java.util.Map;
 
 /**
  * @author max
  */
 public abstract class NewVirtualFileSystem extends VirtualFileSystem implements FileSystemInterface, CachingVirtualFileSystem {
-  private final Map<VirtualFileListener, VirtualFileListener> myListenerWrappers = new HashMap<VirtualFileListener, VirtualFileListener>();
+  private final Map<VirtualFileListener, VirtualFileListener> myListenerWrappers = new ConcurrentHashMap<VirtualFileListener, VirtualFileListener>();
 
   @Nullable
   public abstract VirtualFile findFileByPathIfCached(@NotNull @NonNls final String path);
@@ -73,25 +73,22 @@
 
   @Override
   public void addVirtualFileListener(@NotNull final VirtualFileListener listener) {
-    synchronized (myListenerWrappers) {
-      VirtualFileListener wrapper = new VirtualFileFilteringListener(listener, this);
-      VirtualFileManager.getInstance().addVirtualFileListener(wrapper);
-      myListenerWrappers.put(listener, wrapper);
-    }
+    VirtualFileListener wrapper = new VirtualFileFilteringListener(listener, this);
+    VirtualFileManager.getInstance().addVirtualFileListener(wrapper);
+    myListenerWrappers.put(listener, wrapper);
   }
 
   @Override
   public void removeVirtualFileListener(@NotNull final VirtualFileListener listener) {
-    synchronized (myListenerWrappers) {
-      final VirtualFileListener wrapper = myListenerWrappers.remove(listener);
-      if (wrapper != null) {
-        VirtualFileManager.getInstance().removeVirtualFileListener(wrapper);
-      }
+    final VirtualFileListener wrapper = myListenerWrappers.remove(listener);
+    if (wrapper != null) {
+      VirtualFileManager.getInstance().removeVirtualFileListener(wrapper);
     }
   }
 
   public abstract int getRank();
 
+  @NotNull
   @Override
   public abstract VirtualFile copyFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile newParent, @NotNull String copyName) throws IOException;
 
@@ -99,6 +96,7 @@
   @NotNull
   public abstract VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException;
 
+  @NotNull
   @Override
   public abstract VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException;
 
@@ -115,6 +113,7 @@
     return false;
   }
 
+  @NotNull
   public String getCanonicallyCasedName(@NotNull VirtualFile file) {
     return file.getName();
   }
diff --git a/platform/platform-api/src/com/intellij/ui/ComponentTreeWatcher.java b/platform/platform-api/src/com/intellij/ui/ComponentTreeWatcher.java
index cbcceb3..15364cb 100644
--- a/platform/platform-api/src/com/intellij/ui/ComponentTreeWatcher.java
+++ b/platform/platform-api/src/com/intellij/ui/ComponentTreeWatcher.java
@@ -63,7 +63,7 @@
       return;
     }
 
-    if (parentComponent instanceof Container) {
+    if (parentComponent instanceof Container && processChildren((Container)parentComponent)) {
       Container container = (Container)parentComponent;
       for (int i = 0; i < container.getComponentCount(); i++) {
         register(container.getComponent(i));
@@ -74,11 +74,15 @@
     processComponent(parentComponent);
   }
 
+  protected boolean processChildren(Container container) {
+    return true;
+  }
+
   protected abstract void processComponent(Component parentComponent);
 
   private void unregister(Component component) {
 
-    if (component instanceof Container) {
+    if (component instanceof Container && processChildren((Container)component)) {
       Container container = (Container)component;
       for (int i = 0; i < container.getComponentCount(); i++) {
         unregister(container.getComponent(i));
diff --git a/platform/platform-api/src/com/intellij/ui/ListScrollingUtil.java b/platform/platform-api/src/com/intellij/ui/ListScrollingUtil.java
index dd58560..08b3acb 100644
--- a/platform/platform-api/src/com/intellij/ui/ListScrollingUtil.java
+++ b/platform/platform-api/src/com/intellij/ui/ListScrollingUtil.java
@@ -301,15 +301,7 @@
       }
     });
 
-    InputMap map = list.getInputMap(JComponent.WHEN_FOCUSED);
-    UIUtil.maybeInstall(map, SCROLLUP_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
-    UIUtil.maybeInstall(map, SCROLLDOWN_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
-    UIUtil.maybeInstall(map, SELECT_PREVIOUS_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
-    UIUtil.maybeInstall(map, SELECT_NEXT_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
-    UIUtil.maybeInstall(map, SELECT_FIRST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0));
-    UIUtil.maybeInstall(map, SELECT_LAST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_END, 0));
-    UIUtil.maybeInstall(map, MOVE_HOME_ID, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
-    UIUtil.maybeInstall(map, MOVE_END_ID, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
+    maybeInstallDefaultShortcuts(list);
 
     new ListScrollAction(CommonShortcuts.getMoveUp(), list) {
       @Override
@@ -348,7 +340,19 @@
       }
     };
   }
-  
+
+  static void maybeInstallDefaultShortcuts(JComponent component) {
+    InputMap map = component.getInputMap(JComponent.WHEN_FOCUSED);
+    UIUtil.maybeInstall(map, SCROLLUP_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_UP, 0));
+    UIUtil.maybeInstall(map, SCROLLDOWN_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_PAGE_DOWN, 0));
+    UIUtil.maybeInstall(map, SELECT_PREVIOUS_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_UP, 0));
+    UIUtil.maybeInstall(map, SELECT_NEXT_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_DOWN, 0));
+    UIUtil.maybeInstall(map, SELECT_FIRST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_HOME, 0));
+    UIUtil.maybeInstall(map, SELECT_LAST_ROW_ACTION_ID, KeyStroke.getKeyStroke(KeyEvent.VK_END, 0));
+    UIUtil.maybeInstall(map, MOVE_HOME_ID, KeyStroke.getKeyStroke(KeyEvent.VK_LEFT, 0));
+    UIUtil.maybeInstall(map, MOVE_END_ID, KeyStroke.getKeyStroke(KeyEvent.VK_RIGHT, 0));
+  }
+
   public static abstract class ListScrollAction extends AnAction {
     protected ListScrollAction(final ShortcutSet shortcutSet, final JComponent component) {
       registerCustomShortcutSet(shortcutSet, component);
diff --git a/platform/platform-api/src/com/intellij/ui/MouseDragHelper.java b/platform/platform-api/src/com/intellij/ui/MouseDragHelper.java
index 1543c5d..e46748c 100644
--- a/platform/platform-api/src/com/intellij/ui/MouseDragHelper.java
+++ b/platform/platform-api/src/com/intellij/ui/MouseDragHelper.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.ui;
 
+import com.intellij.ide.ui.UISettings;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.ui.NullableComponent;
 import com.intellij.openapi.util.Disposer;
@@ -27,10 +28,7 @@
 
 import javax.swing.*;
 import java.awt.*;
-import java.awt.event.KeyEvent;
-import java.awt.event.MouseEvent;
-import java.awt.event.MouseListener;
-import java.awt.event.MouseMotionListener;
+import java.awt.event.*;
 
 public abstract class MouseDragHelper implements MouseListener, MouseMotionListener, KeyEventDispatcher, Weighted {
 
@@ -58,6 +56,16 @@
 
   }
 
+  /**
+   *
+   * @param event
+   * @return false if Settings -> Appearance -> Drag-n-Drop with ALT pressed only is selected but event doesn't have ALT modifier
+   */
+  public static boolean checkModifiers(InputEvent event) {
+    if (event == null || !UISettings.getInstance().DND_WITH_PRESSED_ALT_ONLY) return true;
+    return (event.getModifiers() & InputEvent.ALT_MASK) != 0;
+  }
+
   public void start() {
     if (myGlassPane != null) return;
 
diff --git a/platform/platform-api/src/com/intellij/ui/TableScrollingUtil.java b/platform/platform-api/src/com/intellij/ui/TableScrollingUtil.java
index 7b30f22..48f1940 100644
--- a/platform/platform-api/src/com/intellij/ui/TableScrollingUtil.java
+++ b/platform/platform-api/src/com/intellij/ui/TableScrollingUtil.java
@@ -280,6 +280,9 @@
         moveHome(list);
       }
     });
+
+    ListScrollingUtil.maybeInstallDefaultShortcuts(list);
+
     new AnAction() {
       public void actionPerformed(AnActionEvent e) {
         moveHome(list);
diff --git a/platform/platform-api/src/com/intellij/ui/UserActivityWatcher.java b/platform/platform-api/src/com/intellij/ui/UserActivityWatcher.java
index cbe1b84..031eb94 100644
--- a/platform/platform-api/src/com/intellij/ui/UserActivityWatcher.java
+++ b/platform/platform-api/src/com/intellij/ui/UserActivityWatcher.java
@@ -16,6 +16,7 @@
 package com.intellij.ui;
 
 import com.intellij.openapi.Disposable;
+import com.intellij.openapi.ui.ComboBox;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.EventDispatcher;
 
@@ -51,6 +52,7 @@
       fireUIChanged();
     }
   };
+
   private final PropertyChangeListener myTableListener = new PropertyChangeListener() {
     public void propertyChange(PropertyChangeEvent evt) {
       TableModel oldModel = (TableModel)evt.getOldValue();
@@ -68,12 +70,19 @@
       }
     }
   };
+
   private final ChangeListener myChangeListener = new ChangeListener() {
     public void stateChanged(final ChangeEvent e) {
       fireUIChanged();
     }
   };
 
+  private final PropertyChangeListener myCellEditorChangeListener = new PropertyChangeListener() {
+    public void propertyChange(PropertyChangeEvent e) {
+      if (e.getOldValue() != null && e.getNewValue() == null) fireUIChanged();
+    }
+  };
+
   public void addUserActivityListener(UserActivityListener listener) {
     myListeners.addListener(listener);
   }
@@ -147,6 +156,10 @@
 
   }
 
+  protected boolean processChildren(Container container) {
+    return !(container instanceof JTable);
+  }
+
   protected void processComponent(final Component parentComponent) {
     if (parentComponent instanceof JTextComponent) {
       ((JTextComponent)parentComponent).getDocument().addDocumentListener(myDocumentListener);
@@ -177,6 +190,7 @@
       if (model != null) {
         model.addTableModelListener(myTableModelListener);
       }
+      table.addPropertyChangeListener(ComboBox.TABLE_CELL_EDITOR_PROPERTY, myCellEditorChangeListener);
     }
 
     if (parentComponent instanceof JSlider) {
@@ -206,6 +220,7 @@
       if (model != null) {
         model.removeTableModelListener(myTableModelListener);
       }
+      component.removePropertyChangeListener(myCellEditorChangeListener);
     }
 
     if (component instanceof JSlider){
diff --git a/platform/platform-api/src/com/intellij/ui/border/CustomLineBorder.java b/platform/platform-api/src/com/intellij/ui/border/CustomLineBorder.java
index ea09048..ee68a3f 100644
--- a/platform/platform-api/src/com/intellij/ui/border/CustomLineBorder.java
+++ b/platform/platform-api/src/com/intellij/ui/border/CustomLineBorder.java
@@ -48,7 +48,7 @@
   @Override
   public void paintBorder(Component c, Graphics g, int x, int y, int w, int h) {
     final Color oldColor = g.getColor();
-    g.setColor(myColor);
+    g.setColor(getColor());
 
     if (myInsets.left > 0) g.fillRect(x, y, x + myInsets.left, y + h);
     if (myInsets.bottom > 0) g.fillRect(x, y + h - myInsets.bottom, x + w, y + h);
@@ -58,6 +58,10 @@
     g.setColor(oldColor);
   }
 
+  protected Color getColor() {
+    return myColor;
+  }
+
   @Override
   public Insets getBorderInsets(Component c) {
     return myInsets;
diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/DefaultEditorTabsPainter.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/DefaultEditorTabsPainter.java
index 2f7b37a..04a9e43 100644
--- a/platform/platform-api/src/com/intellij/ui/tabs/impl/DefaultEditorTabsPainter.java
+++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/DefaultEditorTabsPainter.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -68,7 +68,7 @@
 
   private static void drawShadow(Graphics2D g, int x, int w, int shadowBottom) {
     int shadowTop = shadowBottom - ACTIVE_TAB_SHADOW_HEIGHT;
-    g.setPaint(UIUtil.getGradientPaint(x, shadowTop, new Color(0, 0, 0, 0),
+    g.setPaint(UIUtil.getGradientPaint(x, shadowTop, Gray.TRANSPARENT,
                                    x, shadowBottom, new Color(0, 0, 0, 30)));
     g.fillRect(x, shadowTop, w, ACTIVE_TAB_SHADOW_HEIGHT);
   }
diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/DragHelper.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/DragHelper.java
index 3ba5cd0..655854a 100644
--- a/platform/platform-api/src/com/intellij/ui/tabs/impl/DragHelper.java
+++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/DragHelper.java
@@ -94,7 +94,7 @@
   }
 
   protected void processDrag(MouseEvent event, Point targetScreenPoint, Point startPointScreen) {
-    if (!myTabs.isTabDraggingEnabled() || !isDragSource(event)) return;
+    if (!myTabs.isTabDraggingEnabled() || !isDragSource(event) || !MouseDragHelper.checkModifiers(event)) return;
 
     SwingUtilities.convertPointFromScreen(startPointScreen, myTabs);
 
diff --git a/platform/platform-impl/src/com/intellij/designer/model/Property.java b/platform/platform-impl/src/com/intellij/designer/model/Property.java
index 8c6d85f..51d27b7 100644
--- a/platform/platform-impl/src/com/intellij/designer/model/Property.java
+++ b/platform/platform-impl/src/com/intellij/designer/model/Property.java
@@ -18,9 +18,11 @@
 import com.intellij.designer.propertyTable.PropertyEditor;
 import com.intellij.designer.propertyTable.PropertyRenderer;
 import com.intellij.psi.PsiElement;
+import com.intellij.util.ui.TextTransferable;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.awt.datatransfer.Transferable;
 import java.util.Collections;
 import java.util.List;
 
@@ -126,6 +128,17 @@
 
   //////////////////////////////////////////////////////////////////////////////////////////
   //
+  // Copy
+  //
+  //////////////////////////////////////////////////////////////////////////////////////////
+
+  @NotNull
+  public Transferable doCopy(@NotNull T container, @NotNull Object commonValue) {
+    return new TextTransferable(commonValue.toString());
+  }
+
+  //////////////////////////////////////////////////////////////////////////////////////////
+  //
   // Presentation
   //
   //////////////////////////////////////////////////////////////////////////////////////////
diff --git a/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java b/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java
index 8a10114..06d4872 100644
--- a/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java
+++ b/platform/platform-impl/src/com/intellij/designer/propertyTable/PropertyTable.java
@@ -22,6 +22,7 @@
 import com.intellij.designer.propertyTable.renderers.LabelPropertyRenderer;
 import com.intellij.ide.ui.search.SearchUtil;
 import com.intellij.lang.annotation.HighlightSeverity;
+import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.colors.EditorColorsManager;
 import com.intellij.openapi.editor.colors.TextAttributesKey;
@@ -84,7 +85,7 @@
   private final TableSpeedSearch mySpeedSearch;
 
   private final AbstractTableModel myModel = new PropertyTableModel();
-  private List<PropertiesContainer> myContainers = Collections.emptyList();
+  protected List<PropertiesContainer> myContainers = Collections.emptyList();
   protected List<Property> myProperties = Collections.emptyList();
   protected final Set<String> myExpandedProperties = new HashSet<String>();
 
@@ -636,7 +637,7 @@
   }
 
   @Nullable
-  private Object getValue(Property property) throws Exception {
+  protected final Object getValue(Property property) throws Exception {
     int size = myContainers.size();
     if (size == 0) {
       return null;
@@ -815,6 +816,15 @@
     }
   }
 
+  @Override
+  public void removeEditor() {
+    super.removeEditor();
+    updateEditActions();
+  }
+
+  protected void updateEditActions() {
+  }
+
   private boolean setValueAtRow(int row, final Object newValue) {
     final Property property = myProperties.get(row);
 
@@ -1165,6 +1175,13 @@
           .append(MessageFormat.format("Error getting value: {0}", e.getMessage()), SimpleTextAttributes.ERROR_ATTRIBUTES);
         return errComponent;
       }
+      finally {
+        ApplicationManager.getApplication().invokeLater(new Runnable() {
+          public void run() {
+            updateEditActions();
+          }
+        });
+      }
     }
 
     @Override
diff --git a/platform/platform-impl/src/com/intellij/ide/CopyPasteManagerEx.java b/platform/platform-impl/src/com/intellij/ide/CopyPasteManagerEx.java
index dea9dd8..102000e 100644
--- a/platform/platform-impl/src/com/intellij/ide/CopyPasteManagerEx.java
+++ b/platform/platform-impl/src/com/intellij/ide/CopyPasteManagerEx.java
@@ -154,7 +154,7 @@
         addToTheTopOfTheStack(content);
       }
       else {
-        moveContentToStackTop(same);
+        moveContentToStackTop(same, false); // notification is done in setContents() method
       }
     }
     catch (UnsupportedFlavorException ignore) { }
@@ -283,12 +283,18 @@
   }
 
   public void moveContentToStackTop(Transferable t) {
+    moveContentToStackTop(t, true);
+  }
+
+  private void moveContentToStackTop(Transferable t, boolean notifyOthers) {
     Transferable current = myData.isEmpty() ? null : myData.get(0);
     if (!Comparing.equal(t, current)) {
       myData.remove(t);
       myData.add(0, t);
-      setSystemClipboardContent(t);
-      fireContentChanged(current, t);
+      if (notifyOthers) {
+        setSystemClipboardContent(t);
+        fireContentChanged(current, t);
+      }
     }
   }
 }
diff --git a/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java
index 06c419a..726c8e5 100644
--- a/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/ide/FrameStateManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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,20 +18,18 @@
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.application.ApplicationActivationListener;
 import com.intellij.openapi.application.impl.ApplicationImpl;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.util.ActionCallback;
 import com.intellij.openapi.util.BusyObject;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.wm.IdeFrame;
 import com.intellij.util.Alarm;
 import com.intellij.util.containers.ContainerUtil;
-import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.util.List;
 
-public class FrameStateManagerImpl extends FrameStateManager implements ApplicationComponent {
+public class FrameStateManagerImpl extends FrameStateManager {
   private final List<FrameStateListener> myListeners = ContainerUtil.createLockFreeCopyOnWriteList();
 
   private boolean myShouldSynchronize;
@@ -84,21 +82,6 @@
     return myActive.getReady(this);
   }
 
-  @Override
-  @NotNull
-  @NonNls
-  public String getComponentName() {
-    return "FrameStateManager";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
   private void fireDeactivationEvent() {
     for (FrameStateListener listener : myListeners) {
       listener.onFrameDeactivated();
diff --git a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java
index 46a6c34..9f16051 100644
--- a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java
+++ b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -940,14 +940,11 @@
           return;
         }
         if (keyCode == VK_ENTER && files.getModel().getSize() + toolWindows.getModel().getSize() == 0) {
-          AnAction gotoAction = ActionManager.getInstance().getAction("GotoClass");
-          if (gotoAction == null) {
-            gotoAction = ActionManager.getInstance().getAction("GotoFile");
-          }
-          if (gotoAction != null) {
+          AnAction gotoFile = ActionManager.getInstance().getAction("GotoFile");
+          if (gotoFile != null) {
             final String search = mySpeedSearch.getEnteredPrefix();
             myPopup.cancel();
-            final AnAction action = gotoAction;
+            final AnAction action = gotoFile;
             SwingUtilities.invokeLater(new Runnable() {
               @Override
               public void run() {
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java b/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java
index 363e210..3df1156 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/AbstractCustomizeWizardStep.java
@@ -15,19 +15,69 @@
  */
 package com.intellij.ide.customize;
 
+import com.intellij.ui.ClickListener;
+import com.intellij.ui.ColorUtil;
+import com.intellij.util.ui.UIUtil;
+import org.jetbrains.annotations.NotNull;
+
 import javax.swing.*;
 import java.awt.*;
+import java.awt.event.ItemEvent;
+import java.awt.event.ItemListener;
+import java.awt.event.MouseEvent;
 
 public abstract class AbstractCustomizeWizardStep extends JPanel {
   protected static final int GAP = 20;
 
-  abstract String getTitle();
+  protected abstract String getTitle();
 
-  abstract String getHTMLHeader();
+  protected abstract String getHTMLHeader();
 
-  abstract String getHTMLFooter();
+  protected abstract String getHTMLFooter();
+
+  @NotNull
+  protected static Color getSelectionBackground() {
+    return ColorUtil.mix(UIUtil.getListSelectionBackground(), UIUtil.getLabelBackground(), .75);
+  }
+
+  protected static JPanel createBigButtonPanel(LayoutManager layout, final JToggleButton anchorButton, final Runnable action) {
+    final JPanel panel = new JPanel(layout) {
+      @Override
+      public Color getBackground() {
+        return anchorButton.isSelected() ? getSelectionBackground() : super.getBackground();
+      }
+    };
+    panel.setOpaque(anchorButton.isSelected());
+    new ClickListener() {
+      @Override
+      public boolean onClick(@NotNull MouseEvent event, int clickCount) {
+        anchorButton.setSelected(true);
+        return true;
+      }
+    }.installOn(panel);
+    anchorButton.addItemListener(new ItemListener() {
+      boolean curState = anchorButton.isSelected();
+      @Override
+      public void itemStateChanged(ItemEvent e) {
+        if (e.getStateChange() == ItemEvent.SELECTED && curState != anchorButton.isSelected()) {
+          action.run();
+        }
+        curState = anchorButton.isSelected();
+        panel.setOpaque(curState);
+        panel.repaint();
+      }
+    });
+    return panel;
+  }
 
   Component getDefaultFocusedComponent() {
     return null;
   }
+
+  public void beforeShown(boolean forward) {
+  }
+
+  public boolean beforeOkAction() {
+    return true;
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java
index e4b4a8e..d3e340e 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeFeaturedPluginsStepPanel.java
@@ -19,34 +19,50 @@
 import com.intellij.icons.AllIcons;
 import com.intellij.ide.plugins.IdeaPluginDescriptor;
 import com.intellij.ide.plugins.PluginNode;
+import com.intellij.openapi.progress.util.ProgressIndicatorBase;
+import com.intellij.openapi.ui.VerticalFlowLayout;
 import com.intellij.openapi.updateSettings.impl.PluginDownloader;
+import com.intellij.ui.ColorUtil;
+import com.intellij.ui.JBColor;
+import com.intellij.ui.border.CustomLineBorder;
 import com.intellij.ui.components.JBScrollPane;
+import com.intellij.ui.components.labels.LinkLabel;
+import com.intellij.ui.components.labels.LinkListener;
 import com.intellij.util.ConcurrencyUtil;
 
 import javax.swing.*;
+import javax.swing.border.CompoundBorder;
 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.util.List;
 import java.util.Map;
 import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledThreadPoolExecutor;
 import java.util.concurrent.TimeUnit;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 public class CustomizeFeaturedPluginsStepPanel extends AbstractCustomizeWizardStep {
-  private static ScheduledExecutorService ourService = ConcurrencyUtil.newSingleScheduledThreadExecutor("FeaturedPlugins");
+  private static final int COLS = 3;
+  private static ScheduledExecutorService ourService = new ScheduledThreadPoolExecutor(4, ConcurrencyUtil.newNamedThreadFactory(
+    "FeaturedPlugins", true, Thread.NORM_PRIORITY));
 
-  public CustomizeFeaturedPluginsStepPanel() {
-    setLayout(new GridLayout(0, 3, GAP, GAP));
-    JPanel gridPanel = new JPanel(new GridLayout(0, 3, GAP, GAP));
+  public final AtomicBoolean myCanceled = new AtomicBoolean(false);
+
+
+  public CustomizeFeaturedPluginsStepPanel() throws OfflineException {
+    setLayout(new GridLayout(1, 1));
+    JPanel gridPanel = new JPanel(new GridLayout(0, 3));
     JBScrollPane scrollPane =
       new JBScrollPane(gridPanel, ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED, ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
     scrollPane.getVerticalScrollBar().setUnitIncrement(10);
 
     Map<String, String> config = PluginGroups.getInstance().getFeaturedPlugins();
+    boolean isEmptyOrOffline = true;
+    List<IdeaPluginDescriptor> pluginsFromRepository = PluginGroups.getInstance().getPluginsFromRepository();
     for (Map.Entry<String, String> entry : config.entrySet()) {
       JPanel groupPanel = new JPanel(new GridBagLayout());
       GridBagConstraints gbc = new GridBagConstraints();
-      gbc.insets = new Insets(0, 0, 10, 0);
       gbc.fill = GridBagConstraints.BOTH;
       gbc.anchor = GridBagConstraints.WEST;
       gbc.gridwidth = GridBagConstraints.REMAINDER;
@@ -60,10 +76,10 @@
       final String description = s.substring(i + 1, j);
       final String pluginId = s.substring(j + 1);
       IdeaPluginDescriptor foundDescriptor = null;
-      List<IdeaPluginDescriptor> pluginsFromRepository = PluginGroups.getInstance().getPluginsFromRepository();
       for (IdeaPluginDescriptor descriptor : pluginsFromRepository) {
         if (descriptor.getPluginId().getIdString().equals(pluginId)) {
           foundDescriptor = descriptor;
+          isEmptyOrOffline = false;
           break;
         }
       }
@@ -82,30 +98,100 @@
           return size;
         }
       };
-      final JButton installButton = new JButton("Install", AllIcons.General.DownloadPlugin);
+      final CardLayout wrapperLayout = new CardLayout();
+      final JPanel buttonWrapper = new JPanel(wrapperLayout);
+      final JButton installButton = new JButton("Install");
+      final JProgressBar progressBar = new JProgressBar(0, 100);
+      progressBar.setStringPainted(true);
+      JPanel progressPanel = new JPanel(new VerticalFlowLayout(true, false));
+      progressPanel.add(progressBar);
+      final LinkLabel cancelLink = new LinkLabel("Cancel", AllIcons.Actions.Cancel);
+      JPanel linkWrapper = new JPanel(new FlowLayout(FlowLayout.CENTER));
+      linkWrapper.add(cancelLink);
+      progressPanel.add(linkWrapper);
+
+      JPanel buttonPanel = new JPanel(new VerticalFlowLayout());
+      buttonPanel.add(installButton);
+
+      buttonWrapper.add(buttonPanel, "button");
+      buttonWrapper.add(progressPanel, "progress");
+
+      wrapperLayout.show(buttonWrapper, "button");
+
+      final ProgressIndicatorBase indicator = new ProgressIndicatorBase(true) {
+
+        @Override
+        public void start() {
+          myCanceled.set(false);
+          super.start();
+          SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+              wrapperLayout.show(buttonWrapper, "progress");
+            }
+          });
+        }
+
+        @Override
+        public void processFinish() {
+          super.processFinish();
+          SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+              wrapperLayout.show(buttonWrapper, "button");
+              installButton.setEnabled(false);
+              installButton.setText("Installed");
+            }
+          });
+        }
+
+        @Override
+        public void setFraction(final double fraction) {
+          super.setFraction(fraction);
+          SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+              int value = (int)(100 * fraction + .5);
+              progressBar.setValue(value);
+              progressBar.setString(value + "%");
+            }
+          });
+        }
+
+        @Override
+        public void cancel() {
+          stop();
+          myCanceled.set(true);
+          super.cancel();
+          SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+              wrapperLayout.show(buttonWrapper, "button");
+              progressBar.setValue(0);
+            }
+          });
+        }
+      };
       installButton.addActionListener(new ActionListener() {
         @Override
         public void actionPerformed(ActionEvent e) {
-          installButton.setEnabled(false);
-          installButton.setText("In progress...");
+          wrapperLayout.show(buttonWrapper, "progress");
           ourService.schedule(new Runnable() {
             @Override
             public void run() {
               try {
+                indicator.start();
                 PluginNode node = new PluginNode(descriptor.getPluginId());
                 node.setUrl(descriptor.getUrl());
                 PluginDownloader downloader = PluginDownloader.createDownloader(node);
-                if (downloader.prepareToInstall()) {
-                  downloader.install();
-                  onSuccess();
-                }
-                else {
-                  onFail();
-                }
+                downloader.prepareToInstall(indicator);
+                downloader.install();
+                indicator.processFinish();
               }
               catch (Exception ignored) {
-                ignored.printStackTrace();
-                onFail();
+                if (!myCanceled.get()) {
+                  onFail();
+                }
               }
             }
 
@@ -114,37 +200,48 @@
               SwingUtilities.invokeLater(new Runnable() {
                 @Override
                 public void run() {
-                  installButton.setText("Cannot download plugin");
-                }
-              });
-            }
-
-            void onSuccess() {
-              //noinspection SSBasedInspection
-              SwingUtilities.invokeLater(new Runnable() {
-                @Override
-                public void run() {
-                  installButton.setText("Installed");
+                  indicator.stop();
+                  wrapperLayout.show(buttonWrapper, "progress");
+                  progressBar.setString("Cannot download plugin");
                 }
               });
             }
           }, 0, TimeUnit.SECONDS);
-          //PluginGroups.getInstance().setFeaturedPluginEnabled(pluginId, installButton.isSelected());
         }
       });
+      cancelLink.setListener(new LinkListener() {
+        @Override
+        public void linkSelected(LinkLabel aSource, Object aLinkData) {
+          indicator.cancel();
+        }
+      }, null);
+      gbc.insets.bottom = -5;
       groupPanel.add(titleLabel, gbc);
+      gbc.insets.bottom = 10;
       groupPanel.add(topicLabel, gbc);
       groupPanel.add(descriptionLabel, gbc);
       gbc.weighty = 1;
       groupPanel.add(Box.createVerticalGlue(), gbc);
       gbc.weighty = 0;
-      groupPanel.add(installButton, gbc);
-      gbc.weighty = 1;
-      groupPanel.add(Box.createVerticalGlue(), gbc);
-      groupPanel.setBorder(BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP));
+      groupPanel.add(buttonWrapper, gbc);
       gridPanel.add(groupPanel);
     }
-    setLayout(new GridLayout(1, 1));
+    int cursor = 0;
+    Component[] components = gridPanel.getComponents();
+    int rowCount = components.length / COLS;
+    for (Component component : components) {
+      ((JComponent)component).setBorder(
+        new CompoundBorder(new CustomLineBorder(ColorUtil.withAlpha(JBColor.foreground(), .2), 0, 0, cursor / 3 < rowCount ? 1 : 0,
+                                                cursor % COLS != COLS - 1 ? 1 : 0) {
+          @Override
+          protected Color getColor() {
+            return ColorUtil.withAlpha(JBColor.foreground(), .2);
+          }
+        }, BorderFactory.createEmptyBorder(GAP, GAP, 0, GAP)));
+      cursor++;
+    }
+
+    if (isEmptyOrOffline) throw new OfflineException();
     add(scrollPane);
   }
 
@@ -156,7 +253,7 @@
   @Override
   public String getHTMLHeader() {
     return "<html><body><h2>Download featured plugins</h2>" +
-           "We have a few plugins in our repository that most users like to download." +
+           "We have a few plugins in our repository that most users like to download. " +
            "Perhaps, you need them too?</body></html>";
   }
 
@@ -164,4 +261,6 @@
   public String getHTMLFooter() {
     return "New plugins can also be downloaded in " + CommonBundle.settingsTitle() + " | Plugins";
   }
+
+  static class OfflineException extends Exception {};
 }
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java
index 8bbae3b..203e041 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeIDEWizardDialog.java
@@ -16,6 +16,7 @@
 package com.intellij.ide.customize;
 
 import com.intellij.ide.plugins.PluginManager;
+import com.intellij.ide.startup.StartupActionScriptManager;
 import com.intellij.openapi.application.ApplicationNamesInfo;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.util.SystemInfo;
@@ -53,7 +54,15 @@
     myNavigationLabel.setEnabled(false);
     myFooterLabel.setEnabled(false);
     init();
-    initCurrentStep();
+    initCurrentStep(true);
+    setSize(400, 300);
+    System.setProperty(StartupActionScriptManager.STARTUP_WIZARD_MODE, "true");
+  }
+
+  @Override
+  protected void dispose() {
+    System.clearProperty(StartupActionScriptManager.STARTUP_WIZARD_MODE);
+    super.dispose();
   }
 
   protected void initSteps() {
@@ -62,7 +71,12 @@
       mySteps.add(new CustomizeKeyboardSchemeStepPanel());
     }
     mySteps.add(new CustomizePluginsStepPanel());
-    mySteps.add(new CustomizeFeaturedPluginsStepPanel());
+    try {
+      mySteps.add(new CustomizeFeaturedPluginsStepPanel());
+    }
+    catch (CustomizeFeaturedPluginsStepPanel.OfflineException e) {
+      //skip featured step if we're offline
+    }
   }
 
   @Override
@@ -112,7 +126,7 @@
     }
     if (e.getSource() == myBackButton) {
       myIndex--;
-      initCurrentStep();
+      initCurrentStep(false);
       return;
     }
     if (e.getSource() == myNextButton) {
@@ -121,12 +135,20 @@
         return;
       }
       myIndex++;
-      initCurrentStep();
+      initCurrentStep(true);
     }
   }
 
   @Override
+  public void doCancelAction() {
+    // lets pretend it is the wind..
+  }
+
+  @Override
   protected void doOKAction() {
+    for (AbstractCustomizeWizardStep step : mySteps) {
+      if (!step.beforeOkAction()) return;
+    }
     try {
       PluginManager.saveDisabledPlugins(PluginGroups.getInstance().getDisabledPluginIds(), false);
     }
@@ -135,8 +157,9 @@
     super.doOKAction();
   }
 
-  private void initCurrentStep() {
+  private void initCurrentStep(boolean forward) {
     final AbstractCustomizeWizardStep myCurrentStep = mySteps.get(myIndex);
+    myCurrentStep.beforeShown(forward);
     myCardLayout.swipe(myContentPanel, myCurrentStep.getTitle(), JBCardLayout.SwipeDirection.AUTO, new Runnable() {
       @Override
       public void run() {
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeKeyboardSchemeStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeKeyboardSchemeStepPanel.java
index 99a43bf..c5bca8a 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeKeyboardSchemeStepPanel.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeKeyboardSchemeStepPanel.java
@@ -23,72 +23,63 @@
 
 import javax.swing.*;
 import java.awt.*;
-import java.awt.event.ActionEvent;
-import java.awt.event.ActionListener;
 
 public class CustomizeKeyboardSchemeStepPanel extends AbstractCustomizeWizardStep {
 
-  private final JToggleButton myMacButton;
-  private final JToggleButton myDefaultButton;
+  private final JPanel myMacPanel;
+  private final JPanel myDefaultPanel;
 
   public CustomizeKeyboardSchemeStepPanel() {//&#8997; alt
     setLayout(new GridLayout(1, 2, GAP, GAP));
-    myMacButton = new JToggleButton();
-    myMacButton.setLayout(new VerticalFlowLayout());
     final JRadioButton macRadioButton =
       new JRadioButton("I've never used " + ApplicationNamesInfo.getInstance().getProductName() + " or am a Mac user");
-    myMacButton.add(macRadioButton);
-    myMacButton.add(new JLabel("<html><body><h3>" + KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP + " keymap</h3>" +
-                               "Adapted for Mac<br><br><table><tr><td colspan=\"2\">EXAMPLES</td></tr>" +
-                               "<tr><td style=\"text-align:right;\">&#8984;N</td><td style=\"text-align:left;\">Generate</td></tr>" +
-                               "<tr><td style=\"text-align:right;\">&#8984;O</td><td style=\"text-align:left;\">Go to class</td></tr>" +
-                               "<tr><td style=\"text-align:right;\">&#8984;&#9003;</td><td style=\"text-align:left;\">Delete line</td></tr>" +
-                               "</table></body></html>"
-    ));
-
-    add(myMacButton);
-    myDefaultButton = new JToggleButton();
-    myDefaultButton.setLayout(new VerticalFlowLayout());
-    final JRadioButton defaultRadioButton =
-      new JRadioButton("I used " + ApplicationNamesInfo.getInstance().getProductName() + " before or am a Windows user");
-    myDefaultButton.add(defaultRadioButton);
-    myDefaultButton.add(new JLabel("<html><body><h3>" + KeymapManager.MAC_OS_X_KEYMAP + " keymap</h3>" +
-                                   "Default for all platforms<br><br><table><tr><td colspan=\"2\">EXAMPLES</td></tr>" +
-                                   "<tr><td style=\"text-align:right;\">^N</td><td style=\"text-align:left;\">Generate</td></tr>" +
-                                   "<tr><td style=\"text-align:right;\">&#8984;N</td><td style=\"text-align:left;\">Go to class</td></tr>" +
-                                   "<tr><td style=\"text-align:right;\">&#8984;Y</td><td style=\"text-align:left;\">Delete line</td></tr>" +
-                                   "</table></body></html>"
-    ));
-
-    add(myMacButton);
-    add(myDefaultButton);
-    ButtonGroup group = new ButtonGroup();
-    ButtonGroup subGroup = new ButtonGroup();
-    group.add(myMacButton);
-    group.add(myDefaultButton);
-    myMacButton.addActionListener(new ActionListener() {
+    macRadioButton.setOpaque(false);
+    myMacPanel = createBigButtonPanel(new VerticalFlowLayout(), macRadioButton, new Runnable() {
       @Override
-      public void actionPerformed(ActionEvent e) {
-        macRadioButton.setSelected(myMacButton.isSelected());
+      public void run() {
         StartupUtil.setMyWizardMacKeymap(KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP);
       }
     });
-    myDefaultButton.addActionListener(new ActionListener() {
+    String style = "<style type=\"text/css\">" +
+    "body {margin-left:"+ GAP +"px; border:none;padding:0px;}"+
+    "table {margin:0px; cell-padding:0px; border:none;}"+
+    "</style>";
+
+    myMacPanel.add(macRadioButton);
+    myMacPanel.add(
+      new JLabel("<html><head>"+style+"</head><body><h3>" + KeymapManager.MAC_OS_X_10_5_PLUS_KEYMAP + " keymap</h3>" +
+                 "Adapted for Mac<br><br><table><tr><td align=\"left\" colspan=\"2\">EXAMPLES</td></tr>" +
+                 "<tr><td style=\"text-align:right;\">&#8984;N</td><td style=\"text-align:left;\">Generate</td></tr>" +
+                 "<tr><td style=\"text-align:right;\">&#8984;O</td><td style=\"text-align:left;\">Go to class</td></tr>" +
+                 "<tr><td style=\"text-align:right;\">&#8984;&#9003;</td><td style=\"text-align:left;\">Delete line</td></tr>" +
+                 "</table></body></html>"
+      ));
+
+    add(myMacPanel);
+    final JRadioButton defaultRadioButton =
+      new JRadioButton("I used " + ApplicationNamesInfo.getInstance().getProductName() + " before or am a Windows user");
+    defaultRadioButton.setOpaque(false);
+    myDefaultPanel = createBigButtonPanel(new VerticalFlowLayout(),defaultRadioButton, new Runnable() {
       @Override
-      public void actionPerformed(ActionEvent e) {
-        defaultRadioButton.setSelected(myDefaultButton.isSelected());
+      public void run() {
         StartupUtil.setMyWizardMacKeymap(KeymapManager.MAC_OS_X_KEYMAP);
       }
-    });
-    subGroup.add(macRadioButton);
-    subGroup.add(defaultRadioButton);
-    myDefaultButton.setSelected(true);
-    defaultRadioButton.setSelected(true);
-  }
+    } );
+    myDefaultPanel.add(defaultRadioButton);
+    myDefaultPanel.add(new JLabel("<html><head>" + style + "</head><body><h3>" + KeymapManager.MAC_OS_X_KEYMAP + " keymap</h3>" +
+                                  "Default for all platforms<br><br><table><tr><td align=\"left\" colspan=\"2\">EXAMPLES</td></tr>" +
+                                  "<tr><td style=\"text-align:right;\">^N</td><td style=\"text-align:left;\">Generate</td></tr>" +
+                                  "<tr><td style=\"text-align:right;\">&#8984;N</td><td style=\"text-align:left;\">Go to class</td></tr>" +
+                                  "<tr><td style=\"text-align:right;\">&#8984;Y</td><td style=\"text-align:left;\">Delete line</td></tr>" +
+                                  "</table></body></html>"
+    ));
 
-  @Override
-  Component getDefaultFocusedComponent() {
-    return myMacButton.isSelected() ? myMacButton : myDefaultButton;
+    add(myMacPanel);
+    add(myDefaultPanel);
+    ButtonGroup group = new ButtonGroup();
+    group.add(macRadioButton);
+    group.add(defaultRadioButton);
+    defaultRadioButton.setSelected(true);
   }
 
   @Override
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizePluginsStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizePluginsStepPanel.java
index eca49dd..055a1d6 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizePluginsStepPanel.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizePluginsStepPanel.java
@@ -37,7 +37,6 @@
   private static final String MAIN = "main";
   private static final String CUSTOMIZE = "customize";
   private static final int COLS = 3;
-  private final Color myDescriptionForeground = ColorUtil.withAlpha(UIManager.getColor("Label.foreground"), .75);
   private static final TextProvider CUSTOMIZE_TEXT_PROVIDER = new TextProvider() {
     @Override
     public String getText() {
@@ -61,20 +60,19 @@
     add(scrollPane, MAIN);
     add(myCustomizePanel, CUSTOMIZE);
 
-    //PluginManager.loadDisabledPlugins(new File(PathManager.getConfigPath()).getPath(), myDisabledPluginIds);
-    //for (IdeaPluginDescriptor pluginDescriptor : myAllPlugins) {
-    //  if (pluginDescriptor.getPluginId().getIdString().equals("com.intellij")) {
-    ////    skip 'IDEA CORE' plugin
-        //continue;
-      //}
-    //  //PluginManager.initClassLoader(PluginGroups.class.getClassLoader(), (IdeaPluginDescriptorImpl)pluginDescriptor);
-    //}
     Map<String, List<String>> groups = PluginGroups.getInstance().getTree();
     for (Map.Entry<String, List<String>> entry : groups.entrySet()) {
       final String group = entry.getKey();
       if (PluginGroups.CORE.equals(group)) continue;
 
-      JPanel groupPanel = new JPanel(new GridBagLayout());
+      JPanel groupPanel = new JPanel(new GridBagLayout()) {
+        @Override
+        public Color getBackground() {
+          Color color = UIManager.getColor("Panel.background");
+          return isGroupEnabled(group)? color : ColorUtil.darker(color, 1);
+        }
+      };
+      gridPanel.setOpaque(true);
       GridBagConstraints gbc = new GridBagConstraints();
       gbc.insets = new Insets(0, 0, 10, 0);
       gbc.fill = GridBagConstraints.BOTH;
@@ -100,13 +98,11 @@
           return isGroupEnabled(group);
         }
 
-        //@Override
-        //public Color getForeground() {
-        //  return isGroupEnabled(group)? myDescriptionForeground : myDescriptionDisabledForeground;
-        //}
-
+        @Override
+        public Color getForeground() {
+          return ColorUtil.withAlpha(UIManager.getColor("Label.foreground"), .75);
+        }
       };
-      descriptionLabel.setForeground(myDescriptionForeground);
       groupPanel.add(descriptionLabel, gbc);
       gbc.weighty = 1;
       groupPanel.add(Box.createVerticalGlue(), gbc);
@@ -116,6 +112,7 @@
       }
       else {
         JPanel buttonsPanel = new JPanel(new GridLayout(1, 2, 10, 5));
+        buttonsPanel.setOpaque(false);
         LinkLabel customizeButton = createLink(CUSTOMIZE_COMMAND + ":" + group, CUSTOMIZE_TEXT_PROVIDER);
         buttonsPanel.add(customizeButton);
         LinkLabel disableAllButton = createLink(SWITCH_COMMAND + ":" + group, getGroupSwitchTextProvider(group));
@@ -131,8 +128,12 @@
     for (Component component : components) {
       ((JComponent)component).setBorder(
         new CompoundBorder(new CustomLineBorder(ColorUtil.withAlpha(JBColor.foreground(), .2), 0, 0, cursor / 3 < rowCount - 1 ? 1 : 0,
-                                                cursor % COLS != COLS - 1 ? 1 : 0), BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP))
-      );
+                                                cursor % COLS != COLS - 1 ? 1 : 0) {
+          @Override
+          protected Color getColor() {
+            return ColorUtil.withAlpha(JBColor.foreground(), .2);
+          }
+        }, BorderFactory.createEmptyBorder(GAP, GAP, GAP, GAP)));
       cursor++;
     }
   }
@@ -212,22 +213,20 @@
     return null;
   }
 
-
-
-
-
-  private class IdSetPanel extends JPanel {
+  private class IdSetPanel extends JPanel implements LinkListener<String> {
     private JLabel myTitleLabel = new JLabel();
     private JPanel myContentPanel = new JPanel(new GridLayout(0, 3, 5, 5));
     private JButton mySaveButton = new JButton("Save Changes and Go Back");
+    private String myGroup;
 
     private IdSetPanel() {
       setLayout(new VerticalFlowLayout(VerticalFlowLayout.TOP, 0, GAP, true, false));
       add(myTitleLabel);
       add(myContentPanel);
-      JPanel buttonPanel = new JPanel(new BorderLayout());
-      buttonPanel.add(mySaveButton, BorderLayout.WEST);
-      buttonPanel.add(Box.createHorizontalGlue(), BorderLayout.CENTER);
+      JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEADING, 25, 5));
+      buttonPanel.add(mySaveButton);
+      buttonPanel.add(new LinkLabel<String>("Enable All", null, this, "enable"));
+      buttonPanel.add(new LinkLabel<String>("Disable All", null, this, "disable"));
       add(buttonPanel);
       mySaveButton.addActionListener(new ActionListener() {
         @Override
@@ -237,7 +236,19 @@
       });
     }
 
+    @Override
+    public void linkSelected(LinkLabel aSource, String command) {
+      if (myGroup == null) return;
+      boolean enable = "enable".equals(command);
+      List<IdSet> idSets = PluginGroups.getInstance().getSets(myGroup);
+      for (IdSet set : idSets) {
+        PluginGroups.getInstance().setIdSetEnabled(set, enable);
+      }
+      CustomizePluginsStepPanel.this.repaint();
+    }
+
     void update(String group) {
+      myGroup = group;
       myTitleLabel.setText("<html><body><h2 style=\"text-align:left;\">" + group + "</h2></body></html>");
       myContentPanel.removeAll();
       List<IdSet> idSets = PluginGroups.getInstance().getSets(group);
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java
index 2f9d64b..91e2625c 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/CustomizeUIThemeStepPanel.java
@@ -24,16 +24,13 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.util.IconLoader;
 import com.intellij.openapi.util.SystemInfo;
-import com.intellij.ui.ClickListener;
 import com.intellij.util.IconUtil;
 import com.intellij.util.PlatformUtils;
 import com.intellij.util.ui.UIUtil;
-import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.awt.*;
-import java.awt.event.*;
 import java.util.LinkedHashMap;
 import java.util.Map;
 
@@ -44,7 +41,6 @@
   private static final String INTELLIJ = "IntelliJ";
   private static final String ALLOY = "Alloy. IDEA Theme";
   private static final String GTK = "GTK+";
-  private Component myDefaultFocusedComponent;
   private boolean myInitial = true;
   private boolean myColumnMode;
   private JLabel myPreviewLabel;
@@ -57,7 +53,6 @@
     if (SystemInfo.isMac) {
       myLafNames.put(DEFAULT, IconLoader.getIcon("/lafs/OSXAqua.png"));
       myLafNames.put(DARCULA, IconLoader.getIcon("/lafs/OSXDarcula.png"));
-      myLafNames.put(INTELLIJ, IconLoader.getIcon("/lafs/WindowsIntelliJ.png"));
     }
     else if (SystemInfo.isWindows) {
       if (PlatformUtils.isIdeaCommunity()) {
@@ -82,18 +77,18 @@
       final String lafName = entry.getKey();
       Icon icon = entry.getValue();
       final JRadioButton radioButton = new JRadioButton(lafName, myDefaultLafName == null);
+      radioButton.setOpaque(false);
       if (myDefaultLafName == null) {
         radioButton.setSelected(true);
-        myDefaultFocusedComponent = radioButton;
         myDefaultLafName = lafName;
       }
-      final JPanel panel = new JPanel(new BorderLayout(10, 10)) {
+      final JPanel panel = createBigButtonPanel(new BorderLayout(10, 10), radioButton, new Runnable() {
         @Override
-        public Color getBackground() {
-          return radioButton.isSelected() ? UIUtil.getListSelectionBackground() : super.getBackground();
+        public void run() {
+          applyLaf(lafName, CustomizeUIThemeStepPanel.this);
         }
-      };
-      panel.setOpaque(true);
+      });
+      panel.setBorder(BorderFactory.createEmptyBorder(10, 10, 10, 10));
       panel.add(radioButton, BorderLayout.NORTH);
       final JLabel label = new JLabel(myColumnMode ? IconUtil.scale(icon, .2) : icon) {
         @Override
@@ -103,23 +98,8 @@
           return size;
         }
       };
-
+      label.setVerticalAlignment(SwingConstants.TOP);
       panel.add(label, BorderLayout.CENTER);
-      new ClickListener(){
-        @Override
-        public boolean onClick(@NotNull MouseEvent event, int clickCount) {
-          radioButton.setSelected(true);
-          applyLaf(lafName, CustomizeUIThemeStepPanel.this);
-          return true;
-        }
-      }.installOn(label);
-      radioButton.addItemListener(new ItemListener() {
-        @Override
-        public void itemStateChanged(ItemEvent e) {
-          if (e.getStateChange() != ItemEvent.SELECTED) return;
-          applyLaf(lafName, CustomizeUIThemeStepPanel.this);
-        }
-      });
 
       group.add(radioButton);
       buttonsPanel.add(panel);
@@ -137,11 +117,6 @@
   }
 
   @Override
-  Component getDefaultFocusedComponent() {
-    return myDefaultFocusedComponent;
-  }
-
-  @Override
   public Dimension getPreferredSize() {
     Dimension size = super.getPreferredSize();
     size.width += 30;
@@ -178,6 +153,7 @@
       }
       Window window = SwingUtilities.getWindowAncestor(component);
       if (window != null) {
+        window.setBackground(new Color(UIUtil.getPanelBackground().getRGB()));
         SwingUtilities.updateComponentTreeUI(window);
       }
       if (ApplicationManager.getApplication() != null) {
@@ -204,7 +180,7 @@
 
   @Nullable
   private static UIManager.LookAndFeelInfo getLookAndFeelInfo(String name) {
-    if (DEFAULT.equals(name)) return new UIManager.LookAndFeelInfo(DEFAULT, "apple.laf.AquaLookAndFeel");
+    if (DEFAULT.equals(name)) return new UIManager.LookAndFeelInfo(DEFAULT, "com.apple.laf.AquaLookAndFeel");
     if (DARCULA.equals(name)) return new UIManager.LookAndFeelInfo(DARCULA, DarculaLaf.class.getName());
     if (INTELLIJ.equals(name)) return new UIManager.LookAndFeelInfo(INTELLIJ, IntelliJLaf.class.getName());
     if (ALLOY.equals(name)) return new UIManager.LookAndFeelInfo(ALLOY, "com.incors.plaf.alloy.AlloyIdea");
diff --git a/platform/platform-impl/src/com/intellij/ide/customize/PluginGroups.java b/platform/platform-impl/src/com/intellij/ide/customize/PluginGroups.java
index c649cc1..e3af652 100644
--- a/platform/platform-impl/src/com/intellij/ide/customize/PluginGroups.java
+++ b/platform/platform-impl/src/com/intellij/ide/customize/PluginGroups.java
@@ -32,7 +32,7 @@
 
 class PluginGroups {
   static final String CORE = "Core";
-  private static final int MAX_DESCR_LENGTH = 80;
+  private static final int MAX_DESCR_LENGTH = 50;
 
 
   private static PluginGroups instance = null;
@@ -62,7 +62,7 @@
       myPluginsFromRepository.addAll(RepositoryHelper.loadPluginsFromRepository(null));
     }
     catch (Exception e) {
-      e.printStackTrace();
+      //OK, it's offline
     }
     PluginManager.loadDisabledPlugins(new File(PathManager.getConfigPath()).getPath(), myDisabledPluginIds);
 
diff --git a/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java
index fd48655..02e4d54 100644
--- a/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/ide/dnd/DnDManagerImpl.java
@@ -21,6 +21,7 @@
 import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.Pair;
 import com.intellij.reference.SoftReference;
+import com.intellij.ui.MouseDragHelper;
 import com.intellij.ui.awt.RelativeRectangle;
 import com.intellij.util.ui.GeometryUtil;
 import com.intellij.util.ui.UIUtil;
@@ -538,7 +539,7 @@
     public void dragGestureRecognized(DragGestureEvent dge) {
       try {
         final DnDSource source = getSource(dge.getComponent());
-        if (source == null) return;
+        if (source == null || !MouseDragHelper.checkModifiers(dge.getTriggerEvent())) return;
 
         DnDAction action = getDnDActionForPlatformAction(dge.getDragAction());
         if (source.canStartDragging(action, dge.getDragOrigin())) {
diff --git a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java
index aeb9e65..bea92c9 100644
--- a/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/ide/impl/DataManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +20,6 @@
 import com.intellij.ide.impl.dataRules.*;
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.application.ModalityState;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.extensions.Extensions;
@@ -48,7 +47,7 @@
 import java.util.Map;
 import java.util.Set;
 
-public class DataManagerImpl extends DataManager implements ApplicationComponent {
+public class DataManagerImpl extends DataManager {
   private static final Logger LOG = Logger.getInstance("#com.intellij.ide.impl.DataManagerImpl");
   private final Map<String, GetDataRule> myDataConstantToRuleMap = new THashMap<String, GetDataRule>();
   private WindowManagerEx myWindowManager;
@@ -57,14 +56,6 @@
     registerRules();
   }
 
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
   @Nullable
   private Object getData(@NotNull String dataId, final Component focusedComponent) {
     for (Component c = focusedComponent; c != null; c = c.getParent()) {
@@ -285,12 +276,6 @@
   }
 
   @Override
-  @NotNull
-  public String getComponentName() {
-    return "DataManager";
-  }
-
-  @Override
   public <T> void saveInDataContext(DataContext dataContext, @NotNull Key<T> dataKey, @Nullable T data) {
     if (dataContext instanceof UserDataHolder) {
       ((UserDataHolder)dataContext).putUserData(dataKey, data);
diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.form b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.form
index 05b6682..083237a 100644
--- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.form
+++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.form
@@ -49,7 +49,7 @@
             <properties/>
             <border type="none"/>
             <children>
-              <component id="77a6b" class="javax.swing.JLabel">
+              <component id="77a6b" class="javax.swing.JLabel" binding="myNewPasswordLabel">
                 <constraints>
                   <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
                 </constraints>
@@ -103,7 +103,7 @@
             <properties/>
             <border type="none"/>
             <children>
-              <component id="923f3" class="javax.swing.JLabel">
+              <component id="923f3" class="javax.swing.JLabel" binding="myPasswordLabel">
                 <constraints>
                   <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
                 </constraints>
diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.java
index 903811f..2307fa9 100644
--- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.java
+++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/PasswordComponentBase.java
@@ -41,6 +41,8 @@
   protected JPasswordField myNewPasswordField;
   protected JPasswordField myConfirmPasswordField;
   protected JCheckBox myEncryptCheckBox;
+  protected JLabel myPasswordLabel;
+  protected JLabel myNewPasswordLabel;
 
 
   public PasswordComponentBase(@NotNull MasterKeyPasswordSafe safe, @NotNull String title) {
@@ -48,6 +50,7 @@
     myTitle = title;
     myIconLabel.setText("");
     myIconLabel.setIcon(AllIcons.General.PasswordLock);
+    myIconLabel.setDisabledIcon(AllIcons.General.PasswordLock);
     //myPromptLabel.setUI(new MultiLineLabelUI());
     myPromptLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
 
diff --git a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/ResetPasswordComponent.java b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/ResetPasswordComponent.java
index b645f25..ce75bdb 100644
--- a/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/ResetPasswordComponent.java
+++ b/platform/platform-impl/src/com/intellij/ide/passwordSafe/impl/providers/masterKey/ResetPasswordComponent.java
@@ -18,6 +18,7 @@
 import com.intellij.ide.passwordSafe.HelpID;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Messages;
+import com.intellij.util.ui.DialogUtil;
 import com.intellij.util.ui.UIUtil;
 
 /**
@@ -28,13 +29,17 @@
   private final boolean myFirstTime;
 
   public ResetPasswordComponent(MasterKeyPasswordSafe safe, boolean firstTime) {
-    super(safe, "Reset");
+    super(safe, firstTime ? "Setup" : "Reset");
     myFirstTime = firstTime;
     UIUtil.setEnabled(myPasswordPanel, false, true);
     myPasswordPanel.setVisible(false);
     if (firstTime) {
-      myPromptLabel.setText("<html><br>Specify the password for the password database.<br>" +
-                            "Leave blank to disable the master password.</html>");
+      myNewPasswordLabel.setText(myPasswordLabel.getText());
+      myNewPasswordLabel.setDisplayedMnemonic(myPasswordLabel.getDisplayedMnemonic());
+      myNewPasswordLabel.setDisplayedMnemonicIndex(myPasswordLabel.getDisplayedMnemonicIndex());
+      DialogUtil.registerMnemonic(myPasswordLabel, null);
+      myPromptLabel.setText("<html><br>Specify the new password for the password database.<br>" +
+                            "Leave blank to disable the master password protection.</html>");
     }
     else {
       myPromptLabel.setText("<html><br>The password for the password database will be reset.<br>" +
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java b/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java
index 69944b4..c60ddc4 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/AppearanceConfigurable.java
@@ -154,6 +154,7 @@
     settings.OVERRIDE_NONIDEA_LAF_FONTS = myComponent.myOverrideLAFFonts.isSelected();
     settings.MOVE_MOUSE_ON_DEFAULT_BUTTON = myComponent.myMoveMouseOnDefaultButtonCheckBox.isSelected();
     settings.HIDE_NAVIGATION_ON_FOCUS_LOSS = myComponent.myHideNavigationPopupsCheckBox.isSelected();
+    settings.DND_WITH_PRESSED_ALT_ONLY = myComponent.myAltDNDCheckBox.isSelected();
 
     update |= settings.DISABLE_MNEMONICS != myComponent.myDisableMnemonics.isSelected();
     settings.DISABLE_MNEMONICS = myComponent.myDisableMnemonics.isSelected();
@@ -270,6 +271,7 @@
     myComponent.myHideIconsInQuickNavigation.setSelected(settings.SHOW_ICONS_IN_QUICK_NAVIGATION);
     myComponent.myMoveMouseOnDefaultButtonCheckBox.setSelected(settings.MOVE_MOUSE_ON_DEFAULT_BUTTON);
     myComponent.myHideNavigationPopupsCheckBox.setSelected(settings.HIDE_NAVIGATION_ON_FOCUS_LOSS);
+    myComponent.myAltDNDCheckBox.setSelected(settings.DND_WITH_PRESSED_ALT_ONLY);
     myComponent.myLafComboBox.setSelectedItem(LafManager.getInstance().getCurrentLookAndFeel());
     myComponent.myOverrideLAFFonts.setSelected(settings.OVERRIDE_NONIDEA_LAF_FONTS);
     myComponent.myDisableMnemonics.setSelected(settings.DISABLE_MNEMONICS);
@@ -330,6 +332,7 @@
 
     isModified |= myComponent.myMoveMouseOnDefaultButtonCheckBox.isSelected() != settings.MOVE_MOUSE_ON_DEFAULT_BUTTON;
     isModified |= myComponent.myHideNavigationPopupsCheckBox.isSelected() != settings.HIDE_NAVIGATION_ON_FOCUS_LOSS;
+    isModified |= myComponent.myAltDNDCheckBox.isSelected() != settings.DND_WITH_PRESSED_ALT_ONLY;
     isModified |= !Comparing.equal(myComponent.myLafComboBox.getSelectedItem(), LafManager.getInstance().getCurrentLookAndFeel());
     if (WindowManagerEx.getInstanceEx().isAlphaModeSupported()) {
       isModified |= myComponent.myEnableAlphaModeCheckBox.isSelected() != settings.ENABLE_ALPHA_MODE;
@@ -385,6 +388,7 @@
     private JCheckBox myDisableMnemonics;
     private JCheckBox myDisableMnemonicInControlsCheckBox;
     private JCheckBox myHideNavigationPopupsCheckBox;
+    private JCheckBox myAltDNDCheckBox;
     private JCheckBox myAllowMergeButtons;
     private JBCheckBox myUseSmallLabelsOnTabs;
     private JBCheckBox myWidescreenLayoutCheckBox;
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/AppearancePanel.form b/platform/platform-impl/src/com/intellij/ide/ui/AppearancePanel.form
index 911ca64..59197a0 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/AppearancePanel.form
+++ b/platform/platform-impl/src/com/intellij/ide/ui/AppearancePanel.form
@@ -3,7 +3,7 @@
   <grid id="41bd3" binding="myPanel" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
     <margin top="0" left="0" bottom="0" right="0"/>
     <constraints>
-      <xy x="81" y="44" width="507" height="731"/>
+      <xy x="81" y="44" width="510" height="822"/>
     </constraints>
     <properties/>
     <border type="none"/>
@@ -16,7 +16,7 @@
         <properties/>
         <border type="none"/>
         <children>
-          <grid id="d992b" layout-manager="GridLayoutManager" row-count="8" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+          <grid id="d992b" layout-manager="GridLayoutManager" row-count="9" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
             <margin top="0" left="0" bottom="0" right="0"/>
             <constraints>
               <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="1" fill="3" indent="0" use-parent-layout="false"/>
@@ -49,7 +49,7 @@
               <grid id="4c401" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
                 <margin top="0" left="0" bottom="0" right="0"/>
                 <constraints>
-                  <grid row="4" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+                  <grid row="5" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
                 </constraints>
                 <properties/>
                 <border type="none"/>
@@ -77,7 +77,7 @@
               <grid id="d9fb" layout-manager="GridLayoutManager" row-count="2" 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>
-                  <grid row="6" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+                  <grid row="7" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
                 </constraints>
                 <properties/>
                 <border type="none"/>
@@ -137,7 +137,7 @@
               <grid id="ce348" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
                 <margin top="0" left="0" bottom="0" right="0"/>
                 <constraints>
-                  <grid row="5" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+                  <grid row="6" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
                 </constraints>
                 <properties/>
                 <border type="none"/>
@@ -164,7 +164,9 @@
               </component>
               <component id="9327f" class="javax.swing.JCheckBox" binding="myHideNavigationPopupsCheckBox">
                 <constraints>
-                  <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+                  <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false">
+                    <preferred-size width="271" height="29"/>
+                  </grid>
                 </constraints>
                 <properties>
                   <margin top="2" left="0" bottom="2" right="2"/>
@@ -174,7 +176,7 @@
               <grid id="372a6" layout-manager="GridLayoutManager" row-count="1" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
                 <margin top="0" left="0" bottom="0" right="0"/>
                 <constraints>
-                  <grid row="7" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+                  <grid row="8" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
                 </constraints>
                 <properties/>
                 <border type="none"/>
@@ -198,6 +200,14 @@
                   </component>
                 </children>
               </grid>
+              <component id="2124a" class="javax.swing.JCheckBox" binding="myAltDNDCheckBox">
+                <constraints>
+                  <grid row="4" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+                </constraints>
+                <properties>
+                  <text value="Drag-n-Drop with ALT pressed only"/>
+                </properties>
+              </component>
             </children>
           </grid>
           <grid id="26e1c" binding="myTransparencyPanel" layout-manager="GridLayoutManager" row-count="3" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java
index 6e1d490..b13d025 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/LafManagerImpl.java
@@ -119,7 +119,10 @@
   private final UISettings myUiSettings;
   private String myLastWarning = null;
   private PropertyChangeListener myThemeChangeListener = null;
-
+  private static final HashMap<String, String> ourLafClassesAliases = new HashMap<String, String>();
+  static {
+    ourLafClassesAliases.put("idea.dark.laf.classname", DarculaLookAndFeelInfo.CLASS_NAME);
+  }
 
   /**
    * Invoked via reflection.
@@ -251,6 +254,9 @@
       Element child = (Element)o;
       if (ELEMENT_LAF.equals(child.getName())) {
         className = child.getAttributeValue(ATTRIBUTE_CLASS_NAME);
+        if (className != null && ourLafClassesAliases.containsKey(className)) {
+          className = ourLafClassesAliases.get(className);
+        }
         break;
       }
     }
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLookAndFeelInfo.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLookAndFeelInfo.java
index cf84927..880ff1a 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLookAndFeelInfo.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLookAndFeelInfo.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -24,7 +24,7 @@
  * @author Konstantin Bulenkov
  */
 public class DarculaLookAndFeelInfo extends UIManager.LookAndFeelInfo {
-    @NonNls public static final String CLASS_NAME = "idea.dark.laf.classname";
+    @NonNls public static final String CLASS_NAME = DarculaLaf.class.getName();
     public DarculaLookAndFeelInfo(){
       super(IdeBundle.message("idea.dark.look.and.feel"), CLASS_NAME);
     }
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaProgressBarUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaProgressBarUI.java
index f72399a..37f5ed9 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaProgressBarUI.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaProgressBarUI.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -57,33 +57,41 @@
     g.setColor(new JBColor(Gray._240, Gray._128));
     int w = c.getWidth();
     int h = c.getPreferredSize().height;
-    g.fillRect(0, (c.getHeight() - h)/2, w, h);
+    if (c.isOpaque()) {
+      g.fillRect(0, (c.getHeight() - h)/2, w, h);
+    }
     g.setColor(new JBColor(Gray._165, Gray._88));
     GraphicsUtil.setupAAPainting(g);
-    Path2D.Double path = new Path2D.Double();
-    int ww = getPeriodLength() / 2;
-    g.translate(0, (c.getHeight() - h)/2);
-    path.moveTo(0, 0);
-    path.lineTo(ww, 0);
-    path.lineTo(ww - h / 2, h);
-    path.lineTo(-h / 2, h);
-    path.lineTo(0, 0);
-    path.closePath();
+    g.translate(0, (c.getHeight() - h) / 2);
     int x = -offset;
+    final Area aaa = new Area(new RoundRectangle2D.Double(1, 1, w - 2, h - 2, 8, 8));
     while (x < Math.max(c.getWidth(), c.getHeight())) {
-      g.translate(x, 0);
-      ((Graphics2D)g).fill(path);
-      g.translate(-x, 0);
+      Path2D.Double path = new Path2D.Double();
+      int ww = getPeriodLength() / 2;
+      path.moveTo(x, 0);
+      path.lineTo(x+ww, 0);
+      path.lineTo(x+ww - h / 2, h);
+      path.lineTo(x-h / 2, h);
+      path.lineTo(x, 0);
+      path.closePath();
+
+      final Area area = new Area(path);
+      area.intersect(aaa);
+      ((Graphics2D)g).fill(area);
       x+= getPeriodLength();
     }
     offset = (offset + 1) % getPeriodLength();
     Area area = new Area(new Rectangle2D.Double(0, 0, w, h));
     area.subtract(new Area(new RoundRectangle2D.Double(1,1,w-2, h-2, 8,8)));
     ((Graphics2D)g).setPaint(Gray._128);
-    ((Graphics2D)g).fill(area);
+    if (c.isOpaque()) {
+      ((Graphics2D)g).fill(area);
+    }
     area.subtract(new Area(new RoundRectangle2D.Double(0,0,w, h, 9,9)));
     ((Graphics2D)g).setPaint(c.getParent().getBackground());
-    ((Graphics2D)g).fill(area);
+    if (c.isOpaque()) {
+      ((Graphics2D)g).fill(area);
+    }
     g.drawRoundRect(1,1, w-3, h-3, 8,8);
     g.translate(0, -(c.getHeight() - h)/2);
 
@@ -123,7 +131,9 @@
 
     g.setColor(c.getParent().getBackground());
     Graphics2D g2 = (Graphics2D)g;
-    g.fillRect(0, 0, w, h);
+    if (c.isOpaque()) {
+      g.fillRect(0, 0, w, h);
+    }
 
     g2.translate(0, (c.getHeight() - h)/2);
     g2.setColor(progressBar.getForeground());
diff --git a/platform/platform-impl/src/com/intellij/internal/statistic/persistence/UsageStatisticsPersistenceComponent.java b/platform/platform-impl/src/com/intellij/internal/statistic/persistence/UsageStatisticsPersistenceComponent.java
index 273e5803..6529838 100644
--- a/platform/platform-impl/src/com/intellij/internal/statistic/persistence/UsageStatisticsPersistenceComponent.java
+++ b/platform/platform-impl/src/com/intellij/internal/statistic/persistence/UsageStatisticsPersistenceComponent.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -42,7 +42,7 @@
     )}
 )
 public class UsageStatisticsPersistenceComponent extends BasicSentUsagesPersistenceComponent
-  implements ApplicationComponent, PersistentStateComponent<Element> {
+  implements NamedComponent, PersistentStateComponent<Element> {
 
   @NonNls private boolean isAllowed = false;
   @NonNls private boolean isShowNotification = true;
@@ -171,12 +171,4 @@
   public String getComponentName() {
     return "SentUsagesPersistenceComponent";
   }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
 }
diff --git a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java
index 3733d3f..1ef2f4c 100644
--- a/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/notification/impl/NotificationsManagerImpl.java
@@ -276,7 +276,9 @@
 
     final JPanel content = new NonOpaquePanel(new BorderLayout((int)(label.getIconTextGap() * 1.5), (int)(label.getIconTextGap() * 1.5)));
 
-    text.setCaretPosition(0);
+    if (text.getCaret() != null) {
+      text.setCaretPosition(0);
+    }
     JScrollPane pane = ScrollPaneFactory.createScrollPane(text,
                                                           ScrollPaneConstants.VERTICAL_SCROLLBAR_AS_NEEDED,
                                                           ScrollPaneConstants.HORIZONTAL_SCROLLBAR_AS_NEEDED);
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/BackspaceAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/BackspaceAction.java
index ad5d0c2..5a378d4 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/BackspaceAction.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/BackspaceAction.java
@@ -78,12 +78,7 @@
 
   private static void doBackSpaceAtCaret(@NotNull Editor editor) {
     if(editor.getSelectionModel().hasSelection()) {
-      int newOffset = editor.getSelectionModel().getSelectionStart();
-      if (EditorActionUtil.canEditAtOffset(editor, newOffset)) {
-        editor.getCaretModel().moveToOffset(newOffset);
-        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
-        EditorModificationUtil.deleteSelectedText(editor);
-      }
+      doBackspaceAction(editor);
       return;
     }
 
@@ -131,4 +126,13 @@
       }
     }
   }
+
+  static void doBackspaceAction(@NotNull Editor editor) {
+    int newOffset = editor.getSelectionModel().getSelectionStart();
+    if (EditorActionUtil.canEditAtOffset(editor, newOffset)) {
+      editor.getCaretModel().moveToOffset(newOffset);
+      editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
+      EditorModificationUtil.deleteSelectedText(editor);
+    }
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordEndAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordEndAction.java
index c261c6c..5785f01 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordEndAction.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordEndAction.java
@@ -14,23 +14,22 @@
  * limitations under the License.
  */
 
-/*
- * Created by IntelliJ IDEA.
- * User: max
- * Date: May 14, 2002
- * Time: 7:18:30 PM
- * To change template for new class use 
- * Code Style | Class Templates options (Tools | IDE Options).
- */
 package com.intellij.openapi.editor.actions;
 
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.EditorModificationUtil;
 import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
 import com.intellij.openapi.ide.CopyPasteManager;
 
+/*
+ * Created by IntelliJ IDEA.
+ * User: max
+ * Date: May 14, 2002
+ * Time: 7:18:30 PM
+ */
 public class DeleteToWordEndAction extends TextComponentEditorAction {
   public DeleteToWordEndAction() {
     super(new Handler(false));
@@ -60,6 +59,12 @@
       if (myNegateCamelMode) {
         camelMode = !camelMode;
       }
+
+      if (editor.getSelectionModel().hasSelection()) {
+        EditorModificationUtil.deleteSelectedText(editor);
+        return;
+      }
+
       deleteToWordEnd(editor, camelMode);
     }
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordStartAction.java b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordStartAction.java
index 76e2516..b4839ab 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordStartAction.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/actions/DeleteToWordStartAction.java
@@ -24,9 +24,7 @@
  */
 package com.intellij.openapi.editor.actions;
 
-import com.intellij.openapi.editor.CaretModel;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.*;
 import com.intellij.openapi.editor.actionSystem.EditorWriteActionHandler;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.actionSystem.DataContext;
@@ -81,6 +79,10 @@
     @Override
     public void executeWriteAction(Editor editor, DataContext dataContext) {
       CommandProcessor.getInstance().setCurrentCommandGroupId(EditorActionUtil.DELETE_COMMAND_GROUP);
+      if (editor.getSelectionModel().hasSelection()) {
+        BackspaceAction.doBackspaceAction(editor);
+        return;
+      }
       deleteToWordStart(editor);
     }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java b/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java
index 3ef8a15..0f4ba21 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/ex/EditorSettingsExternalizable.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -25,8 +25,6 @@
 import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.NamedJDOMExternalizable;
 import com.intellij.openapi.util.WriteExternalException;
-import com.intellij.openapi.vfs.CharsetToolkit;
-import com.intellij.openapi.vfs.encoding.EncodingManager;
 import org.intellij.lang.annotations.MagicConstant;
 import org.jdom.Element;
 import org.jetbrains.annotations.NonNls;
@@ -36,7 +34,6 @@
 import java.beans.PropertyChangeSupport;
 import java.io.File;
 import java.lang.reflect.Field;
-import java.nio.charset.Charset;
 import java.util.EnumSet;
 import java.util.Set;
 
@@ -73,10 +70,6 @@
     public boolean IS_DND_ENABLED = true;
     public boolean IS_WHEEL_FONTCHANGE_ENABLED = false;
     public boolean IS_MOUSE_CLICK_SELECTION_HONORS_CAMEL_WORDS = true;
-    @Deprecated
-    public boolean IS_NATIVE2ASCII_FOR_PROPERTIES_FILES;
-    @Deprecated
-    public String DEFAULT_PROPERTIES_FILES_CHARSET_NAME;
 
     public boolean RENAME_VARIABLES_INPLACE = true;
     public boolean PRESELECT_RENAME = true;
@@ -529,18 +522,4 @@
   public void setPreselectRename(final boolean val) {
     myOptions.PRESELECT_RENAME = val;
   }
-
-
-  // returns true if something has been migrated
-  public boolean migrateCharsetSettingsTo(EncodingManager encodingManager) {
-    if (myOptions.DEFAULT_PROPERTIES_FILES_CHARSET_NAME != null) {
-      Charset charset = CharsetToolkit.forName(myOptions.DEFAULT_PROPERTIES_FILES_CHARSET_NAME);
-      if (charset != null) {
-        encodingManager.setDefaultCharsetForPropertiesFiles(null, charset);
-        encodingManager.setNative2AsciiForPropertiesFiles(null, myOptions.IS_NATIVE2ASCII_FOR_PROPERTIES_FILES);
-      }
-      return true;
-    }
-    return false;
-  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java
index e32853c..a2f44fc 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/CaretModelImpl.java
@@ -343,7 +343,8 @@
       return;
     }
     if (myCurrentCaret != null) {
-      throw new IllegalStateException("Current caret is defined, cannot operate on other ones");
+      action.perform(myCurrentCaret);
+      return;
     }
     doWithCaretMerging(new Runnable() {
       public void run() {
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java
index 611a7c2..42abddc 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorFactoryImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityStateListener;
 import com.intellij.openapi.application.impl.LaterInvocator;
+import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
@@ -45,7 +46,7 @@
 
 import java.util.List;
 
-public class EditorFactoryImpl extends EditorFactory {
+public class EditorFactoryImpl extends EditorFactory implements ApplicationComponent {
   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.editor.impl.EditorFactoryImpl");
   private final EditorEventMulticasterImpl myEditorEventMulticaster = new EditorEventMulticasterImpl();
   private final EventDispatcher<EditorFactoryListener> myEditorFactoryEventDispatcher = EventDispatcher.create(EditorFactoryListener.class);
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
index a53ce9b..541fa89 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorImpl.java
@@ -68,10 +68,7 @@
 import com.intellij.openapi.wm.IdeGlassPane;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiFile;
-import com.intellij.ui.GuiUtils;
-import com.intellij.ui.JBColor;
-import com.intellij.ui.LightweightHint;
-import com.intellij.ui.SideBorder;
+import com.intellij.ui.*;
 import com.intellij.ui.components.JBLayeredPane;
 import com.intellij.ui.components.JBScrollBar;
 import com.intellij.ui.components.JBScrollPane;
@@ -140,7 +137,7 @@
   private static final boolean HONOR_CAMEL_HUMPS_ON_TRIPLE_CLICK =
     Boolean.parseBoolean(System.getProperty("idea.honor.camel.humps.on.triple.click"));
   private static final Key<BufferedImage> BUFFER = Key.create("buffer");
-  public static final JBColor CURSOR_FOREGROUND = new JBColor(Color.white, Color.black);
+  public static final JBColor CURSOR_FOREGROUND = new JBColor(Gray._255, Gray._0);
   @NotNull private final DocumentEx myDocument;
 
   private final JPanel myPanel;
@@ -383,7 +380,7 @@
     };
 
     ((MarkupModelEx)DocumentMarkupModel.forDocument(myDocument, myProject, true)).addMarkupModelListener(myCaretModel, markupModelListener);
-    ((MarkupModelEx)getMarkupModel()).addMarkupModelListener(myCaretModel, markupModelListener);
+    getMarkupModel().addMarkupModelListener(myCaretModel, markupModelListener);
 
     myDocument.addDocumentListener(myFoldingModel, myCaretModel);
     myDocument.addDocumentListener(myCaretModel, myCaretModel);
@@ -2915,7 +2912,7 @@
         for (int i = 0; i < myCount; i++) {
           if (!Comparing.equal(color[i], currentColor)) {
             currentColor = color[i];
-            g.setColor(currentColor != null ? currentColor : Color.black);
+            g.setColor(currentColor != null ? currentColor : JBColor.black);
           }
 
           drawChars(g, data[i], starts[i], ends[i], x[i], y[i]);
@@ -4467,7 +4464,7 @@
     //myEditorComponent.setOpaque(true);
   }
 
-  private class CaretRectangle {
+  private static class CaretRectangle {
     private final Point myPoint;
     private final int myWidth;
     private final Caret myCaret;
@@ -4588,7 +4585,7 @@
       }
       else {
         Color caretColor = myScheme.getColor(EditorColors.CARET_COLOR);
-        if (caretColor == null) caretColor = new JBColor(Color.BLACK, Color.WHITE);
+        if (caretColor == null) caretColor = new JBColor(Gray._0, Gray._255);
         g.setColor(caretColor);
         g.fillRect(x, y, width, lineHeight - 1);
         final LogicalPosition startPosition = caret == null ? getCaretModel().getLogicalPosition() : caret.getLogicalPosition();
@@ -5777,7 +5774,7 @@
     }
   }
 
-  private boolean isToggleCaretEvent(MouseEvent e) {
+  private static boolean isToggleCaretEvent(MouseEvent e) {
     KeymapManager keymapManager = KeymapManager.getInstance();
     if (keymapManager == null) {
       return false;
@@ -6763,7 +6760,7 @@
         else {
           g.setColor(UIUtil.getPanelBackground());
           g.drawLine(x, y, x + width, y);
-          g.setColor(new Color(0, 0, 0, 90));
+          g.setColor(Gray._0.withAlpha(90));
           g.drawLine(x, y, x + width, y);
         }
       }
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java
index 65f8ed6..d750a2f 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/EditorMarkupModelImpl.java
@@ -1254,7 +1254,7 @@
                 double cy = 0;
                 double rx = size.width / 10;
                 int ry = myEditor.getLineHeight() * 3 / 2;
-                g2.setPaint(new GradientPaint(0, 0, new Color(255, 255, 255, 75), 0, ry, new Color(255, 255, 255, 10)));
+                g2.setPaint(new GradientPaint(0, 0, Gray._255.withAlpha(75), 0, ry, Gray._255.withAlpha(10)));
                 double pseudoMajorAxis = size.width - rx * 9 / 5;
                 Shape topShape1 = new Ellipse2D.Double(cx - rx - pseudoMajorAxis / 2, cy - ry, 2 * rx, 2 * ry);
                 Shape topShape2 = new Ellipse2D.Double(cx - rx + pseudoMajorAxis / 2, cy - ry, 2 * rx, 2 * ry);
@@ -1264,7 +1264,7 @@
                 g2.fill(topArea);
                 Area bottomArea = new Area(s);
                 bottomArea.subtract(topArea);
-                g2.setPaint(new GradientPaint(0, size.height - ry, new Color(0, 0, 0, 10), 0, size.height, new Color(255, 255, 255, 30)));
+                g2.setPaint(new GradientPaint(0, size.height - ry, Gray._0.withAlpha(10), 0, size.height, Gray._255.withAlpha(30)));
                 g2.fill(bottomArea);
               }
             }
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/VisibleEditorsTracker.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/VisibleEditorsTracker.java
index 1c380a0..bacbf42 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/VisibleEditorsTracker.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/VisibleEditorsTracker.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -19,15 +19,13 @@
 import com.intellij.openapi.command.CommandAdapter;
 import com.intellij.openapi.command.CommandEvent;
 import com.intellij.openapi.command.CommandProcessor;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.EditorFactory;
-import org.jetbrains.annotations.NotNull;
 
 import java.util.HashSet;
 import java.util.Set;
 
-public class VisibleEditorsTracker extends CommandAdapter implements ApplicationComponent{
+public class VisibleEditorsTracker extends CommandAdapter {
   private final Set<Editor> myEditorsVisibleOnCommandStart = new HashSet<Editor>();
   private long myCurrentCommandStart;
   private long myLastCommandFinish;
@@ -41,20 +39,6 @@
     commandProcessor.addCommandListener(this);
   }
 
-  @Override
-  @NotNull
-  public String getComponentName() {
-    return "VisibleEditorsTracker";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
   public boolean wasEditorVisibleOnCommandStart(Editor editor){
     return myEditorsVisibleOnCommandStart.contains(editor);
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java
index 1a3159f..89521379 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/FileDocumentManagerImpl.java
@@ -23,7 +23,6 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.command.UndoConfirmationPolicy;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.diff.DiffManager;
 import com.intellij.openapi.diff.DocumentContent;
@@ -41,7 +40,9 @@
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.fileEditor.*;
 import com.intellij.openapi.fileEditor.impl.text.TextEditorImpl;
-import com.intellij.openapi.fileTypes.*;
+import com.intellij.openapi.fileTypes.BinaryFileTypeDecompilers;
+import com.intellij.openapi.fileTypes.FileType;
+import com.intellij.openapi.fileTypes.UnknownFileType;
 import com.intellij.openapi.project.*;
 import com.intellij.openapi.project.ex.ProjectEx;
 import com.intellij.openapi.ui.DialogBuilder;
@@ -84,7 +85,7 @@
 import java.util.*;
 import java.util.List;
 
-public class FileDocumentManagerImpl extends FileDocumentManager implements ApplicationComponent, VirtualFileListener,
+public class FileDocumentManagerImpl extends FileDocumentManager implements VirtualFileListener,
                                                                             ProjectManagerListener, SafeWriteRequestor {
   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl");
 
@@ -153,20 +154,6 @@
   }
 
   @Override
-  @NotNull
-  public String getComponentName() {
-    return "FileDocumentManager";
-  }
-
-  @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   @Nullable
   public Document getDocument(@NotNull final VirtualFile file) {
     DocumentEx document = (DocumentEx)getCachedDocument(file);
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java
index d83caa3..2c78198 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/NonProjectFileWritingAccessProvider.java
@@ -19,6 +19,8 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.components.StorageScheme;
 import com.intellij.openapi.components.impl.stores.IProjectStore;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.project.ex.ProjectEx;
 import com.intellij.openapi.roots.ModuleRootAdapter;
@@ -105,6 +107,8 @@
   }
 
   private boolean isProjectFile(@NotNull VirtualFile file) {
+    if (ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file)) return true;
+    
     if (myProject instanceof ProjectEx) {
       IProjectStore store = ((ProjectEx)myProject).getStateStore();
 
@@ -115,9 +119,12 @@
       }
 
       if (file.equals(store.getWorkspaceFile()) || file.equals(store.getProjectFile())) return true;
+      for (Module each : ModuleManager.getInstance(myProject).getModules()) {
+        if (file.equals(each.getModuleFile())) return true;
+      }
     }
 
-    return ProjectFileIndex.SERVICE.getInstance(myProject).isInContent(file);
+    return false;
   }
 
   @TestOnly
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java
index ce9a004..8e09e72 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/impl/FileTypeManagerImpl.java
@@ -58,6 +58,7 @@
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
 
 import javax.swing.*;
 import java.io.*;
@@ -264,7 +265,9 @@
       return true;
     }
   });
-  void drainReDetectQueue() {
+
+  @TestOnly
+  public void drainReDetectQueue() {
     reDetectQueue.drain();
   }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java
index 12cbd12..4c09321 100644
--- a/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/keymap/impl/KeymapManagerImpl.java
@@ -84,9 +84,9 @@
       RoamingType.PER_USER);
 
     Keymap[] keymaps = defaultKeymap.getKeymaps();
+    String systemDefaultKeymap = defaultKeymap.getDefaultKeymapName();
     for (Keymap keymap : keymaps) {
       addKeymap(keymap);
-      String systemDefaultKeymap = defaultKeymap.getDefaultKeymapName();
       if (systemDefaultKeymap.equals(keymap.getName())) {
         setActiveKeymap(keymap);
       }
diff --git a/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java
index de02b0d..7f4da6b2 100644
--- a/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/progress/impl/ProgressManagerImpl.java
@@ -21,6 +21,7 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.application.ex.ApplicationEx;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.*;
 import com.intellij.openapi.progress.util.ProgressWindow;
 import com.intellij.openapi.progress.util.SmoothProgressAdapter;
@@ -49,6 +50,7 @@
 import java.util.concurrent.atomic.AtomicInteger;
 
 public class ProgressManagerImpl extends ProgressManager implements Disposable{
+  private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.progress.impl.ProgressManagerImpl");
   private final AtomicInteger myCurrentUnsafeProgressCount = new AtomicInteger(0);
   private final AtomicInteger myCurrentModalProgressCount = new AtomicInteger(0);
 
@@ -172,8 +174,14 @@
       @Override
       public void run() {
         try {
-          if (progress != null && !progress.isRunning()) {
-            progress.start();
+          try {
+            if (progress != null && !progress.isRunning()) {
+              progress.start();
+            }
+          }
+          catch (Throwable e) {
+            LOG.info("Unexpected error when starting progress: ", e);
+            throw new RuntimeException(e);
           }
           process.run();
           maybeSleep();
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java
index e8d8ba4..b50a8d2 100644
--- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java
+++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/PluginDownloader.java
@@ -94,7 +94,7 @@
 
   public boolean prepareToInstall(ProgressIndicator pi) throws IOException {
     IdeaPluginDescriptor descriptor = null;
-    if (PluginManager.isPluginInstalled(PluginId.getId(myPluginId))) {
+    if (!Boolean.getBoolean(StartupActionScriptManager.STARTUP_WIZARD_MODE) && PluginManager.isPluginInstalled(PluginId.getId(myPluginId))) {
       //store old plugins file
       descriptor = PluginManager.getPlugin(PluginId.getId(myPluginId));
       LOG.assertTrue(descriptor != null);
@@ -115,14 +115,16 @@
       errorMessage = ex.getMessage();
     }
     if (myFile == null) {
-      final String text = IdeBundle.message("error.plugin.was.not.installed", getPluginName(), errorMessage);
-      final String title = IdeBundle.message("title.failed.to.download");
-      ApplicationManager.getApplication().invokeLater(new Runnable() {
-        @Override
-        public void run() {
-          Messages.showErrorDialog(text, title);
-        }
-      });
+      if (ApplicationManager.getApplication() != null) {
+        final String text = IdeBundle.message("error.plugin.was.not.installed", getPluginName(), errorMessage);
+        final String title = IdeBundle.message("title.failed.to.download");
+        ApplicationManager.getApplication().invokeLater(new Runnable() {
+          @Override
+          public void run() {
+            Messages.showErrorDialog(text, title);
+          }
+        });
+      }
       return false;
     }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java
index 409950a..07c7eaa 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -221,15 +221,11 @@
 
   @Override
   public boolean isUseUTFGuessing(final VirtualFile virtualFile) {
-    Project project = guessProject(virtualFile);
-    return project == null || EncodingProjectManager.getInstance(project).isUseUTFGuessing(virtualFile);
+    return true;
   }
 
   @Override
   public void setUseUTFGuessing(final VirtualFile virtualFile, final boolean useUTFGuessing) {
-    Project project = guessProject(virtualFile);
-    if (project == null) return;
-    EncodingProjectManager.getInstance(project).setUseUTFGuessing(virtualFile, useUTFGuessing);
   }
 
   @Override
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java
index 43f72f18..65a04b9 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/encoding/EncodingProjectManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -22,20 +22,14 @@
  */
 package com.intellij.openapi.vfs.encoding;
 
-import com.intellij.ide.GeneralSettings;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.components.State;
-import com.intellij.openapi.components.Storage;
-import com.intellij.openapi.components.StoragePathMacros;
-import com.intellij.openapi.components.StorageScheme;
+import com.intellij.openapi.components.*;
 import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileTypes.StdFileTypes;
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.project.ProjectManager;
 import com.intellij.openapi.roots.ProjectFileIndex;
 import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.util.Comparing;
@@ -66,12 +60,9 @@
     @Storage(file = StoragePathMacros.PROJECT_CONFIG_DIR + "/encodings.xml", scheme = StorageScheme.DIRECTORY_BASED)
   }
 )
-public class EncodingProjectManagerImpl extends EncodingProjectManager {
+public class EncodingProjectManagerImpl extends EncodingProjectManager implements NamedComponent, PersistentStateComponent<Element> {
   @NonNls private static final String PROJECT_URL = "PROJECT";
   private final Project myProject;
-  private final GeneralSettings myGeneralSettings;
-  private final EditorSettingsExternalizable myEditorSettings;
-  private boolean myUseUTFGuessing = true;
   private boolean myNative2AsciiForPropertiesFiles;
   private Charset myDefaultCharsetForPropertiesFiles;
   private volatile long myModificationCount;
@@ -82,13 +73,8 @@
     }
   };
 
-  public EncodingProjectManagerImpl(Project project,
-                                    GeneralSettings generalSettings,
-                                    EditorSettingsExternalizable editorSettings,
-                                    PsiDocumentManager documentManager) {
+  public EncodingProjectManagerImpl(Project project, PsiDocumentManager documentManager) {
     myProject = project;
-    myGeneralSettings = generalSettings;
-    myEditorSettings = editorSettings;
     documentManager.addListener(new PsiDocumentManager.Listener() {
       @Override
       public void documentCreated(@NotNull Document document, PsiFile psiFile) {
@@ -122,7 +108,7 @@
       child.setAttribute("url", file == null ? PROJECT_URL : file.getUrl());
       child.setAttribute("charset", charset.name());
     }
-    element.setAttribute("useUTFGuessing", Boolean.toString(myUseUTFGuessing));
+    element.setAttribute("useUTFGuessing", Boolean.toString(true));
     element.setAttribute("native2AsciiForPropertiesFiles", Boolean.toString(myNative2AsciiForPropertiesFiles));
     if (myDefaultCharsetForPropertiesFiles != null) {
       element.setAttribute("defaultCharsetForPropertiesFiles", myDefaultCharsetForPropertiesFiles.name());
@@ -147,20 +133,9 @@
     myMapping.clear();
     myMapping.putAll(mapping);
 
-    myUseUTFGuessing = Boolean.parseBoolean(element.getAttributeValue("useUTFGuessing"));
     myNative2AsciiForPropertiesFiles = Boolean.parseBoolean(element.getAttributeValue("native2AsciiForPropertiesFiles"));
     myDefaultCharsetForPropertiesFiles = CharsetToolkit.forName(element.getAttributeValue("defaultCharsetForPropertiesFiles"));
 
-    boolean migrated = myGeneralSettings.migrateCharsetSettingsTo(this);
-    migrated |= myEditorSettings.migrateCharsetSettingsTo(this);
-    if (migrated) {
-      // load up default project only if some settings have been migrated
-      EncodingProjectManager defaultManager = getInstance(ProjectManager.getInstance().getDefaultProject());
-      if (defaultManager != null) {
-        myGeneralSettings.migrateCharsetSettingsTo(defaultManager);
-        myEditorSettings.migrateCharsetSettingsTo(defaultManager);
-      }
-    }
     myModificationCount++;
   }
 
@@ -172,26 +147,6 @@
   }
 
   @Override
-  public void initComponent() {
-
-  }
-
-  @Override
-  public void disposeComponent() {
-
-  }
-
-  @Override
-  public void projectOpened() {
-
-  }
-
-  @Override
-  public void projectClosed() {
-
-  }
-
-  @Override
   @Nullable
   public Charset getEncoding(@Nullable VirtualFile virtualFile, boolean useParentDefaults) {
     VirtualFile parent = virtualFile;
@@ -387,15 +342,11 @@
 
   @Override
   public boolean isUseUTFGuessing(final VirtualFile virtualFile) {
-    return myUseUTFGuessing;
+    return true;
   }
 
   @Override
   public void setUseUTFGuessing(final VirtualFile virtualFile, final boolean useUTFGuessing) {
-    if (myUseUTFGuessing != useUTFGuessing) {
-      myUseUTFGuessing = useUTFGuessing;
-      reloadAllFilesUnder(null);
-    }
   }
 
   private static final ThreadLocal<Boolean> SUPPRESS_RELOAD = new ThreadLocal<Boolean>();
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/ex/dummy/DummyFileSystem.java b/platform/platform-impl/src/com/intellij/openapi/vfs/ex/dummy/DummyFileSystem.java
index ee751e6..ec03da0 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/ex/dummy/DummyFileSystem.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/ex/dummy/DummyFileSystem.java
@@ -103,6 +103,7 @@
     throw new UnsupportedOperationException();
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent, @NotNull final String copyName) throws IOException {
     throw new UnsupportedOperationException();
@@ -116,6 +117,7 @@
     firePropertyChanged(requestor, vFile, VirtualFile.PROP_NAME, oldName, newName);
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
     final VirtualFileDirectoryImpl dir = (VirtualFileDirectoryImpl)vDir;
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/ex/temp/TempFileSystem.java b/platform/platform-impl/src/com/intellij/openapi/vfs/ex/temp/TempFileSystem.java
index e549fe7..1c6e173 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/ex/temp/TempFileSystem.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/ex/temp/TempFileSystem.java
@@ -87,6 +87,7 @@
     return new FakeVirtualFile(parent, dir);
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException {
     final FSItem fsItem = convert(parent);
@@ -104,6 +105,7 @@
     return new FakeVirtualFile(parent, file);
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor,
                               @NotNull VirtualFile file,
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemBase.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemBase.java
index 7665e94..7524420 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemBase.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemBase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -70,18 +70,12 @@
   }
 
   @Override
-  public void disposeComponent() {
-  }
-
-  @Override
-  public void initComponent() { }
-
-  @Override
   @NotNull
   public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile vDir, @NotNull String dirName) throws IOException {
     throw new UnsupportedOperationException();
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
     throw new UnsupportedOperationException();
@@ -97,6 +91,7 @@
     throw new UnsupportedOperationException();
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent, @NotNull final String copyName) throws IOException {
     throw new UnsupportedOperationException();
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemImpl.java
index 02a102c..9f36af3 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpFileSystemImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +16,6 @@
 package com.intellij.openapi.vfs.impl.http;
 
 import com.intellij.util.io.URLUtil;
-import org.jetbrains.annotations.NotNull;
 
 /**
  * @author nik
@@ -30,9 +29,4 @@
     return (HttpFileSystemImpl)getInstance();
   }
 
-  @Override
-  @NotNull
-  public String getComponentName() {
-    return "HttpFileSystem";
-  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpsFileSystem.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpsFileSystem.java
index e9e53fa..e1068db 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpsFileSystem.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/HttpsFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2014 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,7 +17,6 @@
 
 import com.intellij.openapi.vfs.VirtualFileManager;
 import org.jetbrains.annotations.NonNls;
-import org.jetbrains.annotations.NotNull;
 
 /**
  * @author nik
@@ -33,9 +32,4 @@
     return (HttpsFileSystem)VirtualFileManager.getInstance().getFileSystem(HTTPS_PROTOCOL);
   }
 
-  @Override
-  @NotNull
-  public String getComponentName() {
-    return "HttpsFileSystem";
-  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java
index 52a1ee2..7ca0530 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/jar/JarFileSystemImpl.java
@@ -286,6 +286,7 @@
     throw new IOException(VfsBundle.message("jar.modification.not.supported.error", vDir.getUrl()));
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
     throw new IOException(VfsBundle.message("jar.modification.not.supported.error", vDir.getUrl()));
@@ -300,6 +301,7 @@
     throw new IOException(VfsBundle.message("jar.modification.not.supported.error", vFile.getUrl()));
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent, @NotNull String copyName) throws IOException {
     throw new IOException(VfsBundle.message("jar.modification.not.supported.error", vFile.getUrl()));
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java
index 59023d3..3feb74d 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/local/LocalFileSystemBase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -396,6 +396,7 @@
     return new FakeVirtualFile(parent, dir);
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(final Object requestor, @NotNull final VirtualFile parent, @NotNull final String file) throws IOException {
     final File ioFile = new File(convertToIOFile(parent), file);
@@ -524,6 +525,7 @@
     });
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(final Object requestor,
                               @NotNull final VirtualFile vFile,
@@ -640,6 +642,7 @@
     return true;
   }
 
+  @NotNull
   @Override
   public String getCanonicallyCasedName(@NotNull final VirtualFile file) {
     if (isCaseSensitive()) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
index 8044cfe..6cff8a6 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/newvfs/persistent/PersistentFSImpl.java
@@ -416,6 +416,7 @@
     return len;
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor, @NotNull VirtualFile file, @NotNull VirtualFile parent, @NotNull String name) throws IOException {
     getDelegate(file).copyFile(requestor, file, parent, name);
@@ -428,6 +429,7 @@
     return child;
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildDirectory(Object requestor, @NotNull VirtualFile parent, @NotNull String dir) throws IOException {
     getDelegate(parent).createChildDirectory(requestor, parent, dir);
@@ -440,6 +442,7 @@
     return child;
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile parent, @NotNull String file) throws IOException {
     getDelegate(parent).createChildFile(requestor, parent, file);
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java
index b66fcf4..58f315f 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/FocusManagerImpl.java
@@ -363,21 +363,23 @@
       return true;
     }
 
-    boolean doNotExecuteBecauseAppIsInactive =
-      !myApp.isActive() && !canExecuteOnInactiveApplication(cmd) && Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive");
+    if (!Registry.is("focus.fix.lost.cursor")) {
+      boolean doNotExecuteBecauseAppIsInactive =
+        !myApp.isActive() && !canExecuteOnInactiveApplication(cmd) && Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive");
 
-    if (doNotExecuteBecauseAppIsInactive) {
-      if (myCallbackOnActivation != null) {
-        myCallbackOnActivation.setRejected();
-        if (myFocusCommandOnAppActivation != null) {
-          resetCommand(myFocusCommandOnAppActivation, true);
+      if (doNotExecuteBecauseAppIsInactive) {
+        if (myCallbackOnActivation != null) {
+          myCallbackOnActivation.setRejected();
+          if (myFocusCommandOnAppActivation != null) {
+            resetCommand(myFocusCommandOnAppActivation, true);
+          }
         }
+
+        myFocusCommandOnAppActivation = cmd;
+        myCallbackOnActivation = result;
+
+        return true;
       }
-
-      myFocusCommandOnAppActivation = cmd;
-      myCallbackOnActivation = result;
-
-      return true;
     }
 
     return false;
@@ -1152,6 +1154,7 @@
 
   @Override
   public boolean isFocusTransferEnabled() {
+    if (Registry.is("focus.fix.lost.cursor")) return true;
     return myApp.isActive() || !Registry.is("actionSystem.suspendFocusTransferIfApplicationInactive");
   }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java
index 33e0a84..a782ee1 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeFrameImpl.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.openapi.wm.impl;
 
+import com.apple.eawt.AppEvent;
 import com.intellij.diagnostic.IdeMessagePanel;
 import com.intellij.ide.AppLifecycleListener;
 import com.intellij.ide.DataManager;
@@ -52,6 +53,7 @@
 import com.intellij.openapi.wm.impl.status.*;
 import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeFrame;
 import com.intellij.ui.*;
+import com.intellij.ui.mac.MacMainFrameDecorator;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -63,6 +65,10 @@
 import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 import java.io.File;
+import java.lang.reflect.InvocationTargetException;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 /**
  * @author Anton Katilin
@@ -455,6 +461,14 @@
   }
 
   public void dispose() {
+    if (SystemInfo.isMac && isInFullScreen()) {
+      ((MacMainFrameDecorator)myFrameDecorator).exitFullScreenAndDispose();
+    } else {
+      disposeImpl();
+    }
+  }
+
+  public void disposeImpl() {
     if (isTemporaryDisposed()) {
       super.dispose();
       return;
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java
index bb62139..09395f5 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/LibraryDependentToolWindowManager.java
@@ -9,9 +9,9 @@
 import com.intellij.openapi.roots.ModuleRootEvent;
 import com.intellij.openapi.roots.ModuleRootListener;
 import com.intellij.openapi.startup.StartupManager;
-import com.intellij.openapi.wm.ext.LibraryDependentToolWindow;
 import com.intellij.openapi.wm.ToolWindow;
 import com.intellij.openapi.wm.ex.ToolWindowManagerEx;
+import com.intellij.openapi.wm.ext.LibraryDependentToolWindow;
 import com.intellij.psi.PsiManager;
 import com.intellij.util.messages.MessageBusConnection;
 
@@ -28,11 +28,7 @@
   public void projectOpened() {
     final ModuleRootListener rootListener = new ModuleRootAdapter() {
       public void rootsChanged(ModuleRootEvent event) {
-        DumbService.getInstance(myProject).smartInvokeLater(new Runnable() {
-          public void run() {
-            checkToolWindowStatuses();
-          }
-        });
+        checkToolWindowStatuses();
       }
     };
 
@@ -54,16 +50,21 @@
       return;
     }
 
-    for (LibraryDependentToolWindow libraryToolWindow : Extensions.getExtensions(LibraryDependentToolWindow.EXTENSION_POINT_NAME)) {
-       if (libraryToolWindow.getLibrarySearchHelper().isLibraryExists(myProject)) {
-           ensureToolWindowExists(libraryToolWindow);
-       } else {
-         ToolWindow toolWindow = myToolWindowManager.getToolWindow(libraryToolWindow.id);
-         if (toolWindow != null) {
-           myToolWindowManager.unregisterToolWindow(libraryToolWindow.id);
-         }
-       }
-    }
+    DumbService.getInstance(myProject).smartInvokeLater(new Runnable() {
+      public void run() {
+        for (LibraryDependentToolWindow libraryToolWindow : Extensions.getExtensions(LibraryDependentToolWindow.EXTENSION_POINT_NAME)) {
+          if (libraryToolWindow.getLibrarySearchHelper().isLibraryExists(myProject)) {
+            ensureToolWindowExists(libraryToolWindow);
+          }
+          else {
+            ToolWindow toolWindow = myToolWindowManager.getToolWindow(libraryToolWindow.id);
+            if (toolWindow != null) {
+              myToolWindowManager.unregisterToolWindow(libraryToolWindow.id);
+            }
+          }
+        }
+      }
+    });
   }
 
   private void ensureToolWindowExists(LibraryDependentToolWindow extension) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButton.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButton.java
index 8f9a4ac..7d534d5 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButton.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButton.java
@@ -174,7 +174,7 @@
   }
 
   private void processDrag(final MouseEvent e) {
-    if (myDragCancelled) return;
+    if (myDragCancelled || !MouseDragHelper.checkModifiers(e)) return;
     if (!isDraggingNow()) {
       if (myPressedPoint == null) return;
       if (isWithinDeadZone(e)) return;
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 413386b..b2fc056 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
@@ -16,7 +16,6 @@
 package com.intellij.openapi.wm.impl;
 
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.TaskInfo;
 import com.intellij.openapi.project.Project;
@@ -45,7 +44,7 @@
  * @author Anton Katilin
  * @author Vladimir Kondratyev
  */
-public final class TestWindowManager extends WindowManagerEx implements ApplicationComponent{
+public final class TestWindowManager extends WindowManagerEx {
   private static final StatusBarEx ourStatusBar = new DummyStatusBar();
 
   public final void doNotSuggestAsParent(final Window window) { }
@@ -339,18 +338,6 @@
   public void adjustContainerWindow(Component c, Dimension oldSize, Dimension newSize) { }
 
   @Override
-  @NotNull
-  public final String getComponentName() {
-    return "TestWindowManager";
-  }
-
-  @Override
-  public final void initComponent() { }
-
-  @Override
-  public final void disposeComponent() { }
-
-  @Override
   public void addListener(final WindowManagerListener listener) { }
 
   @Override
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java
index 36012ed..1913175 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/WindowManagerImpl.java
@@ -69,7 +69,7 @@
   name = "WindowManager",
   roamingType = RoamingType.GLOBAL,
   storages = {@Storage(file = StoragePathMacros.APP_CONFIG + "/window.manager.xml")})
-public final class WindowManagerImpl extends WindowManagerEx implements ApplicationComponent, PersistentStateComponent<Element> {
+public final class WindowManagerImpl extends WindowManagerEx implements NamedComponent, PersistentStateComponent<Element> {
   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.wm.impl.WindowManagerImpl");
 
   @NonNls public static final String FULL_SCREEN = "ide.frame.full.screen";
@@ -405,13 +405,6 @@
   }
 
   @Override
-  public final void disposeComponent() {}
-
-  @Override
-  public final void initComponent() {
-  }
-
-  @Override
   public final void doNotSuggestAsParent(final Window window) {
     myWindowWatcher.doNotSuggestAsParent(window);
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java
index 237ac63..d58d3b9 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/commands/RequestFocusInToolWindowCmd.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -44,7 +44,6 @@
   private final FocusWatcher myFocusWatcher;
 
   private final boolean myForced;
-  private final IdeFocusManager myFocusManager;
   private final Expirable myTimestamp;
 
   public RequestFocusInToolWindowCmd(IdeFocusManager focusManager, final ToolWindowImpl toolWindow, final FocusWatcher focusWatcher, final Runnable finishCallBack, boolean forced) {
@@ -52,13 +51,14 @@
     myToolWindow = toolWindow;
     myFocusWatcher = focusWatcher;
     myForced = forced;
-    myFocusManager = focusManager;
 
-    myTimestamp = myFocusManager.getTimestamp(true);
+    myTimestamp = focusManager.getTimestamp(true);
   }
 
+  @Override
   public final void run() {
     myToolWindow.getActivation().doWhenDone(new Runnable() {
+      @Override
       public void run() {
         processRequestFocus();
       }
@@ -103,6 +103,7 @@
       // Try to focus component which is preferred one for the tool window
       if (preferredFocusedComponent != null) {
         requestFocus(preferredFocusedComponent).doWhenDone(new Runnable() {
+          @Override
           public void run() {
             bringOwnerToFront();
           }
@@ -112,6 +113,7 @@
         // If there is no preferred component then try to focus tool window itself
         final JComponent componentToFocus = myToolWindow.getComponent();
         requestFocus(componentToFocus).doWhenDone(new Runnable() {
+          @Override
           public void run() {
             bringOwnerToFront();
           }
@@ -143,7 +145,7 @@
     // isn't active.
     if (owner != null && owner.getFocusOwner() == null) {
       final Window activeWindow = getActiveWindow(owner.getOwnedWindows());
-      if (activeWindow == null || (activeWindow instanceof FloatingDecorator)) {
+      if (activeWindow == null || activeWindow instanceof FloatingDecorator) {
         LOG.debug("owner.toFront()");
         //Thread.dumpStack();
         //System.out.println("------------------------------------------------------");
@@ -153,23 +155,29 @@
   }
 
 
-  private ActionCallback requestFocus(final Component c) {
+  @NotNull
+  private ActionCallback requestFocus(@NotNull final Component c) {
     final ActionCallback result = new ActionCallback();
     final Alarm checkerAlarm = new Alarm(result);
     Runnable checker = new Runnable() {
       final long startTime = System.currentTimeMillis();
       @Override
       public void run() {
-        if (System.currentTimeMillis() - startTime > 10000) return;
+        if (System.currentTimeMillis() - startTime > 10000) {
+          result.setRejected();
+          return;
+        }
         if (c.isShowing()) {
           final Component owner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getPermanentFocusOwner();
           if (owner != null && owner == c) {
             myManager.getFocusManager().requestFocus(new FocusCommand() {
+              @Override
               @NotNull
               public ActionCallback run() {
                 return new ActionCallback.Done();
               }
             }, myForced).doWhenProcessed(new Runnable() {
+              @Override
               public void run() {
                 updateToolWindow(c);
               }
@@ -178,6 +186,7 @@
           else {
             myManager.getFocusManager().requestFocus(new FocusCommand.ByComponent(c, myToolWindow.getComponent()), myForced)
               .doWhenProcessed(new Runnable() {
+                @Override
                 public void run() {
                   updateToolWindow(c);
                 }
@@ -204,7 +213,7 @@
     updateFocusedComponentForWatcher(c);
   }
 
-  private void updateFocusedComponentForWatcher(final Component c) {
+  private static void updateFocusedComponentForWatcher(final Component c) {
     final WindowWatcher watcher = ((WindowManagerImpl)WindowManager.getInstance()).getWindowWatcher();
     final FocusWatcher focusWatcher = watcher.getFocusWatcherFor(c);
     if (focusWatcher != null && c.isFocusOwner()) {
@@ -216,9 +225,8 @@
    * @return first active window from hierarchy with specified roots. Returns <code>null</code>
    *         if there is no active window in the hierarchy.
    */
-  private Window getActiveWindow(final Window[] windows) {
-    for (int i = 0; i < windows.length; i++) {
-      Window window = windows[i];
+  private static Window getActiveWindow(final Window[] windows) {
+    for (Window window : windows) {
       if (window.isShowing() && window.isActive()) {
         return window;
       }
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 27a476b..065e768 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
@@ -15,12 +15,14 @@
  */
 package com.intellij.openapi.wm.impl.status;
 
+import com.intellij.ide.ui.UISettings;
 import com.intellij.idea.ActionsBundle;
 import com.intellij.notification.EventLog;
 import com.intellij.openapi.actionSystem.ActionGroup;
 import com.intellij.openapi.actionSystem.ActionManager;
 import com.intellij.openapi.actionSystem.ActionPlaces;
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.editor.impl.EditorComponentImpl;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.TaskInfo;
 import com.intellij.openapi.ui.MessageType;
@@ -34,6 +36,7 @@
 import com.intellij.openapi.wm.StatusBar;
 import com.intellij.openapi.wm.StatusBarWidget;
 import com.intellij.openapi.wm.ex.ProgressIndicatorEx;
+import com.intellij.ui.Gray;
 import com.intellij.ui.awt.RelativePoint;
 import com.intellij.ui.components.labels.LinkLabel;
 import com.intellij.ui.components.labels.LinkListener;
@@ -342,7 +345,7 @@
     repaint();
   }
 
-  private void buildInInlineIndicator(@NotNull InlineProgressIndicator inline) {
+  private void buildInInlineIndicator(@NotNull final InlineProgressIndicator inline) {
     removeAll();
     setLayout(new InlineLayout());
     add(myRefreshAndInfoPanel);
@@ -364,6 +367,46 @@
 
     myRefreshAndInfoPanel.revalidate();
     myRefreshAndInfoPanel.repaint();
+
+    if (UISettings.getInstance().PRESENTATION_MODE) {
+      final JRootPane pane = myInfoPanel.getRootPane();
+      final RelativePoint point = new RelativePoint(pane, new Point(pane.getWidth() - 250, 60));
+      final PresentationModeProgressPanel panel = new PresentationModeProgressPanel(inline);
+      final MyInlineProgressIndicator delegate = new MyInlineProgressIndicator(true, inline.getInfo(), inline) {
+        @Override
+        protected void updateProgress() {
+          super.updateProgress();
+          panel.update();
+        }
+      };
+
+      Disposer.register(inline, delegate);
+
+      JBPopupFactory.getInstance().createBalloonBuilder(panel.getRootPanel())
+        .setFadeoutTime(0)
+        .setFillColor(Gray.TRANSPARENT)
+        .setShowCallout(false)
+        .setBorderColor(Gray.TRANSPARENT)
+        .setBorderInsets(new Insets(0, 0, 0, 0))
+        .setAnimationCycle(0)
+        .setCloseButtonEnabled(false)
+        .setHideOnClickOutside(false)
+        .setDisposable(inline)
+        .setHideOnFrameResize(false)
+        .setHideOnKeyOutside(false)
+        .setBlockClicksThroughBalloon(true)
+        .setHideOnAction(false)
+        .createBalloon().show(new PositionTracker<Balloon>(pane) {
+        @Override
+        public RelativePoint recalculateLocation(Balloon object) {
+          final EditorComponentImpl editorComponent = UIUtil.findComponentOfType(pane, EditorComponentImpl.class);
+          if (editorComponent != null) {
+            return new RelativePoint(editorComponent.getParent().getParent(), new Point(editorComponent.getParent().getParent().getWidth() - 150, editorComponent.getParent().getParent().getHeight() - 70));
+          }
+          return point;
+        }
+      }, Balloon.Position.above);
+    }
   }
 
   public Pair<String, String> setText(@Nullable final String text, @Nullable final String requestor) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PresentationModeProgressPanel.form b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PresentationModeProgressPanel.form
new file mode 100644
index 0000000..2e1bb76
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PresentationModeProgressPanel.form
@@ -0,0 +1,67 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="com.intellij.openapi.wm.impl.status.PresentationModeProgressPanel">
+  <grid id="27dc6" binding="myRootPanel" custom-create="true" layout-manager="GridLayoutManager" row-count="4" column-count="2" 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="94"/>
+    </constraints>
+    <properties>
+      <maximumSize width="250" height="60"/>
+      <minimumSize width="250" height="60"/>
+      <opaque value="false"/>
+      <preferredSize width="250" height="60"/>
+    </properties>
+    <border type="none"/>
+    <children>
+      <component id="21ac6" class="javax.swing.JLabel" binding="myText">
+        <constraints>
+          <grid row="0" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false">
+            <preferred-size width="225" height="-1"/>
+            <maximum-size width="225" height="-1"/>
+          </grid>
+        </constraints>
+        <properties>
+          <autoscrolls value="true"/>
+          <text value="Text"/>
+        </properties>
+      </component>
+      <component id="94f42" class="javax.swing.JProgressBar" binding="myProgressBar" default-binding="true">
+        <constraints>
+          <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="7" anchor="8" fill="0" indent="0" use-parent-layout="false">
+            <minimum-size width="225" height="-1"/>
+            <preferred-size width="225" height="-1"/>
+            <maximum-size width="225" height="-1"/>
+          </grid>
+        </constraints>
+        <properties>
+          <indeterminate value="true"/>
+          <opaque value="false"/>
+        </properties>
+      </component>
+      <component id="38c03" class="com.intellij.ui.InplaceButton" binding="myCancelButton" custom-create="true">
+        <constraints>
+          <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+        </constraints>
+        <properties>
+          <opaque value="false"/>
+        </properties>
+      </component>
+      <component id="34af0" class="javax.swing.JLabel" binding="myText2">
+        <constraints>
+          <grid row="2" column="0" row-span="1" col-span="2" vsize-policy="0" hsize-policy="0" anchor="8" fill="0" indent="0" use-parent-layout="false">
+            <preferred-size width="225" height="-1"/>
+            <maximum-size width="225" height="-1"/>
+          </grid>
+        </constraints>
+        <properties>
+          <text value="Text 2"/>
+        </properties>
+      </component>
+      <vspacer id="8e674">
+        <constraints>
+          <grid row="3" column="1" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
+        </constraints>
+      </vspacer>
+    </children>
+  </grid>
+</form>
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PresentationModeProgressPanel.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PresentationModeProgressPanel.java
new file mode 100644
index 0000000..d7bc702
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/PresentationModeProgressPanel.java
@@ -0,0 +1,91 @@
+/*
+ * Copyright 2000-2014 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.openapi.ui.popup.IconButton;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.ui.InplaceButton;
+import com.intellij.ui.TransparentPanel;
+import com.intellij.util.ui.EmptyIcon;
+import com.intellij.util.ui.UIUtil;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.event.ActionEvent;
+import java.awt.event.ActionListener;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class PresentationModeProgressPanel {
+  private final InlineProgressIndicator myProgress;
+  private JLabel myText;
+  private JProgressBar myProgressBar;
+  private InplaceButton myCancelButton;
+  private JLabel myText2;
+  private JPanel myRootPanel;
+
+  public PresentationModeProgressPanel(InlineProgressIndicator progress) {
+    myProgress = progress;
+    final Font font = UIUtil.getLabelFont().deriveFont(11f);
+    myText.setFont(font);
+    myText2.setFont(font);
+    myText.setIcon(EmptyIcon.create(1, 16));
+    myText2.setIcon(EmptyIcon.create(1, 16));
+  }
+  public void update() {
+    UIUtil.invokeLaterIfNeeded(new Runnable() {
+      @Override
+      public void run() {
+        updateImpl();
+      }
+    });
+  }
+
+  private void updateImpl() {
+    if (!StringUtil.equals(myText.getText(), myProgress.getText())) {
+      myText.setText(myProgress.getText());
+    }
+    if (!StringUtil.equals(myText2.getText(), myProgress.getText2())) {
+      myText2.setText(myProgress.getText2());
+    }
+    if ((myProgress.isIndeterminate() || myProgress.getFraction() == 0.0) != myProgressBar.isIndeterminate()) {
+      myProgressBar.setIndeterminate(myProgress.isIndeterminate() || myProgress.getFraction() == 0.0);
+      myProgressBar.revalidate();
+    }
+
+    if (!myProgressBar.isIndeterminate()) {
+      myProgressBar.setValue(((int)(myProgress.getFraction() * 99)) + 1);
+    }
+  }
+
+  public JPanel getRootPanel() {
+    return myRootPanel;
+  }
+
+  private void createUIComponents() {
+    myRootPanel = new TransparentPanel(0.5f);
+    final IconButton iconButton = new IconButton(myProgress.getInfo().getCancelTooltipText(),
+                                                 AllIcons.Process.Stop,
+                                                 AllIcons.Process.StopHovered);
+    myCancelButton = new InplaceButton(iconButton, new ActionListener() {
+      public void actionPerformed(final ActionEvent e) {
+        myProgress.cancel();
+      }
+    }).setFillBg(false);
+  }
+}
diff --git a/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java b/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java
index 67d4477..4ffac2c 100644
--- a/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java
+++ b/platform/platform-impl/src/com/intellij/platform/PlatformProjectOpenProcessor.java
@@ -27,9 +27,9 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.project.ProjectManager;
 import com.intellij.openapi.project.ex.ProjectManagerEx;
+import com.intellij.openapi.roots.ContentEntry;
 import com.intellij.openapi.roots.ModifiableRootModel;
 import com.intellij.openapi.roots.ModuleRootManager;
-import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.startup.StartupManager;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.util.Disposer;
@@ -199,6 +199,8 @@
         @Override
         public void run() {
           ModifiableRootModel model = ModuleRootManager.getInstance(module).getModifiableModel();
+          ContentEntry[] entries = model.getContentEntries();
+          if (entries.length == 1) model.removeContentEntry(entries[0]); // remove custom content entry created for temp directory
           model.addContentEntry(virtualFile);
           model.commit();
         }
diff --git a/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java b/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java
index d5f867c..23bb7cf 100644
--- a/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java
+++ b/platform/platform-impl/src/com/intellij/remote/VagrantBasedCredentialsHolder.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.remote;
 
+import com.intellij.openapi.util.text.StringUtil;
 import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
 
@@ -32,7 +33,7 @@
     myVagrantFolder = folder;
   }
 
-  public void setVagrantFolder(String vagrantFolder) {
+  public void setVagrantFolder(@NotNull String vagrantFolder) {
     myVagrantFolder = vagrantFolder;
   }
 
@@ -42,7 +43,7 @@
   }
 
   public void load(Element element) {
-    setVagrantFolder(element.getAttributeValue(VAGRANT_FOLDER));
+    setVagrantFolder(StringUtil.notNullize(element.getAttributeValue(VAGRANT_FOLDER)));
   }
 
   public void save(Element element) {
diff --git a/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java b/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java
index a1b0f88..5f8fa4b 100644
--- a/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java
+++ b/platform/platform-impl/src/com/intellij/remote/VagrantSupport.java
@@ -40,7 +40,7 @@
   public abstract Pair<String, RemoteCredentials> getVagrantSettings(Project project);
 
   @NotNull
-  public abstract RemoteCredentials getVagrantSettings(Project project, String vagrantFolder);
+  public abstract RemoteCredentials getVagrantSettings(@NotNull Project project, String vagrantFolder);
 
   @NotNull
   public abstract RemoteCredentials getCredentials(@NotNull String folder) throws IOException;
@@ -55,7 +55,7 @@
     });
   }
 
-  public abstract void checkVagrantAndRunIfDown(String folder);
+  public abstract boolean checkVagrantAndRunIfDown(String folder);
 
   public abstract Collection<? extends RemoteConnector> getVagrantInstancesConnectors(@NotNull Project project);
 
diff --git a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java
index d22fa19..9ad0931 100644
--- a/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java
+++ b/platform/platform-impl/src/com/intellij/ui/FocusTrackback.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.ui.popup.JBPopup;
 import com.intellij.openapi.util.ActionCallback;
 import com.intellij.openapi.util.ExpirableRunnable;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.wm.FocusCommand;
 import com.intellij.openapi.wm.IdeFocusManager;
 import com.intellij.openapi.wm.ex.LayoutFocusTraversalPolicyExt;
@@ -452,7 +453,8 @@
   }
 
   public void cleanParentWindow() {
-    if (myParentWindow != null) {
+    if (!Registry.is("focus.fix.lost.cursor")) return;
+      if (myParentWindow != null) {
       try {
         Method tmpLost = Window.class.getDeclaredMethod("setTemporaryLostComponent", Component.class);
         tmpLost.setAccessible(true);
diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java
index 64d904d..dcb514f 100644
--- a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java
+++ b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.ActionCallback;
 import com.intellij.openapi.util.BuildNumber;
+import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.wm.impl.IdeFrameDecorator;
 import com.intellij.openapi.wm.impl.IdeFrameImpl;
@@ -47,6 +48,9 @@
 import java.util.EventListener;
 import java.util.LinkedList;
 import java.util.concurrent.atomic.AtomicInteger;
+import java.util.concurrent.locks.Condition;
+import java.util.concurrent.locks.Lock;
+import java.util.concurrent.locks.ReentrantLock;
 
 import static com.intellij.ui.mac.foundation.Foundation.invoke;
 
@@ -378,17 +382,38 @@
       @Override
       public void run() {
         try {
-            requestToggleFullScreenMethod.invoke(Application.getApplication(),myFrame);
-          }
-          catch (IllegalAccessException e) {
-            LOG.error(e);
-          }
-          catch (InvocationTargetException e) {
-            LOG.error(e);
-          }
+          requestToggleFullScreenMethod.invoke(Application.getApplication(),myFrame);
+        }
+        catch (IllegalAccessException e) {
+          LOG.error(e);
+        }
+        catch (InvocationTargetException e) {
+          LOG.error(e);
+        }
       }
     });
     return callback;
   }
 
+  public void exitFullScreenAndDispose() {
+
+    LOG.assertTrue(isInFullScreen());
+    try {
+      requestToggleFullScreenMethod.invoke(Application.getApplication(), myFrame);
+    }
+    catch (IllegalAccessException e) {
+      LOG.error(e);
+    }
+    catch (InvocationTargetException e) {
+      LOG.error(e);
+    }
+
+    myDispatcher.addListener(new FSAdapter() {
+      @Override
+      public void windowExitedFullScreen(AppEvent.FullScreenEvent event) {
+        myFrame.disposeImpl();
+        myDispatcher.removeListener(this);
+      }
+    });
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java b/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java
index 8e097b2..f41e603 100755
--- a/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java
+++ b/platform/platform-impl/src/com/intellij/ui/messages/SheetMessage.java
@@ -20,6 +20,7 @@
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.util.SystemInfo;
+import com.intellij.ui.Gray;
 import com.intellij.ui.JBColor;
 import com.intellij.ui.mac.MacMainFrameDecorator;
 import com.intellij.util.ui.Animator;
@@ -73,7 +74,7 @@
     myParent = owner;
 
     myWindow.setUndecorated(true);
-    myWindow.setBackground(new JBColor(new Color(0, 0, 0, 0), new Color(0, 0, 0, 0)));
+    myWindow.setBackground(Gray.TRANSPARENT);
     myController = new SheetController(this, title, message, icon, buttons, defaultButton, doNotAskOption, focusedButton);
 
     imageHeight = 0;
diff --git a/platform/platform-resources-en/src/messages/ApplicationBundle.properties b/platform/platform-resources-en/src/messages/ApplicationBundle.properties
index 56e8293..beaf269 100644
--- a/platform/platform-resources-en/src/messages/ApplicationBundle.properties
+++ b/platform/platform-resources-en/src/messages/ApplicationBundle.properties
@@ -634,6 +634,5 @@
 checkbox.reformat.on.typing.rbrace=Reformat block on typing '}'
 
 group.richcopy=Rich-text copy
-checkbox.richcopy.strip.whitespace.at.line.start=Strip common indent
 combobox.richcopy.color.scheme=Color scheme
 combobox.richcopy.color.scheme.active=Active scheme
diff --git a/platform/platform-resources-en/src/messages/CodeInsightBundle.properties b/platform/platform-resources-en/src/messages/CodeInsightBundle.properties
index b7a94b2..6ef2d15 100644
--- a/platform/platform-resources-en/src/messages/CodeInsightBundle.properties
+++ b/platform/platform-resources-en/src/messages/CodeInsightBundle.properties
@@ -286,7 +286,6 @@
 dialog.add.live.template.title=Add Live Template
 templates.no.defined=No templates defined in this context
 templates.surround.no.defined=No surround templates defined in this context
-templates.no.defined.with.prefix=No templates starting with ''{0}'' defined in this context
 templates.settings.page.title=Live Templates
 templates.select.template.chooser.title=Select Template
 templates.export.display.name=Live templates
diff --git a/platform/platform-resources-en/src/messages/InspectionsBundle.properties b/platform/platform-resources-en/src/messages/InspectionsBundle.properties
index 191cc7f..b9d5b98 100644
--- a/platform/platform-resources-en/src/messages/InspectionsBundle.properties
+++ b/platform/platform-resources-en/src/messages/InspectionsBundle.properties
@@ -633,6 +633,11 @@
 inconsistent.bundle.report.missing.translations=Report &missing translations
 inconsistent.bundle.report.inconsistent.properties=Report &inconsistent properties
 inconsistent.bundle.report.duplicate.properties.values=Report properties &overridden with the same value
+inconsistent.bundle.report.inconsistent.properties.placeholders=Report properties with inconsistent &placeholders
+inconsistent.bundle.report.inconsistent.properties.ends=Report properties with inconsistent &ends
+inconsistent.bundle.property.inconsistent.placeholders=Inconsistent count of placeholders: found {0} in ''{1}''
+inconsistent.bundle.property.inconsistent.end.parent.end.from.check.symbols=Inconsistent property value end ''{0}'' but found ''{1}'' in ''{2}''
+inconsistent.bundle.property.inconsistent.end=Inconsistent property value end '{0}'
 inconsistent.bundle.property.inherited.with.the.same.value=Property inherited from the ''{0}'' file with the same value
 edit.inspection.options=Edit ''{0}'' Options
 offline.view.title=Offline View
diff --git a/platform/platform-resources-en/src/misc/registry.properties b/platform/platform-resources-en/src/misc/registry.properties
index 2106fa1..b666adc 100644
--- a/platform/platform-resources-en/src/misc/registry.properties
+++ b/platform/platform-resources-en/src/misc/registry.properties
@@ -262,6 +262,9 @@
 ide.non.english.keyboard.layout.fix=false
 ide.non.english.keyboard.layout.fix.description=Enables a fix for key codes with non-English keyboard layouts
 
+ide.dfa.getters.with.side.effects=java\\.nio\\..*ByteBuffer\\.get.*
+ide.dfa.getters.with.side.effects.description=A regex on qualified names of methods that look like getters but are not. For Constant Conditions & Exception inspection
+
 ide.enable.toolwindow.stack=false
 
 change.signature.awesome.mode=true
@@ -385,5 +388,9 @@
 editor.richcopy.enable=true
 editor.richcopy.debug=false
 editor.richcopy.max.size.megabytes=10
+editor.richcopy.strip.indents=true
 allow.dialog.based.popups=false
 allow.dialog.based.popups.description=Allows to use a JDialog as popup toplevel
+
+focus.fix.lost.cursor=true
+focus.fix.lost.cursor.description=See IDEA-79312
diff --git a/platform/platform-resources/src/META-INF/LangExtensions.xml b/platform/platform-resources/src/META-INF/LangExtensions.xml
index a174ffc..ec1ee6d 100644
--- a/platform/platform-resources/src/META-INF/LangExtensions.xml
+++ b/platform/platform-resources/src/META-INF/LangExtensions.xml
@@ -452,7 +452,7 @@
     <internalFileTemplate name="Html5"/>
     <internalFileTemplate name="Xhtml"/>
     <fileBasedIndex implementation="com.intellij.psi.impl.cache.impl.todo.TodoIndex"/>
-    <fileBasedIndex implementation="com.intellij.psi.impl.cache.impl.id.IdIndex"/>
+    <fileBasedIndex implementation="com.intellij.psi.impl.cache.impl.id.IdIndexImpl"/>
     <fileBasedIndex implementation="com.intellij.psi.search.FilenameIndex"/>
     <fileBasedIndex implementation="com.intellij.psi.search.FileTypeIndex"/>
     <fileBasedIndex implementation="com.intellij.psi.stubs.StubUpdatingIndex"/>
@@ -881,9 +881,13 @@
 
     <virtualFileSystem key="scratchpad" implementationClass="com.intellij.ide.scratch.ScratchpadFileSystem"/>
 
+    <applicationService serviceImplementation="com.intellij.openapi.editor.richcopy.settings.RichCopySettings"/>
     <copyPastePostProcessor implementation="com.intellij.openapi.editor.richcopy.TextWithMarkupProcessor"/>
     <copyPastePostProcessor implementation="com.intellij.openapi.editor.richcopy.RtfCopyPasteProcessor"/>
     <copyPastePostProcessor implementation="com.intellij.openapi.editor.richcopy.HtmlCopyPasteProcessor"/>
+     <!--the following bindings use 'first' order to make sure they capture raw text before any other processor modifies it -->
+    <copyPastePreProcessor implementation="com.intellij.openapi.editor.richcopy.RtfCopyPasteProcessor$RawTextSetter" order="first" id="richcopy-rtf"/>
+    <copyPastePreProcessor implementation="com.intellij.openapi.editor.richcopy.HtmlCopyPasteProcessor$RawTextSetter" order="first" id="richcopy-html"/>
   </extensions>
 </idea-plugin>
 
diff --git a/platform/platform-resources/src/componentSets/Lang.xml b/platform/platform-resources/src/componentSets/Lang.xml
index 403a219..dc2fabf 100644
--- a/platform/platform-resources/src/componentSets/Lang.xml
+++ b/platform/platform-resources/src/componentSets/Lang.xml
@@ -37,10 +37,6 @@
     <component>
       <implementation-class>com.intellij.codeInsight.preview.ImageOrColorPreviewManager</implementation-class>
     </component>
-
-    <component>
-      <implementation-class>com.intellij.openapi.editor.richcopy.settings.RichCopySettings</implementation-class>
-    </component>
   </application-components>
 
   <project-components>
diff --git a/platform/platform-resources/src/idea/Keymap_Xcode.xml b/platform/platform-resources/src/idea/Keymap_Xcode.xml
index 9a4dafd..0b5bf40 100644
--- a/platform/platform-resources/src/idea/Keymap_Xcode.xml
+++ b/platform/platform-resources/src/idea/Keymap_Xcode.xml
@@ -1,19 +1,20 @@
 <component>
   <keymap version="1" name="Xcode" parent="Mac OS X 10.5+">
     <action id="ActivateHierarchyToolWindow"/>
+    <action id="ActivateTODOToolWindow"/>
     <action id="ActivateFavoritesToolWindow">
       <keyboard-shortcut first-keystroke="meta 0"/>
     </action>
     <action id="ActivateProjectToolWindow">
       <keyboard-shortcut first-keystroke="meta 1"/>
     </action>
-x    <action id="ActivateStructureToolWindow">
+    <action id="ActivateStructureToolWindow">
       <keyboard-shortcut first-keystroke="meta 2" />
     </action>
     <action id="ActivateFindToolWindow">
       <keyboard-shortcut first-keystroke="meta 3" />
     </action>
-    <action id="ActivateTODOToolWindow">
+    <action id="ActivateMessagesToolWindow">
       <keyboard-shortcut first-keystroke="meta 4"/>
     </action>
     <action id="ActivateRunToolWindow">
@@ -23,8 +24,8 @@
       <keyboard-shortcut first-keystroke="meta shift Y" />
       <keyboard-shortcut first-keystroke="meta 6" />
     </action>
-    <action id="ActivateMessagesToolWindow">
-      <keyboard-shortcut first-keystroke="meta 8" />
+    <action id="ActivateChangesToolWindow">
+      <keyboard-shortcut first-keystroke="meta 9" />
     </action>
     <action id="FileStructurePopup">
       <keyboard-shortcut first-keystroke="control 6"/>
diff --git a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEnd-after.txt b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEnd-after.txt
index 59aa5d7..0e8f561 100644
--- a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEnd-after.txt
+++ b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEnd-after.txt
@@ -1,2 +1,2 @@
-s<caret>text<caret>o<selection>t<caret></selection> text
-an<caret> l<caret>yet a<selection>not<caret></selection> line
\ No newline at end of file
+s<caret>text<caret>o<caret>r text
+an<caret>er l<caret>yet a<caret>her line
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEndInDifferentHumpsMode-after.txt b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEndInDifferentHumpsMode-after.txt
index 74c13ea..1b3f82a 100644
--- a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEndInDifferentHumpsMode-after.txt
+++ b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordEndInDifferentHumpsMode-after.txt
@@ -1,2 +1,2 @@
-Ab<caret>Dabra<caret>Hum<selection><caret>D</selection>ump Hu<selection>mpDu<caret></selection>
-<selection>YetAnot<caret>HumpedWord</selection>
\ No newline at end of file
+Ab<caret>Dabra<caret>Hum<caret>ump Hu<caret>mp
+<caret>
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStart-after.txt b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStart-after.txt
index 7c5d3fc..b66dd51 100644
--- a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStart-after.txt
+++ b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStart-after.txt
@@ -1,3 +1,3 @@
 <caret>some <caret>t
-<caret>ther <caret>t
-<caret>other line<caret>yet another line
\ No newline at end of file
+o<caret>er t<caret>t
+<caret> line<caret>yet another line
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStartInDifferentHumpsMode-after.txt b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStartInDifferentHumpsMode-after.txt
index eefa20b..33dc0f7 100644
--- a/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStartInDifferentHumpsMode-after.txt
+++ b/platform/platform-tests/testData/editor/multiCaret/EditorDeleteToWordStartInDifferentHumpsMode-after.txt
@@ -1,3 +1,3 @@
 <caret>aCa<caret>
-<caret>pDump Hump<caret>mp
-Yet<caret>herHumpedWord
\ No newline at end of file
+Hum<caret>ump Hu<caret>mp
+<caret>
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/richcopy/BlockSelection.html b/platform/platform-tests/testData/editor/richcopy/BlockSelection.html
index 9f8c46f..1b92b6c 100644
--- a/platform/platform-tests/testData/editor/richcopy/BlockSelection.html
+++ b/platform/platform-tests/testData/editor/richcopy/BlockSelection.html
@@ -1,3 +1,3 @@
-<div style="border:1px inset;padding:2%;"><pre style="margin:0;padding:6px;background-color:#ffffff;font-family:'___PLATFORM_SPECIFIC___';font-size:___PLATFORM_SPECIFIC___;" bgcolor="#ffffff"> <font color="#000080"><b><span style="color:#000080;font-weight:bold;">int </span></b></font><font color="#000000"><span style="color:#000000;">field;</span></font><font color="#000000"><span style="color:#000000;">
+<pre style="background-color:#ffffff;font-family:'___PLATFORM_SPECIFIC___';font-size:___PLATFORM_SPECIFIC___;" bgcolor="#ffffff"> <font color="#000080"><b><span style="color:#000080;font-weight:bold;">int </span></b></font><font color="#000000"><span style="color:#000000;">field;</span></font><font color="#000000"><span style="color:#000000;">
 </span></font><font color="#000000"><span style="color:#000000;">
-</span></font><font color="#000000"><span style="color:#000000;"> </span></font><font color="#000080"><b><span style="color:#000080;font-weight:bold;">public static void </span></b></font><font color="#000000"><span style="color:#000000;">main(String[] args) {</span></font></pre></div>
\ No newline at end of file
+</span></font><font color="#000000"><span style="color:#000000;"> </span></font><font color="#000080"><b><span style="color:#000080;font-weight:bold;">public static void </span></b></font><font color="#000000"><span style="color:#000000;">main(String[] args) {</span></font></pre>
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/richcopy/BlockSelection.rtf b/platform/platform-tests/testData/editor/richcopy/BlockSelection.rtf
index 5285d4d..6ae37249 100644
--- a/platform/platform-tests/testData/editor/richcopy/BlockSelection.rtf
+++ b/platform/platform-tests/testData/editor/richcopy/BlockSelection.rtf
@@ -1,7 +1,7 @@
 {\rtf1\ansi\deff0{\colortbl;\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue128;}
 {\fonttbl{\f1 ___PLATFORM_SPECIFIC___;}}
 
-\s0\box\brdrhair\brdrcf1\brsp317\cbpat2\cb2
+\s0\box\cbpat2\cb2
  \cf3\f1\plain
 \cf3\f1\fs___PLATFORM_SPECIFIC___\b
 int \cf1\plain
@@ -15,4 +15,4 @@
 \cf3\f1\fs___PLATFORM_SPECIFIC___\b
 public static void \cf1\plain
 \cf1\f1\fs___PLATFORM_SPECIFIC___
-main(String[] args) \{\par}
\ No newline at end of file
+main(String[] args) \{}
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/richcopy/NormalSelection.html b/platform/platform-tests/testData/editor/richcopy/NormalSelection.html
index 18efe35b..e1abddb 100644
--- a/platform/platform-tests/testData/editor/richcopy/NormalSelection.html
+++ b/platform/platform-tests/testData/editor/richcopy/NormalSelection.html
@@ -1,8 +1,8 @@
-<div style="border:1px inset;padding:2%;"><pre style="margin:0;padding:6px;background-color:#ffffff;font-family:'___PLATFORM_SPECIFIC___';font-size:___PLATFORM_SPECIFIC___;" bgcolor="#ffffff"><font color="#000080"><b><span style="color:#000080;font-weight:bold;">public class </span></b></font><font color="#000000"><span style="color:#000000;">Basic {
+<pre style="background-color:#ffffff;font-family:'___PLATFORM_SPECIFIC___';font-size:___PLATFORM_SPECIFIC___;" bgcolor="#ffffff"><font color="#000080"><b><span style="color:#000080;font-weight:bold;">public class </span></b></font><font color="#000000"><span style="color:#000000;">Basic {
 </span></font><font color="#000000"><span style="color:#000000;">  </span></font><font color="#000080"><b><span style="color:#000080;font-weight:bold;">int </span></b></font><font color="#000000"><span style="color:#000000;">field;
 </span></font><font color="#000000"><span style="color:#000000;">
 </span></font><font color="#000000"><span style="color:#000000;">  </span></font><font color="#000080"><b><span style="color:#000080;font-weight:bold;">public static void </span></b></font><font color="#000000"><span style="color:#000000;">main(String[] args) {
 </span></font><font color="#000000"><span style="color:#000000;">    System.out.println(</span></font><font color="#008000"><b><span style="color:#008000;font-weight:bold;">"Hello</span></b></font><font color="#000080"><b><span style="color:#000080;font-weight:bold;">\t</span></b></font><font color="#008000"><b><span style="color:#008000;font-weight:bold;">world!"</span></b></font><font color="#000000"><span style="color:#000000;">);
 </span></font><font color="#000000"><span style="color:#000000;">  }
 </span></font><font color="#000000"><span style="color:#000000;">}
-</span></font></pre></div>
\ No newline at end of file
+</span></font></pre>
\ No newline at end of file
diff --git a/platform/platform-tests/testData/editor/richcopy/NormalSelection.rtf b/platform/platform-tests/testData/editor/richcopy/NormalSelection.rtf
index 5a7393a..39ee491 100644
--- a/platform/platform-tests/testData/editor/richcopy/NormalSelection.rtf
+++ b/platform/platform-tests/testData/editor/richcopy/NormalSelection.rtf
@@ -1,7 +1,7 @@
 {\rtf1\ansi\deff0{\colortbl;\red0\green0\blue0;\red255\green255\blue255;\red0\green0\blue128;\red0\green128\blue0;}
 {\fonttbl{\f1 ___PLATFORM_SPECIFIC___;}}
 
-\s0\box\brdrhair\brdrcf1\brsp317\cbpat2\cb2\cf3\f1\plain
+\s0\box\cbpat2\cb2\cf3\f1\plain
 \cf3\f1\fs___PLATFORM_SPECIFIC___\b
 public class \cf1\plain
 \cf1\f1\fs___PLATFORM_SPECIFIC___
@@ -32,4 +32,4 @@
   \}\line
 
 \}\line
-\par}
\ No newline at end of file
+}
\ No newline at end of file
diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/RichCopyTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/RichCopyTest.java
index 7dcc516..0f777d2 100644
--- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/RichCopyTest.java
+++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/RichCopyTest.java
@@ -16,6 +16,8 @@
 package com.intellij.openapi.editor.richcopy;
 
 import com.intellij.openapi.application.ex.PathManagerEx;
+import com.intellij.openapi.editor.richcopy.view.HtmlTransferableData;
+import com.intellij.openapi.editor.richcopy.view.RtfTransferableData;
 import com.intellij.openapi.ide.CopyPasteManager;
 import com.intellij.openapi.util.io.FileUtilRt;
 import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
@@ -48,14 +50,14 @@
     Transferable contents = CopyPasteManager.getInstance().getContents();
     assertNotNull(contents);
 
-    assertTrue(contents.isDataFlavorSupported(HtmlCopyPasteProcessor.FLAVOR));
+    assertTrue(contents.isDataFlavorSupported(HtmlTransferableData.FLAVOR));
     String expectedHtml = getFileContents(getTestName(false) + ".html");
-    String actualHtml = readFully((Reader)contents.getTransferData(HtmlCopyPasteProcessor.FLAVOR));
+    String actualHtml = readFully((Reader)contents.getTransferData(HtmlTransferableData.FLAVOR));
     assertMatches("HTML contents differs", expectedHtml, actualHtml);
 
-    assertTrue(contents.isDataFlavorSupported(RtfCopyPasteProcessor.FLAVOR));
+    assertTrue(contents.isDataFlavorSupported(RtfTransferableData.FLAVOR));
     String expectedRtf = getFileContents(getTestName(false) + ".rtf");
-    String actualRtf = readFully((InputStream)contents.getTransferData(RtfCopyPasteProcessor.FLAVOR));
+    String actualRtf = readFully((InputStream)contents.getTransferData(RtfTransferableData.FLAVOR));
     assertMatches("RTF contents differs", expectedRtf, actualRtf);
   }
 
diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java
index d6c0b30..128320c 100644
--- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java
+++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/richcopy/SyntaxInfoConstructionTest.java
@@ -19,12 +19,13 @@
 import com.intellij.openapi.editor.LogicalPosition;
 import com.intellij.openapi.editor.SelectionModel;
 import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.richcopy.model.ColorRegistry;
+import com.intellij.openapi.editor.richcopy.model.MarkupHandler;
+import com.intellij.openapi.editor.richcopy.model.SyntaxInfo;
 import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
 import com.intellij.ui.JBColor;
 import junit.framework.TestCase;
 
-import java.awt.*;
-
 /**
  * @author Denis Zhdanov
  * @since 3/27/13 11:11 AM
@@ -235,56 +236,64 @@
   }
 
   private String getSyntaxInfo() {
-    final StringBuilder syntaxInfo = new StringBuilder();
-    Editor editor = myFixture.getEditor();
+    final StringBuilder builder = new StringBuilder();
+    final Editor editor = myFixture.getEditor();
+    final String text = editor.getSelectionModel().getSelectedText(true);
+    assertNotNull(text);
 
     TextWithMarkupProcessor processor = new TextWithMarkupProcessor();
     processor.addBuilder(new TextWithMarkupBuilder() {
       @Override
-      public void init(Color defaultForeground, Color defaultBackground, String defaultFontFamily, int fontSize) {
-        assertEquals(JBColor.BLACK, defaultForeground);
-        assertEquals(JBColor.WHITE, defaultBackground);
-        assertEquals(getFontSize(), fontSize);
+      public void reset() {
+
       }
 
       @Override
-      public boolean isOverflowed() {
-        return false;
-      }
+      public void build(SyntaxInfo syntaxInfo) {
+        final ColorRegistry colorRegistry = syntaxInfo.getColorRegistry();
+        assertEquals(JBColor.BLACK, colorRegistry.dataById(syntaxInfo.getDefaultForeground()));
+        assertEquals(JBColor.WHITE, colorRegistry.dataById(syntaxInfo.getDefaultBackground()));
+        assertEquals(getFontSize(), syntaxInfo.getSingleFontSize());
+        SyntaxInfo.MarkupIterator it = syntaxInfo.new MarkupIterator();
+        try {
+          while (it.hasNext()) {
+            it.processNext(new MarkupHandler() {
+              @Override
+              public void handleText(int startOffset, int endOffset) throws Exception {
+                builder.append("text=").append(text.substring(startOffset, endOffset)).append('\n');
+              }
 
-      @Override
-      public void setFontFamily(String fontFamily) {
-      }
+              @Override
+              public void handleForeground(int foregroundId) throws Exception {
+                builder.append("foreground=").append(colorRegistry.dataById(foregroundId)).append(',');
+              }
 
-      @Override
-      public void setFontStyle(int fontStyle) {
-        syntaxInfo.append("fontStyle=").append(fontStyle).append(',');
-      }
+              @Override
+              public void handleBackground(int backgroundId) throws Exception {
+                builder.append("background=").append(colorRegistry.dataById(backgroundId)).append(',');
+              }
 
-      @Override
-      public void setForeground(Color foreground) {
-        syntaxInfo.append("foreground=").append(foreground).append(',');
-      }
+              @Override
+              public void handleFont(int fontNameId) throws Exception {
+                assertEquals(1, fontNameId);
+              }
 
-      @Override
-      public void setBackground(Color background) {
-        syntaxInfo.append("background=").append(background).append(',');
+              @Override
+              public void handleStyle(int style) throws Exception {
+                builder.append("fontStyle=").append(style).append(',');
+              }
+            });
+          }
+        }
+        finally {
+          it.dispose();
+        }
       }
-
-      @Override
-      public void addTextFragment(CharSequence charSequence, int startOffset, int endOffset) {
-        syntaxInfo.append("text=").append(charSequence.subSequence(startOffset, endOffset)).append('\n');
-      }
-
-      @Override
-      public void complete() {
-
-      }
-    });
+     });
     SelectionModel selectionModel = editor.getSelectionModel();
     processor.collectTransferableData(myFixture.getFile(), editor, selectionModel.getBlockSelectionStarts(), selectionModel.getBlockSelectionEnds());
 
-    return syntaxInfo.toString();
+    return builder.toString();
   }
 
   private void init(String text) {
diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java
index 2c51063..fd6dd2e 100644
--- a/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java
+++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileEditor/NonProjectFileAccessTest.java
@@ -21,6 +21,7 @@
 import com.intellij.openapi.application.Result;
 import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.application.impl.ApplicationImpl;
+import com.intellij.openapi.command.WriteCommandAction;
 import com.intellij.openapi.components.impl.ComponentManagerImpl;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.actionSystem.EditorActionManager;
@@ -29,6 +30,10 @@
 import com.intellij.openapi.fileEditor.impl.NonProjectFileNotificationPanel;
 import com.intellij.openapi.fileEditor.impl.NonProjectFileWritingAccessProvider;
 import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider;
+import com.intellij.openapi.module.EmptyModuleType;
+import com.intellij.openapi.module.ModifiableModuleModel;
+import com.intellij.openapi.module.Module;
+import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.roots.ContentEntry;
 import com.intellij.openapi.roots.ModuleRootManager;
 import com.intellij.openapi.roots.ProjectFileIndex;
@@ -84,7 +89,7 @@
     assertNull(getNotificationPanel(nonProjectFile));
   }
 
-  public void testAccessToFilesUnderProjectRootAndDotIdea() throws Exception {
+  public void testAccessToProjectSystemFiles() throws Exception {
     saveProject();
     VirtualFile fileUnderProjectDir = new WriteAction<VirtualFile>() {
       @Override
@@ -100,6 +105,41 @@
     typeAndCheck(fileUnderProjectDir, false);
   }
 
+  public void testAccessToModuleSystemFiles() throws Exception {
+    final Module moduleWithoutContentRoot = new WriteCommandAction<Module>(getProject()) {
+      @Override
+      protected void run(@NotNull Result<Module> result) throws Throwable {
+        String moduleName;
+        ModifiableModuleModel moduleModel = ModuleManager.getInstance(getProject()).getModifiableModel();
+        try {
+          VirtualFile moduleDir = getProject().getBaseDir().createChildDirectory(this, "moduleWithoutContentRoot");
+          moduleName = moduleModel.newModule(moduleDir + "/moduleWithoutContentRoot.iml", EmptyModuleType.EMPTY_MODULE).getName();
+          moduleModel.commit();
+        }
+        catch (Throwable t) {
+          moduleModel.dispose();
+          throw t;
+        }
+
+        result.setResult(ModuleManager.getInstance(getProject()).findModuleByName(moduleName));
+      }
+    }.execute().getResultObject();
+    saveProject();
+    
+    VirtualFile fileUnderModuleDir = new WriteAction<VirtualFile>() {
+      @Override
+      protected void run(@NotNull Result<VirtualFile> result) throws Throwable {
+        result.setResult(moduleWithoutContentRoot.getModuleFile().getParent().createChildData(this, "fileUnderModuleDir.txt"));
+      }
+    }.execute().getResultObject();
+    
+    assertFalse(ProjectFileIndex.SERVICE.getInstance(getProject()).isInContent(fileUnderModuleDir));
+
+    typeAndCheck(moduleWithoutContentRoot.getModuleFile(), true);
+    typeAndCheck(myModule.getModuleFile(), true);
+    typeAndCheck(fileUnderModuleDir, false);
+  }
+
   private void saveProject() {
     ApplicationImpl app = (ApplicationImpl)ApplicationManager.getApplication();
     boolean save = app.isDoNotSave();
diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java
index 0336bb8..2f61f4e 100644
--- a/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java
+++ b/platform/platform-tests/testSrc/com/intellij/openapi/fileTypes/impl/FileTypesTest.java
@@ -37,6 +37,7 @@
 import com.intellij.psi.impl.PsiManagerEx;
 import com.intellij.testFramework.PlatformTestCase;
 import com.intellij.util.PatternUtil;
+import com.intellij.util.ui.UIUtil;
 import junit.framework.TestCase;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -292,10 +293,12 @@
 
       VfsUtil.saveText(vFile, "TYPE:IDEA_MODULE");
       myFileTypeManager.drainReDetectQueue();
+      UIUtil.dispatchAllInvocationEvents();
       assertTrue(vFile.getFileType().toString(), vFile.getFileType() instanceof ModuleFileType);
 
       VfsUtil.saveText(vFile, "TYPE:IDEA_PROJECT");
       myFileTypeManager.drainReDetectQueue();
+      UIUtil.dispatchAllInvocationEvents();
       assertTrue(vFile.getFileType().toString(), vFile.getFileType() instanceof ProjectFileType);
     }
     finally {
diff --git a/platform/projectModel-impl/src/com/intellij/application/options/PathMacrosImpl.java b/platform/projectModel-impl/src/com/intellij/application/options/PathMacrosImpl.java
index 493b21d..cce7a68 100644
--- a/platform/projectModel-impl/src/com/intellij/application/options/PathMacrosImpl.java
+++ b/platform/projectModel-impl/src/com/intellij/application/options/PathMacrosImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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,8 +17,8 @@
 
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.PathMacros;
-import com.intellij.openapi.components.ApplicationComponent;
 import com.intellij.openapi.components.ExpandMacroToPathMap;
+import com.intellij.openapi.components.NamedComponent;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.NamedJDOMExternalizable;
@@ -39,7 +39,7 @@
 /**
  * @author dsl
  */
-public class PathMacrosImpl extends PathMacros implements ApplicationComponent, NamedJDOMExternalizable, RoamingTypeDisabled {
+public class PathMacrosImpl extends PathMacros implements NamedComponent, NamedJDOMExternalizable, RoamingTypeDisabled {
   private static final Logger LOG = Logger.getInstance("#com.intellij.application.options.PathMacrosImpl");
   private final Map<String, String> myLegacyMacros = new HashMap<String, String>();
   private final Map<String, String> myMacros = new HashMap<String, String>();
@@ -148,14 +148,6 @@
   }
 
   @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   public String getExternalFileName() {
     return EXT_FILE_NAME;
   }
diff --git a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdater.java b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdater.java
index 2478fef..5d45cf2 100644
--- a/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdater.java
+++ b/platform/projectModel-impl/src/com/intellij/openapi/roots/impl/PushedFilePropertiesUpdater.java
@@ -92,7 +92,12 @@
           public void fileCreated(@NotNull final VirtualFileEvent event) {
             final VirtualFile file = event.getFile();
             final FilePropertyPusher[] pushers = file.isDirectory() ? myPushers : myFilePushers;
-            pushRecursively(file, pushers);
+            if (event.isFromRefresh()) {
+              schedulePushRecursively(file, pushers);
+            } else {
+              // push synchronously to avoid entering dumb mode in the middle of a meaningful write action
+              doPushRecursively(file, pushers, ProjectRootManager.getInstance(myProject).getFileIndex());
+            }
           }
 
           @Override
@@ -116,7 +121,7 @@
 
             @Override
             public void pushRecursively(VirtualFile file, Project project) {
-              PushedFilePropertiesUpdater.this.pushRecursively(file, pusher);
+              PushedFilePropertiesUpdater.this.schedulePushRecursively(file, pusher);
             }
           });
         }
@@ -124,7 +129,7 @@
     });
   }
 
-  private void pushRecursively(final VirtualFile dir, final FilePropertyPusher... pushers) {
+  private void schedulePushRecursively(final VirtualFile dir, final FilePropertyPusher... pushers) {
     if (pushers.length == 0) return;
     final ProjectFileIndex fileIndex = ProjectRootManager.getInstance(myProject).getFileIndex();
     queueTask(new DumbModeTask() {
diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/values/StringValue.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/values/StringValue.java
index 5385d3c..671fa1a 100644
--- a/platform/script-debugger/backend/src/org/jetbrains/debugger/values/StringValue.java
+++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/values/StringValue.java
@@ -10,5 +10,5 @@
   /**
    * Asynchronously reloads object value with extended size limit
    */
-  ActionCallback reloadHeavyValue();
+  ActionCallback getFullString();
 }
\ No newline at end of file
diff --git a/platform/script-debugger/backend/src/org/jetbrains/debugger/values/ValueType.java b/platform/script-debugger/backend/src/org/jetbrains/debugger/values/ValueType.java
index bd24b5b..06da6c1 100644
--- a/platform/script-debugger/backend/src/org/jetbrains/debugger/values/ValueType.java
+++ b/platform/script-debugger/backend/src/org/jetbrains/debugger/values/ValueType.java
@@ -15,14 +15,7 @@
   ARRAY,
   NODE,
 
-  /**
-   * undefined type.
-   */
   UNDEFINED,
-
-  /**
-   * null type. This is a bogus type that doesn't exist in JavaScript.
-   */
   NULL;
 
   private static final ValueType[] VALUE_TYPES = ValueType.values();
diff --git a/platform/script-debugger/backend/src/org/jetbrains/rpc/NestedCommandCallbackWithResponse.java b/platform/script-debugger/backend/src/org/jetbrains/rpc/NestedCommandCallbackWithResponse.java
index c93e635..ee5640c 100644
--- a/platform/script-debugger/backend/src/org/jetbrains/rpc/NestedCommandCallbackWithResponse.java
+++ b/platform/script-debugger/backend/src/org/jetbrains/rpc/NestedCommandCallbackWithResponse.java
@@ -7,8 +7,8 @@
   extends CommandCallbackWithResponseBase<SUCCESS_RESPONSE, AsyncResult<MAIN_RESULT>, RESULT, ERROR_DETAILS> {
   private final PairConsumer<RESULT, AsyncResult<MAIN_RESULT>> consumer;
 
-  public NestedCommandCallbackWithResponse(AsyncResult<MAIN_RESULT> mainAsyncResult, String methodName, PairConsumer<RESULT, AsyncResult<MAIN_RESULT>> consumer) {
-    super(mainAsyncResult, methodName, null);
+  public NestedCommandCallbackWithResponse(AsyncResult<MAIN_RESULT> result, String methodName, PairConsumer<RESULT, AsyncResult<MAIN_RESULT>> consumer) {
+    super(result, methodName, null);
 
     this.consumer = consumer;
   }
diff --git a/platform/script-debugger/backend/src/org/jetbrains/rpc/ResultReader.java b/platform/script-debugger/backend/src/org/jetbrains/rpc/ResultReader.java
index 439e30d..4bb055c 100644
--- a/platform/script-debugger/backend/src/org/jetbrains/rpc/ResultReader.java
+++ b/platform/script-debugger/backend/src/org/jetbrains/rpc/ResultReader.java
@@ -1,5 +1,7 @@
 package org.jetbrains.rpc;
 
+import org.jetbrains.annotations.NotNull;
+
 public interface ResultReader<RESPONSE> {
-  <RESULT> RESULT readResult(String readMethodName, RESPONSE successResponse);
+  <RESULT> RESULT readResult(@NotNull String readMethodName, @NotNull RESPONSE successResponse);
 }
\ No newline at end of file
diff --git a/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/CustomPropertiesValuePresentation.java b/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/CustomPropertiesValuePresentation.java
index 4654d3e..f6a42d7 100644
--- a/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/CustomPropertiesValuePresentation.java
+++ b/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/CustomPropertiesValuePresentation.java
@@ -21,7 +21,7 @@
 
   @Override
   public void renderValue(@NotNull XValueTextRenderer renderer) {
-    renderer.renderComment(VariableView.getClassName(value));
+    renderer.renderComment(VariableView.getObjectValueDescription(value));
     renderer.renderSpecialSymbol(" {");
     boolean isFirst = true;
     for (Variable property : properties) {
@@ -63,8 +63,7 @@
           break;
 
         case OBJECT:
-          ObjectValue objectValue = (ObjectValue)value;
-          renderer.renderComment(VariableView.getClassName(objectValue));
+          renderer.renderComment(VariableView.getObjectValueDescription((ObjectValue)value));
           break;
 
         default:
diff --git a/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.java b/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.java
index c37df05..90737cc 100644
--- a/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.java
+++ b/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/VariableView.java
@@ -62,8 +62,14 @@
     return StringUtil.isEmpty(className) ? "Object" : className;
   }
 
+  @NotNull
+  public static String getObjectValueDescription(@NotNull ObjectValue value) {
+    String description = value.getValueString();
+    return StringUtil.isEmpty(description) ? getClassName(value) : description;
+  }
+
   public static void setObjectPresentation(@NotNull ObjectValue value, @NotNull Icon icon, @NotNull XValueNode node) {
-    node.setPresentation(icon, new ObjectValuePresentation(getClassName(value)), value.hasProperties() != ThreeState.NO);
+    node.setPresentation(icon, new ObjectValuePresentation(getObjectValueDescription(value)), value.hasProperties() != ThreeState.NO);
   }
 
   public static void setArrayPresentation(@NotNull Value value, @NotNull VariableContext context, @NotNull final Icon icon, @NotNull XValueNode node) {
@@ -475,7 +481,7 @@
       }
 
       final AtomicBoolean evaluated = new AtomicBoolean();
-      ((StringValue)value).reloadHeavyValue().doWhenDone(new Runnable() {
+      ((StringValue)value).getFullString().doWhenDone(new Runnable() {
         @Override
         public void run() {
           if (!callback.isObsolete() && evaluated.compareAndSet(false, true)) {
diff --git a/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/SuspendContextImpl.java b/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/SuspendContextImpl.java
index f4e7677..24e080772 100644
--- a/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/SuspendContextImpl.java
+++ b/platform/script-debugger/debugger-ui/src/org/jetbrains/debugger/frame/SuspendContextImpl.java
@@ -58,7 +58,7 @@
         }
         else {
           if (value instanceof StringValue && ((StringValue)value).isTruncated()) {
-            ((StringValue)value).reloadHeavyValue().doWhenDone(new Runnable() {
+            ((StringValue)value).getFullString().doWhenDone(new Runnable() {
               @Override
               public void run() {
                 result.setDone(value.getValueString());
diff --git a/platform/testFramework/src/com/intellij/mock/MockEditorFactory.java b/platform/testFramework/src/com/intellij/mock/MockEditorFactory.java
index fa9a832..37d365e 100644
--- a/platform/testFramework/src/com/intellij/mock/MockEditorFactory.java
+++ b/platform/testFramework/src/com/intellij/mock/MockEditorFactory.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -119,16 +119,4 @@
   public void refreshAllEditors() {
   }
 
-  @Override
-  @NotNull
-  public String getComponentName() {
-    return "mockeditorfactory";
-  }
-
-  @Override
-  public void initComponent() { }
-
-  @Override
-  public void disposeComponent() {
-  }
 }
diff --git a/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java b/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java
index cfaf4a3..23a371a12 100644
--- a/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java
+++ b/platform/testFramework/src/com/intellij/mock/MockLocalFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -147,6 +147,7 @@
   public void renameFile(final Object requestor, @NotNull final VirtualFile vFile, @NotNull final String newName) throws IOException {
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(final Object requestor, @NotNull final VirtualFile vDir, @NotNull final String fileName) throws IOException {
     return myDelegate.createChildFile(requestor, vDir, fileName);
@@ -158,6 +159,7 @@
     return myDelegate.createChildDirectory(requestor, vDir, dirName);
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(final Object requestor, @NotNull final VirtualFile virtualFile, @NotNull final VirtualFile newParent, @NotNull final String copyName)
     throws IOException {
diff --git a/platform/testFramework/src/com/intellij/mock/MockVirtualFileSystem.java b/platform/testFramework/src/com/intellij/mock/MockVirtualFileSystem.java
index 19870bf..8550f97 100644
--- a/platform/testFramework/src/com/intellij/mock/MockVirtualFileSystem.java
+++ b/platform/testFramework/src/com/intellij/mock/MockVirtualFileSystem.java
@@ -56,24 +56,29 @@
 
   @Override
   public void deleteFile(Object requestor, @NotNull VirtualFile vFile) throws IOException {
+    throw new UnsupportedOperationException();
   }
 
   @Override
   public void moveFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent) throws IOException {
+    throw new UnsupportedOperationException();
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent, @NotNull final String copyName) throws IOException {
-    return null;
+    throw new UnsupportedOperationException();
   }
 
   @Override
   public void renameFile(Object requestor, @NotNull VirtualFile vFile, @NotNull String newName) throws IOException {
+    throw new UnsupportedOperationException();
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
-    return null;
+    throw new UnsupportedOperationException();
   }
 
   @Override
diff --git a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
index 5065b9d..42e7c70 100644
--- a/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
+++ b/platform/testFramework/src/com/intellij/testFramework/LightPlatformTestCase.java
@@ -50,6 +50,7 @@
 import com.intellij.openapi.fileEditor.impl.FileDocumentManagerImpl;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.fileTypes.FileTypeManager;
+import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl;
 import com.intellij.openapi.module.EmptyModuleType;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleManager;
@@ -337,18 +338,29 @@
 
   @Override
   protected void setUp() throws Exception {
-    super.setUp();
-    initApplication();
-    ourApplication.setDataProvider(this);
-    doSetup(new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()), configureLocalInspectionTools(), myAvailableInspectionTools);
-    InjectedLanguageManagerImpl.pushInjectors(getProject());
+    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
+      @Override
+      public void run() {
+        try {
+          LightPlatformTestCase.super.setUp();
+          initApplication();
+          ourApplication.setDataProvider(LightPlatformTestCase.this);
+          doSetup(new SimpleLightProjectDescriptor(getModuleType(), getProjectJDK()), configureLocalInspectionTools(),
+                  myAvailableInspectionTools);
+          InjectedLanguageManagerImpl.pushInjectors(getProject());
 
-    storeSettings();
+          storeSettings();
 
-    myThreadTracker = new ThreadTracker();
-    ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots();
-    VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance();
-    filePointerManager.storePointers();
+          myThreadTracker = new ThreadTracker();
+          ModuleRootManager.getInstance(ourModule).orderEntries().getAllLibrariesAndSdkClassesRoots();
+          VirtualFilePointerManagerImpl filePointerManager = (VirtualFilePointerManagerImpl)VirtualFilePointerManager.getInstance();
+          filePointerManager.storePointers();
+        }
+        catch (Exception e) {
+          throw new RuntimeException(e);
+        }
+      }
+    });
   }
 
   public static void doSetup(@NotNull LightProjectDescriptor descriptor,
@@ -444,6 +456,7 @@
 
       assertEmpty("There are unsaved documents", Arrays.asList(unsavedDocuments));
     }
+    ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
   }
 
   // todo: use Class<? extends InspectionProfileEntry> once on Java 7
@@ -521,6 +534,7 @@
   }
 
   public static void doTearDown(@NotNull final Project project, IdeaTestApplication application, boolean checkForEditors) throws Exception {
+    ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
     DocumentCommitThread.getInstance().clearQueue();
     CodeStyleSettingsManager.getInstance(project).dropTemporarySettings();
     checkAllTimersAreDisposed();
diff --git a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
index 8d062af..c72ff35 100644
--- a/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
+++ b/platform/testFramework/src/com/intellij/testFramework/PlatformTestCase.java
@@ -35,6 +35,8 @@
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.EditorFactory;
 import com.intellij.openapi.editor.event.DocumentListener;
+import com.intellij.openapi.fileTypes.FileTypeManager;
+import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl;
 import com.intellij.openapi.module.EmptyModuleType;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleManager;
@@ -68,7 +70,6 @@
 import com.intellij.psi.impl.DocumentCommitThread;
 import com.intellij.psi.impl.PsiManagerEx;
 import com.intellij.psi.impl.source.tree.injected.InjectedLanguageManagerImpl;
-import com.intellij.util.PatchedWeakReference;
 import com.intellij.util.PlatformUtils;
 import com.intellij.util.indexing.IndexableSetContributor;
 import com.intellij.util.indexing.IndexedRootsProvider;
@@ -228,6 +229,7 @@
     LightPlatformTestCase.clearUncommittedDocuments(getProject());
 
     runStartupActivities();
+    ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
   }
 
   protected Project doCreateProject(File projectFile) throws Exception {
@@ -344,8 +346,6 @@
     }
 
     LocalHistoryImpl.getInstanceImpl().cleanupForNextTest();
-
-    PatchedWeakReference.clearAll();
   }
 
   private static Set<VirtualFile> eternallyLivingFiles() {
diff --git a/platform/testFramework/src/com/intellij/testFramework/TempFiles.java b/platform/testFramework/src/com/intellij/testFramework/TempFiles.java
index add3c46..a193477 100644
--- a/platform/testFramework/src/com/intellij/testFramework/TempFiles.java
+++ b/platform/testFramework/src/com/intellij/testFramework/TempFiles.java
@@ -43,13 +43,15 @@
     return getVFileByFile(createTempFile(prefix, postfix));
   }
 
+  @NotNull
   public File createTempFile(@NotNull String prefix) {
-    return createTempFile(prefix, "_Temp_File_");
+    return createTempFile(prefix, null);
   }
 
-  public File createTempFile(@NotNull String prefix, String postfix) {
+  @NotNull
+  public File createTempFile(@NotNull String prefix, String suffix) {
     try {
-      File tempFile = FileUtil.createTempFile(prefix, postfix);
+      File tempFile = FileUtil.createTempFile(prefix, suffix);
       tempFileCreated(tempFile);
       getVFileByFile(tempFile);
       return tempFile;
@@ -68,10 +70,12 @@
     return LocalFileSystem.getInstance().refreshAndFindFileByIoFile(tempFile);
   }
 
+  @NotNull
   public File createTempDir() {
     return createTempDir("dir");
   }
 
+  @NotNull
   private File createTempDir(@NotNull String prefix) {
     try {
       File dir = FileUtil.createTempDirectory(prefix, "test",false);
@@ -94,12 +98,6 @@
     return getVFileByFile(createTempDir(prefix));
   }
 
-  public String createTempPath() {
-    File tempFile = createTempFile("xxx");
-    String absolutePath = tempFile.getAbsolutePath();
-    return absolutePath;
-  }
-
   public void deleteAll() {
     for (File file : myFilesToDelete) {
       if (!FileUtil.delete(file)) {
@@ -108,7 +106,7 @@
     }
   }
 
-  public VirtualFile createVFile(VirtualFile parentDir, String name, String text) {
+  public VirtualFile createVFile(@NotNull VirtualFile parentDir, @NotNull String name, @NotNull String text) {
     try {
       final VirtualFile virtualFile = parentDir.createChildData(this, name);
       VfsUtil.saveText(virtualFile, text + "\n");
diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
index 1096c84..75d82bc 100644
--- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
+++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/CodeInsightTestFixtureImpl.java
@@ -1000,8 +1000,14 @@
                 super.completionFinished(offset1, offset2, indicator, items, hasModifiers);
               }
             };
-            Editor editor = getCompletionEditor();
-            handler.invokeCompletion(getProject(), editor, invocationCount);
+            final Editor editor = getCompletionEditor();
+            assert editor != null: "Editor is null";
+            editor.getCaretModel().runForEachCaret(new CaretAction() {
+              @Override
+              public void perform(final Caret caret) {
+                handler.invokeCompletion(getProject(), editor, invocationCount);
+              }
+            });
             PsiDocumentManager.getInstance(getProject()).commitAllDocuments(); // to compare with file text
           }
         }, null, null);
diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/HeavyIdeaTestFixtureImpl.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/HeavyIdeaTestFixtureImpl.java
index 3551da7..4adc2aa 100644
--- a/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/HeavyIdeaTestFixtureImpl.java
+++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/impl/HeavyIdeaTestFixtureImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -29,6 +29,8 @@
 import com.intellij.openapi.fileEditor.FileEditorManager;
 import com.intellij.openapi.fileEditor.OpenFileDescriptor;
 import com.intellij.openapi.fileEditor.ex.FileEditorManagerEx;
+import com.intellij.openapi.fileTypes.FileTypeManager;
+import com.intellij.openapi.fileTypes.impl.FileTypeManagerImpl;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.project.Project;
@@ -146,9 +148,9 @@
     new WriteCommandAction.Simple(null) {
       @Override
       protected void run() throws Throwable {
-        File projectFile = FileUtil.createTempFile(myName+"_", PROJECT_FILE_SUFFIX);
-        FileUtil.delete(projectFile);
-        myFilesToDelete.add(projectFile);
+        File tempDirectory = FileUtil.createTempDirectory(myName, "");
+        File projectFile = new File(tempDirectory, myName + PROJECT_FILE_SUFFIX);
+        myFilesToDelete.add(tempDirectory);
 
         LocalFileSystem.getInstance().refreshAndFindFileByIoFile(projectFile);
         ByteArrayOutputStream buffer = new ByteArrayOutputStream();
@@ -166,6 +168,7 @@
 
         ProjectManagerEx.getInstanceEx().openTestProject(myProject);
         LightPlatformTestCase.clearUncommittedDocuments(myProject);
+        ((FileTypeManagerImpl)FileTypeManager.getInstance()).drainReDetectQueue();
       }
     }.execute().throwException();
   }
@@ -244,6 +247,7 @@
       }
     }.execute();
     return ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
+            @Override
             public PsiFile compute() {
               return PsiManager.getInstance(getProject()).findFile(virtualFile[0]);
             }
diff --git a/platform/testFramework/testSrc/com/intellij/testFramework/vcs/AbstractVcsTestCase.java b/platform/testFramework/testSrc/com/intellij/testFramework/vcs/AbstractVcsTestCase.java
index 10a6bc5..4df8f9c 100644
--- a/platform/testFramework/testSrc/com/intellij/testFramework/vcs/AbstractVcsTestCase.java
+++ b/platform/testFramework/testSrc/com/intellij/testFramework/vcs/AbstractVcsTestCase.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -28,6 +28,7 @@
 import com.intellij.openapi.vcs.annotate.AnnotationProvider;
 import com.intellij.openapi.vcs.annotate.FileAnnotation;
 import com.intellij.openapi.vcs.changes.*;
+import com.intellij.openapi.vcs.impl.ProjectLevelVcsManagerImpl;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.testFramework.UsefulTestCase;
@@ -95,7 +96,7 @@
       if (pluginName != null) {
         System.setProperty(key, pluginName);
       }
-      String name = getClass().getName() + "." + testName;
+      String name = testName;
       final TestFixtureBuilder<IdeaProjectTestFixture> testFixtureBuilder = IdeaTestFixtureFactory.getFixtureFactory().createFixtureBuilder(name);
       myProjectFixture = testFixtureBuilder.getFixture();
       testFixtureBuilder.addModule(EmptyModuleFixtureBuilder.class).addContentRoot(clientRoot.toString());
@@ -116,13 +117,15 @@
           assert myWorkingCopyDir != null;
         }
       });
-    } finally {
+    }
+    finally {
       if (was != null) {
         System.setProperty(key, was);
       } else {
         System.clearProperty(key);
       }
     }
+    ((ProjectLevelVcsManagerImpl)ProjectLevelVcsManager.getInstance(myProject)).waitForInitialized();
   }
 
   protected void projectCreated() {
diff --git a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java
index 35463f0..1afdabc 100644
--- a/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java
+++ b/platform/usageView/src/com/intellij/usages/impl/UsageViewImpl.java
@@ -54,10 +54,7 @@
 import com.intellij.usageView.UsageViewManager;
 import com.intellij.usages.*;
 import com.intellij.usages.rules.*;
-import com.intellij.util.Alarm;
-import com.intellij.util.Consumer;
-import com.intellij.util.EditSourceOnDoubleClickHandler;
-import com.intellij.util.Processor;
+import com.intellij.util.*;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.Convertor;
 import com.intellij.util.containers.TransferToEDTQueue;
@@ -1136,9 +1133,7 @@
     for (Usage usage : myUsageNodes.keySet()) {
       if (usage instanceof UsageInfo2UsageAdapter) {
         SmartPsiElementPointer<?> pointer = ((UsageInfo2UsageAdapter)usage).getUsageInfo().getSmartPointer();
-        if (pointer != null) {
-          pointerManager.removePointer(pointer);
-        }
+        pointerManager.removePointer(pointer);
       }
     }
   }
@@ -1164,7 +1159,7 @@
             return;
           }
           showNode(firstUsageNode);
-          if (UsageViewSettings.getInstance().isExpanded()) {
+          if (UsageViewSettings.getInstance().isExpanded() && myUsageNodes.size() < 10000) {
             expandAll();
           }
         }
diff --git a/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java b/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java
index 5d37625..1ce5fb4 100644
--- a/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java
+++ b/platform/util-rt/src/com/intellij/openapi/util/io/FileUtilRt.java
@@ -193,14 +193,11 @@
   public static File createTempDirectory(@NotNull File dir,
                                          @NotNull @NonNls String prefix, @Nullable @NonNls String suffix,
                                          boolean deleteOnExit) throws IOException {
-    File file = doCreateTempFile(dir, prefix, suffix);
+    File file = doCreateTempFile(dir, prefix, suffix, true);
     if (deleteOnExit) {
       file.deleteOnExit();
     }
-    if (!file.delete() && file.exists()) {
-      throw new IOException("Cannot delete file: " + file);
-    }
-    if (!file.mkdir() && !file.isDirectory()) {
+    if (!file.isDirectory()) {
       throw new IOException("Cannot create directory: " + file);
     }
     return file;
@@ -235,7 +232,7 @@
   public static File createTempFile(@NonNls File dir,
                                     @NotNull @NonNls String prefix, @Nullable @NonNls String suffix,
                                     boolean create, boolean deleteOnExit) throws IOException {
-    File file = doCreateTempFile(dir, prefix, suffix);
+    File file = doCreateTempFile(dir, prefix, suffix, false);
     if (deleteOnExit) {
       file.deleteOnExit();
     }
@@ -248,7 +245,10 @@
   }
 
   @NotNull
-  private static File doCreateTempFile(@NotNull File dir, @NotNull @NonNls String prefix, @Nullable @NonNls String suffix) throws IOException {
+  private static File doCreateTempFile(@NotNull File dir,
+                                       @NotNull @NonNls String prefix,
+                                       @Nullable @NonNls String suffix,
+                                       boolean isDirectory) throws IOException {
     //noinspection ResultOfMethodCallIgnored
     dir.mkdirs();
 
@@ -262,7 +262,7 @@
     int exceptionsCount = 0;
     while (true) {
       try {
-        final File temp = createTempFile(prefix, suffix, dir);
+        final File temp = createTemp(prefix, suffix, dir, isDirectory);
         return normalizeFile(temp);
       }
       catch (IOException e) { // Win32 createFileExclusively access denied
@@ -274,7 +274,8 @@
   }
 
   @NotNull
-  public static File createTempFile(@NotNull String prefix, @NotNull String suffix, @NotNull File directory) throws IOException {
+  private static File createTemp(@NotNull String prefix, @NotNull String suffix, @NotNull File directory, boolean isDirectory) throws IOException {
+    // normalize and use only the file name from the prefix
     prefix = new File(prefix).getName();
     File f;
     int i = 0;
@@ -282,15 +283,15 @@
       String name = prefix + (i==0?"":Integer.toString(i)) + suffix;
       f = new File(directory, name);
       if (!name.equals(f.getName())) {
-        throw new IOException("Unable to create temporary file, " + f);
+        throw new IOException("Unable to create temporary file, " + f+", "+name);
       }
       i++;
     } while (f.exists());
 
-    if (!f.createNewFile()) {
+    boolean success = isDirectory ? f.mkdir() : f.createNewFile();
+    if (!success) {
       throw new IOException("Unable to create temporary file " + f);
     }
-
     return f;
   }
 
diff --git a/platform/util/src/com/intellij/execution/process/UnixProcessManager.java b/platform/util/src/com/intellij/execution/process/UnixProcessManager.java
index aa416f6..5aa77f8 100644
--- a/platform/util/src/com/intellij/execution/process/UnixProcessManager.java
+++ b/platform/util/src/com/intellij/execution/process/UnixProcessManager.java
@@ -49,7 +49,7 @@
         C_LIB = ((CLib)Native.loadLibrary("c", CLib.class));
       }
     }
-    catch (Exception e) {
+    catch (Throwable e) {
       Logger log = Logger.getInstance(UnixProcessManager.class);
       log.warn("Can't load c library", e);
       C_LIB = null;
diff --git a/platform/util/src/com/intellij/icons/AllIcons.java b/platform/util/src/com/intellij/icons/AllIcons.java
index d797aee..dfadcb4 100644
--- a/platform/util/src/com/intellij/icons/AllIcons.java
+++ b/platform/util/src/com/intellij/icons/AllIcons.java
@@ -697,6 +697,7 @@
     public static final Icon DeleteContentRootRollover = IconLoader.getIcon("/modules/deleteContentRootRollover.png"); // 9x9
     public static final Icon Edit = IconLoader.getIcon("/modules/edit.png"); // 14x14
     public static final Icon ExcludeRoot = IconLoader.getIcon("/modules/excludeRoot.png"); // 16x16
+    public static final Icon GeneratedFolder = IconLoader.getIcon("/modules/generatedFolder.png"); // 16x16
     public static final Icon GeneratedSourceRoot = IconLoader.getIcon("/modules/generatedSourceRoot.png"); // 16x16
     public static final Icon GeneratedTestRoot = IconLoader.getIcon("/modules/generatedTestRoot.png"); // 16x16
     public static final Icon Library = IconLoader.getIcon("/modules/library.png"); // 16x16
diff --git a/platform/util/src/com/intellij/openapi/util/IconLoader.java b/platform/util/src/com/intellij/openapi/util/IconLoader.java
index b611d7a..3258446 100644
--- a/platform/util/src/com/intellij/openapi/util/IconLoader.java
+++ b/platform/util/src/com/intellij/openapi/util/IconLoader.java
@@ -24,6 +24,7 @@
 import com.intellij.util.RetinaImage;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.WeakHashMap;
+import com.intellij.util.ui.JBImageIcon;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -33,7 +34,6 @@
 import java.awt.*;
 import java.awt.image.BufferedImage;
 import java.awt.image.FilteredImageSource;
-import java.awt.image.ImageObserver;
 import java.awt.image.ImageProducer;
 import java.lang.ref.Reference;
 import java.lang.reflect.Field;
@@ -98,7 +98,7 @@
 
   @Deprecated
   public static Icon getIcon(@NotNull final Image image) {
-    return new MyImageIcon(image);
+    return new JBImageIcon(image);
   }
 
   public static void setUseDarkIcons(boolean useDarkIcons) {
@@ -279,7 +279,7 @@
       Image img = createDisabled(image);
       if (UIUtil.isRetina()) img = RetinaImage.createFrom(img, 2, ImageLoader.ourComponent);
 
-      disabledIcon = new MyImageIcon(img);
+      disabledIcon = new JBImageIcon(img);
       ourIcon2DisabledIcon.put(icon, disabledIcon);
     }
     return disabledIcon;
@@ -383,19 +383,6 @@
     }
   }
 
-  private static final class MyImageIcon extends ImageIcon {
-    public MyImageIcon(final Image image) {
-      super(image);
-    }
-
-    @Override
-    public final synchronized void paintIcon(final Component c, final Graphics g, final int x, final int y) {
-      final ImageObserver observer = getImageObserver();
-
-      UIUtil.drawImage(g, getImage(), x, y, observer == null ? c : observer);
-    }
-  }
-
   public abstract static class LazyIcon implements Icon {
     private boolean myWasComputed;
     private Icon myIcon;
diff --git a/platform/util/src/com/intellij/openapi/util/ThreadLocalCachedIntArray.java b/platform/util/src/com/intellij/openapi/util/ThreadLocalCachedIntArray.java
new file mode 100644
index 0000000..581bb99
--- /dev/null
+++ b/platform/util/src/com/intellij/openapi/util/ThreadLocalCachedIntArray.java
@@ -0,0 +1,32 @@
+/*
+ * Copyright 2000-2014 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.util;
+
+import java.lang.ref.SoftReference;
+
+public final class ThreadLocalCachedIntArray {
+  private final ThreadLocal<SoftReference<int[]>> myThreadLocal = new ThreadLocal<SoftReference<int[]>>();
+
+  public int[] getBuffer(int size) {
+    int[] value = com.intellij.reference.SoftReference.dereference(myThreadLocal.get());
+    if (value == null || value.length <= size) {
+      value = new int[size];
+      myThreadLocal.set(new SoftReference<int[]>(value));
+    }
+
+    return value;
+  }
+}
\ No newline at end of file
diff --git a/platform/util/src/com/intellij/ui/Gray.java b/platform/util/src/com/intellij/ui/Gray.java
index 6370290..bd26bcf 100644
--- a/platform/util/src/com/intellij/ui/Gray.java
+++ b/platform/util/src/com/intellij/ui/Gray.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -31,6 +31,10 @@
   }
 
   public Color withAlpha(int alpha) {
+    if (alpha == 0) {
+      return TRANSPARENT;
+    }
+
     assert 0 <= alpha && alpha <= 255 : "Alpha " + alpha + "is incorrect. Alpha should be in range 0..255";
     return new Gray(getRed(), alpha);
   }
@@ -576,6 +580,9 @@
     _224, _225, _226, _227, _228, _229, _230, _231, _232, _233, _234, _235, _236, _237, _238, _239,
     _240, _241, _242, _243, _244, _245, _246, _247, _248, _249, _250, _251, _252, _253, _254, _255};
 
+  @SuppressWarnings("UseJBColor")
+  public static final Color TRANSPARENT = new Color(0,0,0,0);
+
   //public static void main(String[] args) {
   //  for (int i = 0; i < 256; i++) {
   //    System.out.println("public static final Gray _" + i + " = new Gray("+ i + ");");
diff --git a/platform/util/src/com/intellij/ui/JBGradientPaint.java b/platform/util/src/com/intellij/ui/JBGradientPaint.java
index 7b22d3d..6f511e7 100644
--- a/platform/util/src/com/intellij/ui/JBGradientPaint.java
+++ b/platform/util/src/com/intellij/ui/JBGradientPaint.java
@@ -37,6 +37,7 @@
     super(getX1(c, direction), getY1(c, direction), color1, getX2(c, direction), getY2(c, direction), color2);
   }
 
+  @SuppressWarnings("UnusedParameters")
   private static float getX1(JComponent c, GradientDirection d) {
     return 0;
   }
diff --git a/platform/util/src/com/intellij/ui/TransparentPanel.java b/platform/util/src/com/intellij/ui/TransparentPanel.java
new file mode 100644
index 0000000..a663e1b
--- /dev/null
+++ b/platform/util/src/com/intellij/ui/TransparentPanel.java
@@ -0,0 +1,57 @@
+/*
+ * Copyright 2000-2014 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.ui;
+
+import javax.swing.*;
+import java.awt.*;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+@SuppressWarnings("UnusedDeclaration")
+public class TransparentPanel extends JPanel {
+  private float myOpacity;
+
+  public TransparentPanel(float opacity, LayoutManager layout) {
+    super(layout);
+    if (opacity > 1.0 || opacity < 0.0) {
+      throw new IllegalArgumentException("Opacity should be in range [0.0 .. 1.0]");
+    }
+    myOpacity = opacity;
+  }
+
+  public TransparentPanel(float opacity) {
+    myOpacity = opacity;
+  }
+
+  public TransparentPanel() {
+    myOpacity = 0.7f;
+  }
+
+  public float getOpacity() {
+    return myOpacity;
+  }
+
+  public void setOpacity(float opacity) {
+    myOpacity = opacity;
+  }
+
+  @Override
+  public void paint(Graphics g) {
+    ((Graphics2D)g).setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, myOpacity));
+    super.paint(g);
+  }
+}
diff --git a/platform/util/src/com/intellij/util/PathMappingSettings.java b/platform/util/src/com/intellij/util/PathMappingSettings.java
index 438ae23..9bdd987 100644
--- a/platform/util/src/com/intellij/util/PathMappingSettings.java
+++ b/platform/util/src/com/intellij/util/PathMappingSettings.java
@@ -45,7 +45,7 @@
     List<PathMapping> result = ContainerUtil.newArrayList();
     if (mappings != null) {
       for (PathMapping m : mappings) {
-        if (m != null && !isEmpty(m.myLocalRoot, m.myRemoteRoot)) {
+        if (m != null && !areBothEmpty(m.myLocalRoot, m.myRemoteRoot)) {
           result.add(m);
         }
       }
@@ -65,6 +65,10 @@
     return result;
   }
 
+  public boolean isEmpty() {
+    return myPathMappings.isEmpty();
+  }
+
   private static class BestMappingSelector {
     private int myBestWeight = -1;
     private PathMapping myBest = null;
@@ -116,7 +120,7 @@
   }
 
   public void add(PathMapping mapping) {
-    if (isEmpty(mapping.myLocalRoot, mapping.myRemoteRoot)) {
+    if (areBothEmpty(mapping.myLocalRoot, mapping.myRemoteRoot)) {
       return;
     }
     myPathMappings.add(mapping);
@@ -124,7 +128,7 @@
 
   public void addMapping(String local, String remote) {
     PathMapping mapping = new PathMapping(local, remote);
-    if (isEmpty(mapping.myLocalRoot, mapping.myRemoteRoot)) {
+    if (areBothEmpty(mapping.myLocalRoot, mapping.myRemoteRoot)) {
       return;
     }
     myPathMappings.add(mapping);
@@ -175,7 +179,7 @@
 
   @NotNull
   public static String mapToLocal(String path, String remoteRoot, String localRoot) {
-    if (isEmpty(localRoot, remoteRoot)) {
+    if (areBothEmpty(localRoot, remoteRoot)) {
       return path;
     }
     path = norm(path);
@@ -184,7 +188,7 @@
     return path;
   }
 
-  public static boolean isEmpty(String localRoot, String remoteRoot) {
+  public static boolean areBothEmpty(String localRoot, String remoteRoot) {
     return StringUtil.isEmpty(localRoot) || StringUtil.isEmpty(remoteRoot);
   }
 
@@ -305,7 +309,7 @@
     }
 
     private boolean isEmpty() {
-      return PathMappingSettings.isEmpty(myLocalRoot, myRemoteRoot);
+      return PathMappingSettings.areBothEmpty(myLocalRoot, myRemoteRoot);
     }
 
     private static String trimSlash(String s) {
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentBitSet.java b/platform/util/src/com/intellij/util/containers/ConcurrentBitSet.java
index cc134cd..d7542a7 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentBitSet.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentBitSet.java
@@ -407,13 +407,21 @@
     StringBuilder b = new StringBuilder();
     b.append('{');
 
-    int i = nextSetBit(0);
-    if (i != -1) {
-      b.append(i);
-      for (i = nextSetBit(i + 1); i >= 0; i = nextSetBit(i + 1)) {
-        int endOfRun = nextClearBit(i);
+    for (int i = nextSetBit(0); i >= 0; i = nextSetBit(i + 1)) {
+      int endOfRun = nextClearBit(i);
+      if (endOfRun - i > 1) {
+        if (b.length() != 1) {
+          b.append(", ");
+        }
+        b.append(i).append("...").append(endOfRun-1);
+        i = endOfRun;
+      }
+      else {
         do {
-          b.append(", ").append(i);
+          if (b.length() != 1) {
+            b.append(", ");
+          }
+          b.append(i);
         }
         while (++i < endOfRun);
       }
diff --git a/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java b/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java
deleted file mode 100644
index d73a732..0000000
--- a/platform/util/src/com/intellij/util/containers/VariableWidthIntArray.java
+++ /dev/null
@@ -1,133 +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.util.containers;
-
-import com.intellij.openapi.diagnostic.Logger;
-
-/**
- * @author Dmitry.Shtukenberg
- */
-public final class VariableWidthIntArray implements Cloneable {
-  private static final Logger LOG = Logger.getInstance("#com.intellij.util.containers.VariableWidthIntArray");
-
-  private int[] intArray = null;
-  private short[] shortArray = null;
-  private byte[] byteArray = null;
-
-  private final int minValue;
-  private final int maxValue;
-
-  static final int INT = 1;
-  static final int SHORT = 2;
-  static final int BYTE = 3;
-  private final int arrayType;
-
-  public VariableWidthIntArray( int minValue, int maxValue, int initialCapacity ) {
-    this.minValue = minValue;
-    this.maxValue = maxValue;
-
-    if( minValue < Short.MIN_VALUE || maxValue > Short.MAX_VALUE ) {
-      intArray = new int[ bestSize(initialCapacity) ];
-      arrayType = INT;
-    }
-    else if( minValue < Byte.MIN_VALUE || maxValue > Byte.MAX_VALUE ) {
-      shortArray = new short[ bestSize(initialCapacity) ];
-      arrayType = SHORT;
-    }
-    else {
-      byteArray = new byte[ bestSize(initialCapacity) ];
-      arrayType = BYTE;
-    }
-  }
-
-  static int bestSize( int maxSize ) {
-    int newSize = (int)(((double)maxSize) * 5 / 4);
-    return newSize <= maxSize ? maxSize + 1 : newSize;
-  }
-
-  public void ensureArraySize( int index ) {
-    if( intArray != null && intArray.length <= index ) {
-      int[] tmp = new int[ bestSize(index) ];
-      System.arraycopy( intArray, 0, tmp, 0, intArray.length );
-      intArray = tmp;
-    }
-    else if( shortArray != null && shortArray.length <= index ) {
-      short[] tmp = new short[ bestSize(index) ];
-      System.arraycopy( shortArray, 0, tmp, 0, shortArray.length );
-      shortArray = tmp;
-    }
-    else if( byteArray.length <= index ) {
-      byte[] tmp = new byte[ bestSize(index) ];
-      System.arraycopy( byteArray, 0, tmp, 0, byteArray.length );
-      byteArray = tmp;
-    }
-  }
-
-  public int get( int index ) {
-    switch( arrayType ) {
-      case INT: return intArray[index];
-      case SHORT: return shortArray[index];
-      case BYTE: return byteArray[index];
-    }
-    LOG.error("No array allocated");
-    return 0;
-  }
-
-  public void put( int index, int value ) {
-    if( value < minValue || value > maxValue ) {
-      LOG.error("Value out of domain");
-    }
-
-    switch( arrayType ) {
-      case INT: intArray[index] = value; return;
-      case SHORT: shortArray[index] = (short)value; return;
-      case BYTE: byteArray[index] = (byte)value; return;
-    }
-
-    LOG.error("No array allocated");
-  }
-
-  @Override
-  public Object clone() throws CloneNotSupportedException {
-    VariableWidthIntArray arr = (VariableWidthIntArray)super.clone();
-    if( intArray != null ) { arr.intArray = intArray.clone(); }
-    if( shortArray != null ) { arr.shortArray = shortArray.clone(); }
-    if( byteArray != null ) { arr.byteArray = byteArray.clone(); }
-    return arr;
-  }
-
-  public void arraycopy(int[] src, int from, int to, int count) {
-    for( int i = 0; i < count; i++ )
-      put( i + to, src[i + from] );
-  }
-
-  public void move(int from, int to, int count) {
-    switch( arrayType ) {
-      case INT: System.arraycopy( intArray, from, intArray, to, count ); break;
-      case SHORT: System.arraycopy( shortArray, from, shortArray, to, count ); break;
-      case BYTE: System.arraycopy( byteArray, from, byteArray, to, count ); break;
-      default:
-        LOG.error("Invalid array type");
-    }
-  }
-
-  public boolean arrayequal( VariableWidthIntArray src, int srcfrom, int from, int count ) {
-    if( src.arrayType != arrayType ) return false;
-    for( int i = 0; i < count; i++ )
-      if( get(from+i) != src.get(srcfrom+i)) return false;
-    return true;
-  }
-}
diff --git a/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java b/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java
index b0b30fe..e4a1f5c 100644
--- a/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java
+++ b/platform/util/src/com/intellij/util/io/DataInputOutputUtil.java
@@ -55,6 +55,22 @@
     }
   }
 
+  public static long readLONG(@NotNull DataInput record) throws IOException {
+    final int val = record.readUnsignedByte();
+    if (val < 192) {
+      return val;
+    }
+
+    long res = val - 192;
+    for (int sh = 6; ; sh += 7) {
+      int next = record.readUnsignedByte();
+      res |= (long)(next & 0x7F) << sh;
+      if ((next & 0x80) == 0) {
+        return res;
+      }
+    }
+  }
+
   public static void writeINT(@NotNull DataOutput record, int val) throws IOException {
     if (0 <= val && val < 192) {
       record.writeByte(val);
@@ -70,6 +86,21 @@
     }
   }
 
+  public static void writeLONG(@NotNull DataOutput record, long val) throws IOException {
+    if (0 <= val && val < 192) {
+      record.writeByte((int)val);
+    }
+    else {
+      record.writeByte(192 + (int)(val & 0x3F));
+      val >>>= 6;
+      while (val >= 128) {
+        record.writeByte((int)(val & 0x7F) | 0x80);
+        val >>>= 7;
+      }
+      record.writeByte((int)val);
+    }
+  }
+
   public static int readSINT(@NotNull DataInput record) throws IOException {
     return readINT(record) - 64;
   }
diff --git a/platform/util/src/com/intellij/util/io/IntToIntBtree.java b/platform/util/src/com/intellij/util/io/IntToIntBtree.java
index 5820c9f..f074d36 100644
--- a/platform/util/src/com/intellij/util/io/IntToIntBtree.java
+++ b/platform/util/src/com/intellij/util/io/IntToIntBtree.java
@@ -73,7 +73,7 @@
       FileUtil.delete(file);
     }
 
-    storage = new ResizeableMappedFile(file, pageSize, storageLockContext, 1024 * 1024, true, IOUtil.ourByteBuffersUseNativeByteOrder);
+    storage = new ResizeableMappedFile(file, pageSize, storageLockContext, pageSize, true, IOUtil.ourByteBuffersUseNativeByteOrder);
     root = new BtreeIndexNodeView(this);
 
     if (initial) {
@@ -95,7 +95,7 @@
 
       hashPageCapacity = i;
       metaPageLen = BtreePage.RESERVED_META_PAGE_LEN;
-      i = (int)(hashPageCapacity * 0.8);
+      i = (int)(hashPageCapacity * 0.9);
       if ((i & 1) == 1) ++i;
     } else {
       hashPageCapacity = -1;
diff --git a/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java b/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java
index 219544b..a202cd8 100644
--- a/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java
+++ b/platform/util/src/com/intellij/util/io/PersistentBTreeEnumerator.java
@@ -24,7 +24,7 @@
 
 public class PersistentBTreeEnumerator<Data> extends PersistentEnumeratorBase<Data> {
   private static final int PAGE_SIZE;
-  private static final int DEFAULT_PAGE_SIZE = 4096;
+  private static final int DEFAULT_PAGE_SIZE = 32768;
 
   static {
     int pageSize;
diff --git a/platform/util/src/com/intellij/util/io/PersistentHashMapValueStorage.java b/platform/util/src/com/intellij/util/io/PersistentHashMapValueStorage.java
index 5c76742..c0318ba 100644
--- a/platform/util/src/com/intellij/util/io/PersistentHashMapValueStorage.java
+++ b/platform/util/src/com/intellij/util/io/PersistentHashMapValueStorage.java
@@ -352,23 +352,15 @@
   }
 
   private long readPrevChunkAddress(long chunk) throws IOException {
-    final int prevOffsetDiff = DataInputOutputUtil.readINT(myBufferDataStreamWrapper);
-    if (prevOffsetDiff < 0) {
-      return chunk - (-prevOffsetDiff | ((long)DataInputOutputUtil.readINT(myBufferDataStreamWrapper) << 32));
-    }
+    final long prevOffsetDiff = DataInputOutputUtil.readLONG(myBufferDataStreamWrapper);
     assert prevOffsetDiff < chunk;
     return prevOffsetDiff != 0 ? chunk - prevOffsetDiff : 0;
   }
 
   private static void writePrevChunkAddress(long prevChunkAddress, long currentChunkAddress, DataOutputStream dataOutputStream) throws IOException {
+    assert currentChunkAddress >= prevChunkAddress;
     long diff = currentChunkAddress - prevChunkAddress;
-
-    if (diff < Integer.MAX_VALUE || prevChunkAddress == 0)
-      DataInputOutputUtil.writeINT(dataOutputStream, prevChunkAddress == 0 ? 0 : (int)diff);
-    else {
-      DataInputOutputUtil.writeINT(dataOutputStream, -(int)diff);
-      DataInputOutputUtil.writeINT(dataOutputStream, (int)(diff >>> 32));
-    }
+    DataInputOutputUtil.writeLONG(dataOutputStream, prevChunkAddress == 0 ? 0 : diff);
   }
 
   public long getSize() {
diff --git a/platform/util/src/com/intellij/util/ui/JBImageIcon.java b/platform/util/src/com/intellij/util/ui/JBImageIcon.java
new file mode 100644
index 0000000..8d8bc6e
--- /dev/null
+++ b/platform/util/src/com/intellij/util/ui/JBImageIcon.java
@@ -0,0 +1,38 @@
+/*
+ * Copyright 2000-2014 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.util.ui;
+
+import javax.swing.*;
+import java.awt.*;
+import java.awt.image.ImageObserver;
+
+/**
+ * HiDPI-aware image icon
+ *
+ * @author Konstantin Bulenkov
+ */
+public class JBImageIcon extends ImageIcon {
+  public JBImageIcon(Image image) {
+    super(image);
+  }
+
+  @Override
+  public final synchronized void paintIcon(final Component c, final Graphics g, final int x, final int y) {
+    final ImageObserver observer = getImageObserver();
+
+    UIUtil.drawImage(g, getImage(), x, y, observer == null ? c : observer);
+  }
+}
diff --git a/platform/util/src/com/intellij/util/ui/ThreeStateCheckBox.java b/platform/util/src/com/intellij/util/ui/ThreeStateCheckBox.java
index 37aedba..49d7638 100644
--- a/platform/util/src/com/intellij/util/ui/ThreeStateCheckBox.java
+++ b/platform/util/src/com/intellij/util/ui/ThreeStateCheckBox.java
@@ -26,7 +26,7 @@
   private State myState;
   private boolean myThirdStateEnabled = true;
 
-  public static enum State {
+  public enum State {
     SELECTED, NOT_SELECTED, DONT_CARE
   }
 
diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java
index 59272d4..f0a900b 100644
--- a/platform/util/src/com/intellij/util/ui/UIUtil.java
+++ b/platform/util/src/com/intellij/util/ui/UIUtil.java
@@ -384,6 +384,10 @@
   }
 
   public static void setEnabled(Component component, boolean enabled, boolean recursively) {
+    setEnabled(component, enabled, recursively, false);
+  }
+
+  public static void setEnabled(Component component, boolean enabled, boolean recursively, boolean visibleOnly) {
     component.setEnabled(enabled);
     if (component instanceof JComboBox && isUnderAquaLookAndFeel()) {
       // On Mac JComboBox instances have children: com.apple.laf.AquaComboBoxButton and javax.swing.CellRendererPane.
@@ -401,7 +405,9 @@
         final Container container = (Container)component;
         final int subComponentCount = container.getComponentCount();
         for (int i = 0; i < subComponentCount; i++) {
-          setEnabled(container.getComponent(i), enabled, recursively);
+          Component child = container.getComponent(i);
+          if (visibleOnly && !child.isVisible()) continue;
+          setEnabled(child, enabled, recursively, visibleOnly);
         }
       }
     }
@@ -2937,4 +2943,10 @@
     }
     return genericFontFamily;
   }
+
+  @NotNull
+  public static String rightArrow() {
+    char rightArrow = '\u2192';
+    return getLabelFont().canDisplay(rightArrow) ? String.valueOf(rightArrow) : "->";
+  }
 }
diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java
index e2f9484..6cc4b7c 100644
--- a/platform/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java
+++ b/platform/vcs-api/src/com/intellij/openapi/vcs/VcsVFSListener.java
@@ -41,7 +41,7 @@
  * @author yole
  */
 public abstract class VcsVFSListener implements Disposable {
-  private VcsDirtyScopeManager myDirtyScopeManager;
+  private final VcsDirtyScopeManager myDirtyScopeManager;
   private final ProjectLevelVcsManager myVcsManager;
   private final VcsFileListenerContextHelper myVcsFileListenerContextHelper;
 
@@ -72,7 +72,7 @@
 
   protected enum VcsDeleteType {SILENT, CONFIRM, IGNORE}
 
-  protected VcsVFSListener(final Project project, final AbstractVcs vcs) {
+  protected VcsVFSListener(@NotNull Project project, @NotNull AbstractVcs vcs) {
     myProject = project;
     myVcs = vcs;
     myChangeListManager = ChangeListManager.getInstance(project);
@@ -90,6 +90,7 @@
     myVcsFileListenerContextHelper = VcsFileListenerContextHelper.getInstance(myProject);
   }
 
+  @Override
   public void dispose() {
   }
 
@@ -104,7 +105,7 @@
 
   private boolean isUnderMyVcs(VirtualFile file) {
     return myVcsManager.getVcsFor(file) == myVcs &&
-           (myVcsManager.isFileInContent(file)) &&
+           myVcsManager.isFileInContent(file) &&
            !myChangeListManager.isIgnoredFile(file);
   }
 
@@ -314,13 +315,15 @@
   protected abstract boolean isDirectoryVersioningSupported();
 
   private class MyVirtualFileAdapter extends VirtualFileAdapter {
+    @Override
     public void fileCreated(@NotNull final VirtualFileEvent event) {
       VirtualFile file = event.getFile();
       if (isUnderMyVcs(file)) {
-        VcsVFSListener.this.fileAdded(event, file);
+        fileAdded(event, file);
       }
     }
 
+    @Override
     public void fileCopied(@NotNull final VirtualFileCopyEvent event) {
       if (isEventIgnored(event, true) || myChangeListManager.isIgnoredFile(event.getFile())) return;
       final AbstractVcs oldVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getOriginalFile());
@@ -336,6 +339,7 @@
       }
     }
 
+    @Override
     public void beforeFileDeletion(@NotNull final VirtualFileEvent event) {
       final VirtualFile file = event.getFile();
       if (isEventIgnored(event, true)) {
@@ -357,6 +361,7 @@
       }
     }
 
+    @Override
     public void beforeFileMovement(@NotNull final VirtualFileMoveEvent event) {
       if (isEventIgnored(event, true)) return;
       final VirtualFile file = event.getFile();
@@ -369,6 +374,7 @@
       }
     }
 
+    @Override
     public void fileMoved(@NotNull final VirtualFileMoveEvent event) {
       if (isEventIgnored(event, true)) return;
       final AbstractVcs oldVcs = ProjectLevelVcsManager.getInstance(myProject).getVcsFor(event.getOldParent());
@@ -377,6 +383,7 @@
       }
     }
 
+    @Override
     public void beforePropertyChange(@NotNull final VirtualFilePropertyEvent event) {
       if (!isEventIgnored(event, false) && event.getPropertyName().equalsIgnoreCase(VirtualFile.PROP_NAME)) {
         String oldName = (String)event.getOldValue();
@@ -406,6 +413,7 @@
   private class MyCommandAdapter extends CommandAdapter {
     private int myCommandLevel;
 
+    @Override
     public void commandStarted(final CommandEvent event) {
       if (myProject != event.getProject()) return;
       myCommandLevel++;
@@ -457,6 +465,7 @@
       }
     }
 
+    @Override
     public void commandFinished(final CommandEvent event) {
       if (myProject != event.getProject()) return;
       myCommandLevel--;
diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/ContentRevisionVirtualFile.java b/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/ContentRevisionVirtualFile.java
index 6f5a848..71626fa 100644
--- a/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/ContentRevisionVirtualFile.java
+++ b/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/ContentRevisionVirtualFile.java
@@ -84,8 +84,7 @@
 
       myModificationStamp++;
       setRevision(myContentRevision.getRevisionNumber().asString());
-      final ByteBuffer byteBuffer = getCharset().encode(content);
-      myContent = byteBuffer.compact().array();
+      myContent = content.getBytes(getCharset());
       ApplicationManager.getApplication().runWriteAction(new Runnable() {
         public void run() {
           vcsFileSystem.fireContentsChanged(this, ContentRevisionVirtualFile.this, 0);
diff --git a/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsFileSystem.java b/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsFileSystem.java
index 45f9b27..8cea93b 100644
--- a/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsFileSystem.java
+++ b/platform/vcs-api/src/com/intellij/openapi/vcs/vfs/VcsFileSystem.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -83,6 +83,7 @@
     throw new RuntimeException(COULD_NOT_IMPLEMENT_MESSAGE);
   }
 
+  @NotNull
   @Override
   public VirtualFile copyFile(Object requestor, @NotNull VirtualFile vFile, @NotNull VirtualFile newParent, @NotNull final String copyName) throws IOException {
     throw new RuntimeException(COULD_NOT_IMPLEMENT_MESSAGE);
@@ -93,6 +94,7 @@
     throw new RuntimeException(COULD_NOT_IMPLEMENT_MESSAGE);
   }
 
+  @NotNull
   @Override
   public VirtualFile createChildFile(Object requestor, @NotNull VirtualFile vDir, @NotNull String fileName) throws IOException {
     throw new RuntimeException(COULD_NOT_IMPLEMENT_MESSAGE);
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java
index 5165081..5c8e0ab 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/FilePathImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2012 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.
@@ -62,8 +62,7 @@
     }
   }
 
-  @NotNull
-  private static File fileFromVirtual(VirtualFile virtualParent, final VirtualFile child, @NotNull String name) {
+  private static File fileFromVirtual(VirtualFile virtualParent, final VirtualFile child, String name) {
     assert virtualParent != null || child != null;
     if (virtualParent != null) {
       return new File(virtualParent.getPath(), name);
@@ -72,12 +71,12 @@
   }
 
   @Heavy
-  public FilePathImpl(@NotNull VirtualFile virtualParent, @NotNull String name, final boolean isDirectory) {
+  public FilePathImpl(@NotNull VirtualFile virtualParent, String name, final boolean isDirectory) {
     this(virtualParent, name, isDirectory, null, false);
   }
 
   @Heavy
-  private FilePathImpl(@NotNull VirtualFile virtualParent, @NotNull String name, final boolean isDirectory, final boolean forDeleted) {
+  private FilePathImpl(@NotNull VirtualFile virtualParent, String name, final boolean isDirectory, final boolean forDeleted) {
     this(virtualParent, name, isDirectory, null, forDeleted);
   }
 
@@ -96,15 +95,15 @@
     this(virtualFile.getParent(), virtualFile.getName(), virtualFile.isDirectory(), virtualFile, false);
   }
 
-  @NotNull
   public FilePath createChild(final String subPath, final boolean isDirectory) {
     if (StringUtil.isEmptyOrSpaces(subPath)) return this;
 
-    VirtualFile virtualFile = getVirtualFile();
-    if (virtualFile != null && subPath.indexOf('/') == -1 && subPath.indexOf('\\') == -1) {
-      return new FilePathImpl(virtualFile, subPath, isDirectory, true);
+    if (getVirtualFile() != null && subPath.indexOf('/') == -1 && subPath.indexOf('\\') == -1) {
+      return new FilePathImpl(getVirtualFile(), subPath, isDirectory, true);
     }
-    return new FilePathImpl(new File(getIOFile(), subPath), isDirectory);
+    else {
+      return new FilePathImpl(new File(getIOFile(), subPath), isDirectory);
+    }
   }
 
   public int hashCode() {
@@ -115,13 +114,13 @@
     if (!(o instanceof FilePath)) {
       return false;
     }
-    if (!isSpecialName(myName) && !isSpecialName(((FilePath)o).getName()) &&
-        !Comparing.equal(myName, ((FilePath)o).getName())) {
-      return false;
+    else {
+      if (! isSpecialName(myName) && ! isSpecialName(((FilePath)o).getName()) &&
+          ! Comparing.equal(myName, ((FilePath)o).getName())) return false;
+      return myFile.equals(((FilePath)o).getIOFile());
     }
-    return myFile.equals(((FilePath)o).getIOFile());
   }
-
+  
   private static boolean isSpecialName(final String name) {
     return ".".equals(name) || "..".equals(name);
   }
@@ -129,29 +128,31 @@
   @Override
   public void refresh() {
     if (myLocal) {
-      VirtualFile virtualParent = getVirtualFileParent();
-      myVirtualFile = virtualParent == null ? LocalFileSystem.getInstance().findFileByIoFile(myFile) : virtualParent.findChild(myName);
+      if (myVirtualParent == null) {
+        myVirtualFile = LocalFileSystem.getInstance().findFileByIoFile(myFile);
+      }
+      else {
+        myVirtualFile = myVirtualParent.findChild(myName);
+      }
     }
   }
 
   @Override
   public void hardRefresh() {
-    if (myLocal) {
-      VirtualFile virtualFile = getVirtualFile();
-      if (virtualFile == null || !virtualFile.isValid()) {
-        myVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(myFile);
-      }
+    if (myLocal && (myVirtualFile == null || ! myVirtualFile.isValid())) {
+      myVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(myFile);
     }
   }
 
-  @NotNull
   @Override
   public String getPath() {
-    final VirtualFile virtualFile = getVirtualFile();
+    final VirtualFile virtualFile = myVirtualFile;
     if (virtualFile != null && virtualFile.isValid()) {
       return virtualFile.getPath();
     }
-    return myFile.getPath();
+    else {
+      return myFile.getPath();
+    }
   }
 
   public void setIsDirectory(boolean isDirectory) {
@@ -160,17 +161,20 @@
 
   @Override
   public boolean isDirectory() {
-    VirtualFile virtualFile = getVirtualFile();
-    return virtualFile == null ? myIsDirectory : virtualFile.isDirectory();
+    if (myVirtualFile == null) {
+      return myIsDirectory;
+    }
+    else {
+      return myVirtualFile.isDirectory();
+    }
   }
 
   @Override
-  public boolean isUnder(@NotNull FilePath parent, boolean strict) {
-    VirtualFile virtualFile = getVirtualFile();
-    if (virtualFile != null) {
+  public boolean isUnder(FilePath parent, boolean strict) {
+    if (myVirtualFile != null) {
       final VirtualFile parentFile = parent.getVirtualFile();
       if (parentFile != null) {
-        return VfsUtilCore.isAncestor(parentFile, virtualFile, strict);
+        return VfsUtilCore.isAncestor(parentFile, myVirtualFile, strict);
       }
     }
     return FileUtil.isAncestor(parent.getIOFile(), getIOFile(), strict);
@@ -178,9 +182,8 @@
 
   @Override
   public FilePath getParentPath() {
-    VirtualFile virtualParent = getVirtualFileParent();
-    if (virtualParent != null && virtualParent.getParent() != null) {
-      return new FilePathImpl(virtualParent);
+    if (myVirtualParent != null && myVirtualParent.isValid() && myVirtualParent.getParent() != null) {
+      return new FilePathImpl(myVirtualParent);
     }
 
     // can't use File.getParentPath() because the path may not correspond to an actual file on disk,
@@ -197,25 +200,19 @@
   @Override
   @Nullable
   public VirtualFile getVirtualFile() {
-    VirtualFile virtualFile = myVirtualFile;
-    if (virtualFile != null && !virtualFile.isValid()) {
-      myVirtualFile = virtualFile = null;
+    if (myVirtualFile != null && !myVirtualFile.isValid()) {
+      myVirtualFile = null;
     }
-    if (virtualFile == null) {
-      refresh();
-      virtualFile = myVirtualFile;
-    }
-    return virtualFile;
+    return myVirtualFile;
   }
 
   @Override
   @Nullable
   public VirtualFile getVirtualFileParent() {
-    VirtualFile virtualParent = myVirtualParent;
-    if (virtualParent != null && !virtualParent.isValid()) {
-      myVirtualParent = virtualParent = null;
+    if (myVirtualParent != null && !myVirtualParent.isValid()) {
+      myVirtualParent = null;
     }
-    return virtualParent;
+    return myVirtualParent;
   }
 
   @Override
@@ -224,7 +221,6 @@
     return myFile;
   }
 
-  @NotNull
   @Override
   public String getName() {
     return myName;
@@ -232,21 +228,21 @@
 
   @Override
   public String getPresentableUrl() {
-    VirtualFile virtualFile = getVirtualFile();
-    if (virtualFile == null || !virtualFile.isValid()) {
+    if (myVirtualFile == null || !myVirtualFile.isValid()) {
       return myFile.getAbsolutePath();
     }
-    return virtualFile.getPresentableUrl();
+    else {
+      return myVirtualFile.getPresentableUrl();
+    }
   }
 
   @Override
   @Nullable
   public Document getDocument() {
-    VirtualFile virtualFile = getVirtualFile();
-    if (virtualFile == null || virtualFile.getFileType().isBinary()) {
+    if (myVirtualFile == null || myVirtualFile.getFileType().isBinary()) {
       return null;
     }
-    return FileDocumentManager.getInstance().getDocument(virtualFile);
+    return FileDocumentManager.getInstance().getDocument(myVirtualFile);
   }
 
   @Override
@@ -257,8 +253,7 @@
   @Override
   public Charset getCharset(Project project) {
     // try to find existing virtual file
-    VirtualFile virtualFile = getVirtualFile();
-    VirtualFile existing = virtualFile != null && virtualFile.isValid() ? virtualFile : null;
+    VirtualFile existing = myVirtualFile != null && myVirtualFile.isValid() ? myVirtualFile : null;
     if (existing == null) {
       LocalFileSystem lfs = LocalFileSystem.getInstance();
       for (File f = myFile; f != null; f = f.getParentFile()) {
@@ -283,8 +278,7 @@
 
   @Override
   public FileType getFileType() {
-    VirtualFile virtualFile = getVirtualFile();
-    return virtualFile != null ? virtualFile.getFileType() : FileTypeManager.getInstance().getFileTypeByFileName(myFile.getName());
+    return myVirtualFile != null ? myVirtualFile.getFileType() : FileTypeManager.getInstance().getFileTypeByFileName(myFile.getName());
   }
 
   public static FilePathImpl create(VirtualFile file) {
@@ -322,52 +316,59 @@
     if (virtualFileParent != null) {
       return new FilePathImpl(virtualFileParent, selectedFile.getName(), isDirectory, true);
     }
-    return new FilePathImpl(selectedFile, isDirectory);
+    else {
+      return new FilePathImpl(selectedFile, isDirectory);
+    }
   }
 
-  public static FilePath createOn(@NotNull String s) {
+  public static FilePath createOn(String s) {
     File ioFile = new File(s);
     final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
     VirtualFile virtualFile = localFileSystem.findFileByIoFile(ioFile);
     if (virtualFile != null) {
       return new FilePathImpl(virtualFile);
     }
-    VirtualFile virtualFileParent = localFileSystem.findFileByIoFile(ioFile.getParentFile());
-    if (virtualFileParent == null) return null;
-    return new FilePathImpl(virtualFileParent, ioFile.getName(), false);
+    else {
+      VirtualFile virtualFileParent = localFileSystem.findFileByIoFile(ioFile.getParentFile());
+      if (virtualFileParent != null) {
+        return new FilePathImpl(virtualFileParent, ioFile.getName(), false);
+      }
+      else {
+        return null;
+      }
+    }
   }
 
-  private static final Constructor<File> ourFileStringConstructor;
-  static {
-    // avoid filename normalization (IDEADEV-10548)
-    Constructor<File> constructor = null; // new File(String, int)
-    try {
-      constructor = File.class.getDeclaredConstructor(String.class, int.class);
-      constructor.setAccessible(true);
-    }
-    catch (Exception ignored) {
-    }
-    ourFileStringConstructor = constructor;
-  }
+  private static Constructor<File> ourFileStringConstructor;
+  private static boolean ourFileStringConstructorInitialized;
 
   @NotNull
-  public static FilePath createNonLocal(@NotNull String path, final boolean directory) {
+  public static FilePath createNonLocal(String path, final boolean directory) {
     path = path.replace('/', File.separatorChar);
-    File file = createIoFile(path);
-    return new FilePathImpl(file, directory, false);
-  }
-
-  @NotNull
-  private static File createIoFile(@NotNull String path) {
-    if (ourFileStringConstructor != null) {
+    // avoid filename normalization (IDEADEV-10548)
+    if (!ourFileStringConstructorInitialized) {
+      ourFileStringConstructorInitialized = true;
       try {
-        return ourFileStringConstructor.newInstance(path, 1);
+        ourFileStringConstructor = File.class.getDeclaredConstructor(String.class, int.class);
+        ourFileStringConstructor.setAccessible(true);
       }
       catch (Exception ex) {
-        // reflection call failed, try regular call
+        ourFileStringConstructor = null;
       }
     }
-    return new File(path);
+    File file = null;
+    try {
+      if (ourFileStringConstructor != null) {
+        file = ourFileStringConstructor.newInstance(path, 1);
+      }
+    }
+    catch (Exception ex) {
+      // reflection call failed, try regular call
+    }
+    if (file == null) {
+      file = new File(path);
+    }
+    return new FilePathImpl(file, directory, false);
   }
 
   @Override
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/TreeModelBuilder.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/TreeModelBuilder.java
index ba022cb..48a17ae 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/TreeModelBuilder.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/TreeModelBuilder.java
@@ -504,7 +504,8 @@
 
     ChangesBrowserNode parentNode = myFoldersCache.get(parentPath.getKey());
     if (parentNode == null) {
-      parentNode = ChangesBrowserNode.create(myProject, new FilePathImpl(new File(parentPath.getPath()), true));
+      FilePathImpl filePath = parentPath.getVf() == null ? new FilePathImpl(new File(parentPath.getPath()), true) : new FilePathImpl(parentPath.getVf());
+      parentNode = ChangesBrowserNode.create(myProject, filePath);
       ChangesBrowserNode grandPa = getParentNodeFor(parentPath, policy, rootNode);
       model.insertNodeInto(parentNode, grandPa, grandPa.getChildCount());
       myFoldersCache.put(parentPath.getKey(), parentNode);
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java
index 87d7faa..904b070 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/ProjectLevelVcsManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -72,6 +72,7 @@
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
 
 import javax.swing.*;
 import java.awt.*;
@@ -896,4 +897,9 @@
   public ContentRevisionCache getContentRevisionCache() {
     return myContentRevisionCache;
   }
+
+  @TestOnly
+  public void waitForInitialized() {
+    myInitialization.waitForInitialized();
+  }
 }
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsInitialization.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsInitialization.java
index f0987ce..498f3d1 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsInitialization.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/impl/VcsInitialization.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -21,32 +21,34 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.startup.StartupManager;
 import com.intellij.openapi.util.Pair;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.TestOnly;
 
+import java.util.ArrayList;
 import java.util.Collections;
 import java.util.Comparator;
-import java.util.LinkedList;
 import java.util.List;
+import java.util.concurrent.Future;
 
 public class VcsInitialization {
   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.vcs.impl.VcsInitialization");
 
-  private final Project myProject;
-  private final List<Pair<VcsInitObject, Runnable>> myList;
+  private final List<Pair<VcsInitObject, Runnable>> myList = new ArrayList<Pair<VcsInitObject, Runnable>>();
   private final Object myLock;
   private boolean myInitStarted;
+  private volatile Future<?> myFuture;
 
-  public VcsInitialization(final Project project) {
+  public VcsInitialization(@NotNull final Project project) {
     myLock = new Object();
-    myProject = project;
-    myList = new LinkedList<Pair<VcsInitObject, Runnable>>();
 
-    StartupManager.getInstance(myProject).registerPostStartupActivity(new DumbAwareRunnable() {
+    StartupManager.getInstance(project).registerPostStartupActivity(new DumbAwareRunnable() {
+      @Override
       public void run() {
-        if (myProject.isDisposed()) return;
-        ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
+        if (project.isDisposed()) return;
+        myFuture = ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
           @Override
           public void run() {
-            if (!myProject.isDisposed()) {
+            if (!project.isDisposed()) {
               execute();
             }
           }
@@ -55,7 +57,7 @@
     });
   }
 
-  public void add(final VcsInitObject vcsInitObject, final Runnable runnable) {
+  public void add(@NotNull final VcsInitObject vcsInitObject, @NotNull final Runnable runnable) {
     synchronized (myLock) {
       if (myInitStarted) {
         if (! vcsInitObject.isCanBeLast()) {
@@ -76,12 +78,24 @@
       myInitStarted = true; // list would not be modified starting from this point
     }
     Collections.sort(list, new Comparator<Pair<VcsInitObject, Runnable>>() {
+      @Override
       public int compare(Pair<VcsInitObject, Runnable> o1, Pair<VcsInitObject, Runnable> o2) {
-        return new Integer(o1.getFirst().getOrder()).compareTo(new Integer(o2.getFirst().getOrder()));
+        return o1.getFirst().getOrder() - o2.getFirst().getOrder();
       }
     });
     for (Pair<VcsInitObject, Runnable> pair : list) {
       pair.getSecond().run();
     }
   }
+
+  @TestOnly
+  public void waitForInitialized() {
+    try {
+      myFuture.get();
+      myFuture = null;
+    }
+    catch (Exception e) {
+      throw new RuntimeException(e);
+    }
+  }
 }
diff --git a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/VcsTestUtil.java b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/VcsTestUtil.java
index 51b6fdd..63f54a8 100644
--- a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/VcsTestUtil.java
+++ b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/VcsTestUtil.java
@@ -1,3 +1,18 @@
+/*
+ * Copyright 2000-2014 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.vcs;
 
 import com.intellij.notification.Notification;
@@ -54,24 +69,17 @@
    * @param name   Name of the directory.
    * @return reference to the created or already existing directory.
    */
-  public static VirtualFile createDir(@NotNull Project project, @NotNull final VirtualFile parent, @NotNull final String name) {
-    final Ref<VirtualFile> result = new Ref<VirtualFile>();
-    new WriteCommandAction.Simple(project) {
+  public static VirtualFile createDir(@NotNull final Project project, @NotNull final VirtualFile parent, @NotNull final String name) {
+    return new WriteCommandAction<VirtualFile>(project) {
       @Override
-      protected void run() throws Throwable {
-        try {
-          VirtualFile dir = parent.findChild(name);
-          if (dir == null) {
-            dir = parent.createChildDirectory(this, name);
-          }
-          result.set(dir);
+      protected void run(@NotNull Result<VirtualFile> result) throws Throwable {
+        VirtualFile dir = parent.findChild(name);
+        if (dir == null) {
+          dir = parent.createChildDirectory(this, name);
         }
-        catch (IOException e) {
-          throw new RuntimeException(e);
-        }
+        result.setResult(dir);
       }
-    }.execute();
-    return result.get();
+    }.execute().throwException().getResultObject();
   }
 
   public static void renameFileInCommand(@NotNull Project project, @NotNull final VirtualFile file, @NotNull final String newName) {
diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerManagerImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerManagerImpl.java
index 3191f19..04ab04f 100644
--- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerManagerImpl.java
+++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebuggerManagerImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -64,7 +64,7 @@
   storages = {@Storage(
     file = StoragePathMacros.WORKSPACE_FILE)})
 public class XDebuggerManagerImpl extends XDebuggerManager
-  implements ProjectComponent, PersistentStateComponent<XDebuggerManagerImpl.XDebuggerState> {
+  implements NamedComponent, PersistentStateComponent<XDebuggerManagerImpl.XDebuggerState> {
   @NonNls public static final String COMPONENT_NAME = "XDebuggerManager";
   private final Project myProject;
   private final XBreakpointManagerImpl myBreakpointManager;
@@ -148,14 +148,6 @@
     return myProject;
   }
 
-  @Override
-  public void projectOpened() {
-  }
-
-  @Override
-  public void projectClosed() {
-  }
-
   @NotNull
   @Override
   public String getComponentName() {
@@ -163,14 +155,6 @@
   }
 
   @Override
-  public void initComponent() {
-  }
-
-  @Override
-  public void disposeComponent() {
-  }
-
-  @Override
   @NotNull
   public XDebugSession startSession(@NotNull final ProgramRunner runner,
                                     @NotNull final ExecutionEnvironment environment,
diff --git a/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataReferenceContributor.java b/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataReferenceContributor.java
index dbe3cf2..6211357 100644
--- a/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataReferenceContributor.java
+++ b/plugins/IdeaTestAssistant/src/com/intellij/testAssistant/TestDataReferenceContributor.java
@@ -120,7 +120,7 @@
 
     @NotNull
     @Override
-    protected ResolveResult[] innerResolve(boolean caseSensitive) {
+    protected ResolveResult[] innerResolve(boolean caseSensitive, @NotNull PsiFile containingFile) {
       if (getIndex() == 0 && StringUtil.startsWithChar(getText(), '$')) {
         if (PROJECT_ROOT_VARIABLE.equals(getText())) {
           final PsiDirectory projectPsiRoot = getProjectPsiRoot();
@@ -135,7 +135,7 @@
           }
         }
       }
-      return super.innerResolve(caseSensitive);
+      return super.innerResolve(caseSensitive, containingFile);
     }
 
     @Nullable
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml
index a9bfaa1..2b47e3a 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/META-INF/InspectionGadgets.xml
@@ -394,10 +394,6 @@
     <localInspection language="JAVA" shortName="AnonymousInnerClass" bundle="com.siyeh.InspectionGadgetsBundle" key="anonymous.inner.class.display.name"
                      groupBundle="messages.InspectionsBundle" groupKey="group.names.class.structure" enabledByDefault="false"
                      level="WARNING" implementationClass="com.siyeh.ig.classlayout.AnonymousInnerClassInspection"/>
-    <localInspection language="JAVA" suppressId="ClassWithoutPackageStatement" shortName="ClassInTopLevelPackage" bundle="com.siyeh.InspectionGadgetsBundle"
-                     key="class.in.top.level.package.display.name" groupBundle="messages.InspectionsBundle"
-                     groupKey="group.names.class.structure" enabledByDefault="false" level="WARNING"
-                     implementationClass="com.siyeh.ig.classlayout.ClassInTopLevelPackageInspection"/>
     <localInspection language="JAVA" suppressId="NonStaticInitializer" shortName="ClassInitializer" bundle="com.siyeh.InspectionGadgetsBundle"
                      key="class.initializer.display.name" groupBundle="messages.InspectionsBundle" groupKey="group.names.class.structure"
                      enabledByDefault="false" level="WARNING" implementationClass="com.siyeh.ig.classlayout.ClassInitializerInspection"/>
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspection.java
index fc0a725..0902805 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2013 Dave Griffith, Bas Leijdekkers
+ * Copyright 2003-2014 Dave Griffith, Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -60,20 +60,51 @@
     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 boolean staticEqualsCall;
+      if (MethodCallUtils.isEqualsCall(expression)) {
+        staticEqualsCall = false;
+      }
+      else {
+        final String name = methodExpression.getReferenceName();
+        if (!"equals".equals(name) && !"equal".equals(name)) {
+          return;
+        }
+        final PsiMethod method = expression.resolveMethod();
+        if (method == null) {
+          return;
+        }
+        final PsiClass aClass = method.getContainingClass();
+        if (aClass == null) {
+          return;
+        }
+        final String qualifiedName = aClass.getQualifiedName();
+        if (!"java.util.Objects".equals(qualifiedName) && !"com.google.common.base.Objects".equals(qualifiedName)) {
+          return;
+        }
+        staticEqualsCall = true;
+      }
       final PsiExpressionList argumentList = expression.getArgumentList();
       final PsiExpression[] arguments = argumentList.getExpressions();
-      if (arguments.length != 1) {
-        return;
+      final PsiExpression expression1;
+      final PsiExpression expression2;
+      if (staticEqualsCall) {
+        if (arguments.length != 2) {
+          return;
+        }
+        expression1 = arguments[0];
+        expression2 = arguments[1];
       }
-      final PsiExpression expression1 = arguments[0];
-      final PsiExpression expression2 = methodExpression.getQualifierExpression();
+      else {
+        if (arguments.length != 1) {
+          return;
+        }
+        expression1 = arguments[0];
+        expression2 = methodExpression.getQualifierExpression();
+      }
+
       final PsiType comparisonType;
       if (expression2 == null) {
         final PsiClass aClass = PsiTreeUtil.getParentOfType(expression, PsiClass.class);
@@ -94,7 +125,7 @@
       final PsiType comparedTypeErasure = TypeConversionUtil.erasure(comparedType);
       final PsiType comparisonTypeErasure = TypeConversionUtil.erasure(comparisonType);
       if (comparedTypeErasure == null || comparisonTypeErasure == null ||
-          TypeConversionUtil.areTypesConvertible(comparedTypeErasure, comparisonTypeErasure)) {
+          TypeConversionUtil.areTypesConvertible(comparedType, comparisonType)) {
         return;
       }
       registerMethodCallError(expression, comparedType, comparisonType);
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspectionBase.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspectionBase.java
deleted file mode 100644
index dec9e2e..0000000
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspectionBase.java
+++ /dev/null
@@ -1,81 +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.siyeh.ig.classlayout;
-
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiFile;
-import com.intellij.psi.PsiJavaFile;
-import com.intellij.psi.util.FileTypeUtils;
-import com.siyeh.InspectionGadgetsBundle;
-import com.siyeh.ig.BaseInspection;
-import com.siyeh.ig.BaseInspectionVisitor;
-import com.siyeh.ig.psiutils.ClassUtils;
-import org.jetbrains.annotations.NotNull;
-
-public class ClassInTopLevelPackageInspectionBase extends BaseInspection {
-  @Override
-  @NotNull
-  public String getID() {
-    return "ClassWithoutPackageStatement";
-  }
-
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionGadgetsBundle.message(
-      "class.in.top.level.package.display.name");
-  }
-
-  @Override
-  @NotNull
-  protected String buildErrorString(Object... infos) {
-    return InspectionGadgetsBundle.message(
-      "class.in.top.level.package.problem.descriptor");
-  }
-
-  @Override
-  protected boolean buildQuickFixesOnlyForOnTheFlyErrors() {
-    return true;
-  }
-
-  @Override
-  public BaseInspectionVisitor buildVisitor() {
-    return new ClassInTopLevelPackageVisitor();
-  }
-
-  private static class ClassInTopLevelPackageVisitor
-    extends BaseInspectionVisitor {
-
-    @Override
-    public void visitClass(@NotNull PsiClass aClass) {
-      // no call to super, so that it doesn't drill down to inner classes
-      if (FileTypeUtils.isInServerPageFile(aClass)) {
-        return;
-      }
-      if (ClassUtils.isInnerClass(aClass)) {
-        return;
-      }
-      final PsiFile file = aClass.getContainingFile();
-      if (!(file instanceof PsiJavaFile)) {
-        return;
-      }
-      if (((PsiJavaFile)file).getPackageStatement() != null) {
-        return;
-      }
-      registerClassError(aClass);
-    }
-  }
-}
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/InterfaceMayBeAnnotatedFunctionalInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/InterfaceMayBeAnnotatedFunctionalInspection.java
index e4f77e0..b9f43f7 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/InterfaceMayBeAnnotatedFunctionalInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/classlayout/InterfaceMayBeAnnotatedFunctionalInspection.java
@@ -75,7 +75,7 @@
       if (LambdaHighlightingUtil.checkInterfaceFunctional(aClass) != null) {
         return;
       }
-      final List<MethodSignature> candidates = LambdaUtil.findFunctionCandidates(aClass);
+      final List<HierarchicalMethodSignature> candidates = LambdaUtil.findFunctionCandidates(aClass);
       if (candidates == null || candidates.size() != 1) {
         return;
       }
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java
index 6b2f34b..bebf5a5 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/PointlessArithmeticExpressionInspection.java
@@ -20,8 +20,8 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.*;
 import com.intellij.psi.tree.IElementType;
-import com.intellij.psi.util.ConstantExpressionUtil;
 import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.PsiUtilCore;
 import com.siyeh.InspectionGadgetsBundle;
 import com.siyeh.ig.BaseInspection;
 import com.siyeh.ig.BaseInspectionVisitor;
@@ -116,20 +116,19 @@
       }
       else if (tokenType.equals(JavaTokenType.ASTERISK) && isZero(operand) ||
         tokenType.equals(JavaTokenType.PERC) && (isOne(operand) || EquivalenceChecker.expressionsAreEquivalent(previousOperand, operand))) {
-        return PsiType.LONG.equals(polyadicExpression.getType()) ? "0L" : "0";
-      }
-      else if (tokenType.equals(JavaTokenType.LE) || tokenType.equals(JavaTokenType.GE) ||
-               tokenType.equals(JavaTokenType.LT) || tokenType.equals(JavaTokenType.GT)) {
-        return (tokenType.equals(JavaTokenType.LT) || tokenType.equals(JavaTokenType.GT)) ? "false" : "true";
+        fromTarget = operands[0];
+        untilTarget = operands[length - 1];
+        replacement = PsiType.LONG.equals(polyadicExpression.getType()) ? "0L" : "0";
+        break;
       }
 
       previousOperand = operand;
     }
-    return buildReplacementExpression(polyadicExpression, fromTarget, untilTarget, replacement).trim();
+    return getText(polyadicExpression, fromTarget, untilTarget, replacement).trim();
   }
 
-  public static String buildReplacementExpression(PsiPolyadicExpression expression, PsiElement fromTarget, PsiElement untilTarget,
-                                                  String replacement) {
+  public static String getText(PsiPolyadicExpression expression, PsiElement fromTarget, PsiElement untilTarget,
+                               @NotNull @NonNls String replacement) {
     final StringBuilder result = new StringBuilder();
     boolean stop = false;
     for (PsiElement child : expression.getChildren()) {
@@ -198,13 +197,10 @@
       if (!arithmeticTokens.contains(expression.getOperationTokenType())) {
         return;
       }
-      if (ExpressionUtils.hasStringType(expression)) {
+      if (ExpressionUtils.hasStringType(expression) || PsiUtilCore.hasErrorElementChild(expression)) {
         return;
       }
       final PsiExpression[] operands = expression.getOperands();
-      if (operands.length < 2) {
-        return;
-      }
       final IElementType tokenType = expression.getOperationTokenType();
       final boolean isPointless;
       if (tokenType.equals(JavaTokenType.PLUS)) {
@@ -222,14 +218,6 @@
       else if (tokenType.equals(JavaTokenType.PERC)) {
         isPointless = modExpressionIsPointless(operands);
       }
-      else if (tokenType.equals(JavaTokenType.LE) ||
-               tokenType.equals(JavaTokenType.GE) ||
-               tokenType.equals(JavaTokenType.GT) ||
-               tokenType.equals(JavaTokenType.LT)) {
-        final PsiExpression lhs = operands[0];
-        final PsiExpression rhs = operands[1];
-        isPointless = comparisonExpressionIsPointless(lhs, rhs, tokenType);
-      }
       else {
         isPointless = false;
       }
@@ -292,45 +280,6 @@
       }
       return false;
     }
-
-    private boolean comparisonExpressionIsPointless(
-      PsiExpression lhs, PsiExpression rhs, IElementType comparison) {
-      if (PsiType.INT.equals(lhs.getType()) &&
-          PsiType.INT.equals(rhs.getType())) {
-        return intComparisonIsPointless(lhs, rhs, comparison);
-      }
-      else if (PsiType.LONG.equals(lhs.getType()) &&
-               PsiType.LONG.equals(rhs.getType())) {
-        return longComparisonIsPointless(lhs, rhs, comparison);
-      }
-      return false;
-    }
-
-    private boolean intComparisonIsPointless(
-      PsiExpression lhs, PsiExpression rhs, IElementType comparison) {
-      if (isMaxInt(lhs) || isMinInt(rhs)) {
-        return JavaTokenType.GE.equals(comparison) ||
-               JavaTokenType.LT.equals(comparison);
-      }
-      if (isMinInt(lhs) || isMaxInt(rhs)) {
-        return JavaTokenType.LE.equals(comparison) ||
-               JavaTokenType.GT.equals(comparison);
-      }
-      return false;
-    }
-
-    private boolean longComparisonIsPointless(
-      PsiExpression lhs, PsiExpression rhs, IElementType comparison) {
-      if (isMaxLong(lhs) || isMinLong(rhs)) {
-        return JavaTokenType.GE.equals(comparison) ||
-               JavaTokenType.LT.equals(comparison);
-      }
-      if (isMinLong(lhs) || isMaxLong(rhs)) {
-        return JavaTokenType.LE.equals(comparison) ||
-               JavaTokenType.GT.equals(comparison);
-      }
-      return false;
-    }
   }
 
   boolean isZero(PsiExpression expression) {
@@ -346,32 +295,4 @@
     }
     return ExpressionUtils.isOne(expression);
   }
-
-  private static boolean isMinInt(PsiExpression expression) {
-    final Integer value = (Integer)
-      ConstantExpressionUtil.computeCastTo(
-        expression, PsiType.INT);
-    return value != null && value.intValue() == Integer.MIN_VALUE;
-  }
-
-  private static boolean isMaxInt(PsiExpression expression) {
-    final Integer value = (Integer)
-      ConstantExpressionUtil.computeCastTo(
-        expression, PsiType.INT);
-    return value != null && value.intValue() == Integer.MAX_VALUE;
-  }
-
-  private static boolean isMinLong(PsiExpression expression) {
-    final Long value = (Long)
-      ConstantExpressionUtil.computeCastTo(
-        expression, PsiType.LONG);
-    return value != null && value.longValue() == Long.MIN_VALUE;
-  }
-
-  private static boolean isMaxLong(PsiExpression expression) {
-    final Long value = (Long)
-      ConstantExpressionUtil.computeCastTo(
-        expression, PsiType.LONG);
-    return value != null && value.longValue() == Long.MAX_VALUE;
-  }
 }
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java
index ebd8449..69c2bad 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/StringEqualsEmptyStringInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2003-2012 Dave Griffith, Bas Leijdekkers
+ * Copyright 2003-2014 Dave Griffith, Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,6 +18,8 @@
 import com.intellij.codeInspection.ProblemDescriptor;
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.*;
+import com.intellij.psi.tree.IElementType;
+import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.siyeh.HardcodedMethodConstants;
@@ -27,6 +29,7 @@
 import com.siyeh.ig.InspectionGadgetsFix;
 import com.siyeh.ig.PsiReplacementUtil;
 import com.siyeh.ig.psiutils.BoolUtils;
+import com.siyeh.ig.psiutils.EquivalenceChecker;
 import com.siyeh.ig.psiutils.ExpressionUtils;
 import com.siyeh.ig.psiutils.TypeUtils;
 import org.jetbrains.annotations.NonNls;
@@ -97,19 +100,19 @@
       }
       final PsiExpression qualifier = expression.getQualifierExpression();
       final PsiExpression argument = arguments[0];
-      final String variableText;
+      final PsiExpression checkedExpression;
       final boolean addNullCheck;
       if (ExpressionUtils.isEmptyStringLiteral(argument)) {
-        variableText = getRemainingText(qualifier);
+        checkedExpression = getCheckedExpression(qualifier);
         addNullCheck = false;
       }
       else {
-        variableText = getRemainingText(argument);
-        addNullCheck = true;
+        checkedExpression = getCheckedExpression(argument);
+        addNullCheck = !isCheckedForNull(checkedExpression);
       }
-      StringBuilder newExpression;
+      final StringBuilder newExpression;
       if (addNullCheck) {
-        newExpression = new StringBuilder(variableText);
+        newExpression = new StringBuilder(checkedExpression.getText());
         newExpression.append("!=null&&");
       } else {
         newExpression = new StringBuilder("");
@@ -121,38 +124,81 @@
         if (BoolUtils.isNegation(parentExpression)) {
           expressionToReplace = parentExpression;
           if (useIsEmpty) {
-            newExpression.append('!').append(variableText).append(".isEmpty()");
+            newExpression.append('!').append(checkedExpression.getText()).append(".isEmpty()");
           }
           else {
-            newExpression.append(variableText).append(".length()!=0");
+            newExpression.append(checkedExpression.getText()).append(".length()!=0");
           }
         }
         else {
           expressionToReplace = call;
           if (useIsEmpty) {
-            newExpression.append(variableText).append(".isEmpty()");
+            newExpression.append(checkedExpression.getText()).append(".isEmpty()");
           }
           else {
-            newExpression.append(variableText).append(".length()==0");
+            newExpression.append(checkedExpression.getText()).append(".length()==0");
           }
         }
       }
       else {
         expressionToReplace = call;
         if (useIsEmpty) {
-          newExpression.append(variableText).append(".isEmpty()");
+          newExpression.append(checkedExpression.getText()).append(".isEmpty()");
         }
         else {
-          newExpression.append(variableText).append(".length()==0");
+          newExpression.append(checkedExpression.getText()).append(".length()==0");
         }
       }
       PsiReplacementUtil.replaceExpression(expressionToReplace, newExpression.toString());
     }
 
-    private String getRemainingText(PsiExpression expression) {
-      if (useIsEmpty ||
-          !(expression instanceof PsiMethodCallExpression)) {
-        return expression.getText();
+    private static boolean isCheckedForNull(PsiExpression expression) {
+      final PsiPolyadicExpression polyadicExpression =
+        PsiTreeUtil.getParentOfType(expression, PsiPolyadicExpression.class, true, PsiStatement.class, PsiVariable.class);
+      if (polyadicExpression == null) {
+        return false;
+      }
+      final IElementType tokenType = polyadicExpression.getOperationTokenType();
+      for (PsiExpression operand : polyadicExpression.getOperands()) {
+        if (PsiTreeUtil.isAncestor(operand, expression, true)) {
+          return false;
+        }
+        if (!(operand instanceof PsiBinaryExpression)) {
+          continue;
+        }
+        final PsiBinaryExpression binaryExpression = (PsiBinaryExpression)operand;
+        final IElementType operationTokenType = binaryExpression.getOperationTokenType();
+        if (JavaTokenType.ANDAND.equals(tokenType)) {
+          if (!JavaTokenType.NE.equals(operationTokenType)) {
+            continue;
+          }
+        }
+        else if (JavaTokenType.OROR.equals(tokenType)) {
+          if (!JavaTokenType.EQEQ.equals(operationTokenType)) {
+            continue;
+          }
+        }
+        else {
+          continue;
+        }
+        final PsiExpression lhs = binaryExpression.getLOperand();
+        final PsiExpression rhs = binaryExpression.getROperand();
+        if (rhs == null) {
+          continue;
+        }
+        if (PsiType.NULL.equals(lhs.getType()) && EquivalenceChecker.expressionsAreEquivalent(expression, rhs)) {
+          return true;
+        }
+        else if (PsiType.NULL.equals(rhs.getType()) && EquivalenceChecker.expressionsAreEquivalent(expression, lhs)) {
+          return true;
+        }
+      }
+      return false;
+    }
+
+    private PsiExpression getCheckedExpression(PsiExpression expression) {
+      if (useIsEmpty || !(expression instanceof PsiMethodCallExpression)) {
+        return expression;
       }
       // to replace stringBuffer.toString().equals("") with
       // stringBuffer.length() == 0
@@ -161,15 +207,15 @@
       final String referenceName = methodExpression.getReferenceName();
       final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
       if (qualifierExpression == null) {
-        return expression.getText();
+        return expression;
       }
       final PsiType type = qualifierExpression.getType();
       if (HardcodedMethodConstants.TO_STRING.equals(referenceName) && type != null && (type.equalsToText(
         CommonClassNames.JAVA_LANG_STRING_BUFFER) || type.equalsToText(CommonClassNames.JAVA_LANG_STRING_BUILDER))) {
-        return qualifierExpression.getText();
+        return qualifierExpression;
       }
       else {
-        return expression.getText();
+        return expression;
       }
     }
   }
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java
deleted file mode 100644
index 828b4c68..0000000
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/classlayout/ClassInTopLevelPackageInspection.java
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright 2003-2011 Dave Griffith, Bas Leijdekkers
- *
- * 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.siyeh.ig.classlayout;
-
-import com.siyeh.ig.InspectionGadgetsFix;
-import com.siyeh.ig.fixes.MoveClassFix;
-
-public class ClassInTopLevelPackageInspection extends ClassInTopLevelPackageInspectionBase {
-
-  @Override
-  protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new MoveClassFix();
-  }
-}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ProblematicWhitespaceInspection.java b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ProblematicWhitespaceInspection.java
index 8f823f0..bbd0f14 100644
--- a/plugins/InspectionGadgets/src/com/siyeh/ig/style/ProblematicWhitespaceInspection.java
+++ b/plugins/InspectionGadgets/src/com/siyeh/ig/style/ProblematicWhitespaceInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -141,7 +141,7 @@
                 registerError(file, file.getName(), Boolean.valueOf(isOnTheFly()), Boolean.TRUE);
                 return;
               }
-              else {
+              else if (!spaceSeen) {
                 final int currentIndent = Math.max(0, j);
                 if (currentIndent != previousLineIndent) {
                   registerError(file, file.getName(), Boolean.valueOf(isOnTheFly()), Boolean.TRUE);
diff --git a/plugins/InspectionGadgets/src/inspectionDescriptions/ClassInTopLevelPackage.html b/plugins/InspectionGadgets/src/inspectionDescriptions/ClassInTopLevelPackage.html
deleted file mode 100644
index c6263f2..0000000
--- a/plugins/InspectionGadgets/src/inspectionDescriptions/ClassInTopLevelPackage.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
-<body>
-Reports any classes which do not contain package declarations.
-<!-- tooltip end -->
-<p>
-
-</body>
-</html>
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/junit/useOfObsoleteAssert/singleStaticIport.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/junit/useOfObsoleteAssert/singleStaticImport.after.java
similarity index 100%
rename from plugins/InspectionGadgets/test/com/siyeh/igfixes/junit/useOfObsoleteAssert/singleStaticIport.after.java
rename to plugins/InspectionGadgets/test/com/siyeh/igfixes/junit/useOfObsoleteAssert/singleStaticImport.after.java
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_isempty/NullCheckAlreadyPresent.after.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_isempty/NullCheckAlreadyPresent.after.java
new file mode 100644
index 0000000..7277bd0
--- /dev/null
+++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_isempty/NullCheckAlreadyPresent.after.java
@@ -0,0 +1,12 @@
+package com.siyeh.igfixes.performance.replace_with_isempty;
+
+public class NullCheckAlreadyPresent {
+
+  String[] splitProperties = {"1","2"};
+
+  public void someAction() {
+    if (splitProperties[1] != null && splitProperties[1].isEmpty()) {
+      System.out.println("");
+    }
+  }
+}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_isempty/NullCheckAlreadyPresent.java b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_isempty/NullCheckAlreadyPresent.java
new file mode 100644
index 0000000..e91b650
--- /dev/null
+++ b/plugins/InspectionGadgets/test/com/siyeh/igfixes/performance/replace_with_isempty/NullCheckAlreadyPresent.java
@@ -0,0 +1,12 @@
+package com.siyeh.igfixes.performance.replace_with_isempty;
+
+public class NullCheckAlreadyPresent {
+
+  String[] splitProperties = {"1","2"};
+
+  public void someAction() {
+    if (splitProperties[1] != null && "".<caret>equals(splitProperties[1])) {
+      System.out.println("");
+    }
+  }
+}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/PointlessArithmeticExpression.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/PointlessArithmeticExpression.java
index d7577b1..019805a 100644
--- a/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/PointlessArithmeticExpression.java
+++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/PointlessArithmeticExpression.java
@@ -123,4 +123,5 @@
   System.out.println(u * 1);
   long g = 8L / 8L;
   long h = 9L * 0L;
+  int a = 8 * 0 * 8 * ; // don't warn
 }}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/expected.xml
index 58e0898..f6af122 100644
--- a/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/expected.xml
+++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/numeric/pointless_arithmetic_expression/expected.xml
@@ -38,90 +38,6 @@
 
   <problem>
     <file>PointlessArithmeticExpression.java</file>
-    <line>30</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;k&lt;=Integer.MAX_VALUE&lt;/code&gt; can be replaced with 'true' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>34</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;k&gt;=Integer.MIN_VALUE&lt;/code&gt; can be replaced with 'true' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>38</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;k&gt;Integer.MAX_VALUE&lt;/code&gt; can be replaced with 'false' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>42</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;k&lt;Integer.MIN_VALUE&lt;/code&gt; can be replaced with 'false' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>46</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;Integer.MAX_VALUE &gt;= k&lt;/code&gt; can be replaced with 'true' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>50</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;Integer.MIN_VALUE &lt;= k&lt;/code&gt; can be replaced with 'true' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>54</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;Integer.MAX_VALUE &lt; k&lt;/code&gt; can be replaced with 'false' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>58</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;Integer.MIN_VALUE &gt; k&lt;/code&gt; can be replaced with 'false' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>70</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;i &gt; Integer.MAX_VALUE&lt;/code&gt; can be replaced with 'false' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>76</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;i &lt;= Integer.MAX_VALUE&lt;/code&gt; can be replaced with 'true' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>80</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;i &gt;= Integer.MIN_VALUE&lt;/code&gt; can be replaced with 'true' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
-    <line>83</line>
-    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
-    <description>&lt;code&gt;i &lt; Integer.MIN_VALUE&lt;/code&gt; can be replaced with 'false' #loc</description>
-  </problem>
-
-  <problem>
-    <file>PointlessArithmeticExpression.java</file>
     <line>93</line>
     <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Pointless arithmetic expression</problem_class>
     <description>&lt;code&gt;i / i&lt;/code&gt; can be replaced with '1' #loc</description>
diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspectionTest.java
index 3168d9e..92e72bb81 100644
--- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspectionTest.java
+++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/bugs/EqualsBetweenInconvertibleTypesInspectionTest.java
@@ -39,6 +39,32 @@
            "}");
   }
 
+  public void testJavaUtilObjectsEquals() {
+    doStatementTest("java.util.Objects./*'equals()' between objects of inconvertible types 'Integer' and 'String'*/equals/**/(Integer.valueOf(1), \"string\");");
+  }
+
+  public void testComGoogleCommonBaseObjects() {
+    doStatementTest("com.google.common.base.Objects./*'equal()' between objects of inconvertible types 'Integer' and 'String'*/equal/**/(Integer.valueOf(1), \"string\");");
+  }
+
+  @Override
+  protected String[] getEnvironmentClasses() {
+    return new String[] {
+      "package java.util;" +
+      "public final class Objects {" +
+      "  public static boolean equals(Object a, Object b) {" +
+      "    return (a == b) || (a != null && a.equals(b));" +
+      "  }" +
+      "}",
+      "package com.google.common.base;" +
+      "public final class Objects {" +
+      "  public static boolean equal(Object a, Object b) {" +
+      "    return true;" +
+      "  }" +
+      "}"
+    };
+  }
+
   @Override
   protected InspectionProfileEntry getInspection() {
     return new EqualsBetweenInconvertibleTypesInspection();
diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/StringEqualsEmptyStringFixTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/StringEqualsEmptyStringFixTest.java
index a42fccb..6bd1cef 100644
--- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/StringEqualsEmptyStringFixTest.java
+++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/fixes/performance/StringEqualsEmptyStringFixTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2012 Bas Leijdekkers
+ * Copyright 2012-2014 Bas Leijdekkers
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,4 +31,5 @@
 
   public void testSimple() { doTest(); }
   public void testNullCheck() { doTest(); }
+  public void testNullCheckAlreadyPresent() { doTest(); }
 }
diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/ProblematicWhitespaceInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/ProblematicWhitespaceInspectionTest.java
index c0e062c..3cfc26b 100644
--- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/ProblematicWhitespaceInspectionTest.java
+++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/style/ProblematicWhitespaceInspectionTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -69,6 +69,34 @@
            "}\n/**/");
   }
 
+  public void testSmartTabsInFile2() {
+    final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject());
+    final CommonCodeStyleSettings.IndentOptions options = settings.getIndentOptions(JavaFileType.INSTANCE);
+    options.USE_TAB_CHARACTER = true;
+    options.SMART_TABS = true;
+    doTest("class X {\n" +
+           "\tvoid aaa(boolean a, boolean b, boolean c) {\n" +
+           "\t\taaa(true,\n" +
+           "\t\t    true,\n" +
+           "\t\t    true);\n" +
+           "\t}\n" +
+           "}\n");
+  }
+
+  public void testSmartTabsInFile3() {
+    final CodeStyleSettings settings = CodeStyleSettingsManager.getSettings(getProject());
+    final CommonCodeStyleSettings.IndentOptions options = settings.getIndentOptions(JavaFileType.INSTANCE);
+    options.USE_TAB_CHARACTER = true;
+    options.SMART_TABS = true;
+    doTest("/*File 'X.java' uses spaces for indentation*/class X {\n" +
+           "\tvoid aaa(boolean a, boolean b, boolean c) {\n" +
+           "\t\taaa(true,\n" +
+           "\t \t    true,\n" +
+           "\t\t    true);\n" +
+           "\t}\n" +
+           "}\n/**/");
+  }
+
   @Override
   protected InspectionProfileEntry getInspection() {
     return new ProblematicWhitespaceInspection();
diff --git a/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntention.java b/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntention.java
index 13f7f8b..26ca6de 100644
--- a/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntention.java
+++ b/plugins/IntentionPowerPak/src/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntention.java
@@ -64,8 +64,8 @@
     PsiCodeBlock blockFromText = psiElementFactory.createCodeBlockFromText(blockText, lambdaExpression);
     ChangeContextUtil.encodeContextInfo(blockFromText, true);
     PsiNewExpression newExpression = (PsiNewExpression)psiElementFactory.createExpressionFromText("new " + functionalInterfaceType.getCanonicalText() + "(){}", lambdaExpression);
-    final PsiClass thisClass = PsiTreeUtil.getParentOfType(lambdaExpression, PsiClass.class, true);
-    final String thisClassName = thisClass.getName();
+    final PsiClass thisClass = RefactoringChangeUtil.getThisClass(lambdaExpression);
+    final String thisClassName = thisClass != null ? thisClass.getName() : null;
     if (thisClassName != null) {
       final PsiThisExpression thisAccessExpr = thisClass instanceof PsiAnonymousClass ? null : RefactoringChangeUtil
         .createThisExpression(lambdaExpression.getManager(), thisClass);
@@ -86,8 +86,11 @@
         @Override
         public void visitMethodCallExpression(PsiMethodCallExpression expression) {
           super.visitMethodCallExpression(expression);
-          if (thisAccessExpr != null && expression.getMethodExpression().getQualifierExpression() == null) {
-            replacements.put(expression, psiElementFactory.createExpressionFromText(thisAccessExpr.getText() + "." + expression.getText(), expression));
+          if (thisAccessExpr != null) {
+            final PsiMethod psiMethod = expression.resolveMethod();
+            if (psiMethod != null && !psiMethod.hasModifierProperty(PsiModifier.STATIC) && expression.getMethodExpression().getQualifierExpression() == null) {
+              replacements.put(expression, psiElementFactory.createExpressionFromText(thisAccessExpr.getText() + "." + expression.getText(), expression));
+            }
           }
         }
       });
diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/StaticCalls.java b/plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/StaticCalls.java
new file mode 100644
index 0000000..b4fa8c2
--- /dev/null
+++ b/plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/StaticCalls.java
@@ -0,0 +1,11 @@
+class Foo {
+
+  public static void main(String[] args) {
+    new Thread((<caret>) -> print());
+  }
+
+  public static void print() {
+    System.out.println("print");
+  }
+
+}
diff --git a/plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/StaticCalls_after.java b/plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/StaticCalls_after.java
new file mode 100644
index 0000000..2d4f54c
--- /dev/null
+++ b/plugins/IntentionPowerPak/test/com/siyeh/ipp/types/lambda2anonymous/StaticCalls_after.java
@@ -0,0 +1,16 @@
+class Foo {
+
+  public static void main(String[] args) {
+    new Thread(new Runnable() {
+        @Override
+        public void run() {
+            print();
+        }
+    });
+  }
+
+  public static void print() {
+    System.out.println("print");
+  }
+
+}
diff --git a/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntentionTest.java b/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntentionTest.java
index a607642..6f20941 100644
--- a/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntentionTest.java
+++ b/plugins/IntentionPowerPak/testSrc/com/siyeh/ipp/types/ReplaceLambdaWithAnonymousIntentionTest.java
@@ -75,6 +75,10 @@
     doTest();
   }
 
+  public void testStaticCalls() {
+    doTest();
+  }
+
   @Override
   protected String getIntentionName() {
     return IntentionPowerPackBundle.message("replace.lambda.with.anonymous.intention.name");
diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java
index e718b8f..d47ac8d0 100644
--- a/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java
+++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/AntBuildMessageView.java
@@ -791,26 +791,30 @@
               final Runnable finishRunnable = new Runnable() {
                 public void run() {
                   final int errorCount = getErrorCount();
-                  final AntBuildFileBase buildFile = myBuildFile;
-                  if (buildFile != null) {
-                    if (errorCount == 0 && buildFile.isViewClosedWhenNoErrors()) {
-                      close();
-                    }
-                    else if (errorCount > 0) {
-                      myTreeView.scrollToFirstError();
+                  try {
+                    final AntBuildFileBase buildFile = myBuildFile;
+                    if (buildFile != null) {
+                      if (errorCount == 0 && buildFile.isViewClosedWhenNoErrors()) {
+                        close();
+                      }
+                      else if (errorCount > 0) {
+                        myTreeView.scrollToFirstError();
+                      }
+                      else {
+                        myTreeView.scrollToStatus();
+                      }
                     }
                     else {
-                      myTreeView.scrollToStatus();
+                      myTreeView.scrollToLastMessage();
                     }
                   }
-                  else {
-                    myTreeView.scrollToLastMessage();
+                  finally {
+                    VirtualFileManager.getInstance().asyncRefresh(new Runnable() {
+                      public void run() {
+                        antBuildListener.buildFinished(aborted ? AntBuildListener.ABORTED : AntBuildListener.FINISHED_SUCCESSFULLY, errorCount);
+                      }
+                    });
                   }
-                  VirtualFileManager.getInstance().asyncRefresh(new Runnable() {
-                    public void run() {
-                      antBuildListener.buildFinished(aborted ? AntBuildListener.ABORTED : AntBuildListener.FINISHED_SUCCESSFULLY, errorCount);
-                    }
-                  });
                 }
               };
               if (shouldActivate) {
diff --git a/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java b/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java
index d697491..a0a075f 100644
--- a/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java
+++ b/plugins/ant/src/com/intellij/lang/ant/config/execution/ExecutionHandler.java
@@ -71,43 +71,41 @@
                               @Nullable final AntBuildMessageView buildMessageViewToReuse,
                               final DataContext dataContext,
                               List<BuildFileProperty> additionalProperties, @NotNull final AntBuildListener antBuildListener) {
-    FileDocumentManager.getInstance().saveAllDocuments();
-    final AntCommandLineBuilder builder = new AntCommandLineBuilder();
     final AntBuildMessageView messageView;
     final GeneralCommandLine commandLine;
-    synchronized (builder) {
-      Project project = buildFile.getProject();
+    final Project project = buildFile.getProject();
+    try {
+      FileDocumentManager.getInstance().saveAllDocuments();
+      final AntCommandLineBuilder builder = new AntCommandLineBuilder();
 
-      try {
-        builder.setBuildFile(buildFile.getAllOptions(), VfsUtil.virtualToIoFile(buildFile.getVirtualFile()));
-        builder.calculateProperties(dataContext, additionalProperties);
-        builder.addTargets(targets);
+      builder.setBuildFile(buildFile.getAllOptions(), VfsUtil.virtualToIoFile(buildFile.getVirtualFile()));
+      builder.calculateProperties(dataContext, additionalProperties);
+      builder.addTargets(targets);
 
-        builder.getCommandLine().setCharset(EncodingProjectManager.getInstance(buildFile.getProject()).getDefaultCharset());
+      builder.getCommandLine().setCharset(EncodingProjectManager.getInstance(buildFile.getProject()).getDefaultCharset());
 
-        messageView = prepareMessageView(buildMessageViewToReuse, buildFile, targets);
-        commandLine = CommandLineBuilder.createFromJavaParameters(builder.getCommandLine());
-        messageView.setBuildCommandLine(commandLine.getCommandLineString());
-      }
-      catch (RunCanceledException e) {
-        e.showMessage(project, AntBundle.message("run.ant.erorr.dialog.title"));
-        antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
-        return;
-      }
-      catch (CantRunException e) {
-        ExecutionErrorDialog.show(e, AntBundle.message("cant.run.ant.erorr.dialog.title"), project);
-        antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
-        return;
-      }
-      catch (Macro.ExecutionCancelledException e) {
-        antBuildListener.buildFinished(AntBuildListener.ABORTED, 0);
-        return;
-      }
-      catch (Throwable e) {
-        antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
-        LOG.error(e);
-        return;
-      }
+      messageView = prepareMessageView(buildMessageViewToReuse, buildFile, targets);
+      commandLine = CommandLineBuilder.createFromJavaParameters(builder.getCommandLine());
+      messageView.setBuildCommandLine(commandLine.getCommandLineString());
+    }
+    catch (RunCanceledException e) {
+      e.showMessage(project, AntBundle.message("run.ant.erorr.dialog.title"));
+      antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
+      return;
+    }
+    catch (CantRunException e) {
+      ExecutionErrorDialog.show(e, AntBundle.message("cant.run.ant.erorr.dialog.title"), project);
+      antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
+      return;
+    }
+    catch (Macro.ExecutionCancelledException e) {
+      antBuildListener.buildFinished(AntBuildListener.ABORTED, 0);
+      return;
+    }
+    catch (Throwable e) {
+      antBuildListener.buildFinished(AntBuildListener.FAILED_TO_RUN, 0);
+      LOG.error(e);
+      return;
     }
 
     new Task.Backgroundable(buildFile.getProject(), AntBundle.message("ant.build.progress.dialog.title"), true) {
@@ -195,28 +193,31 @@
 
         final OutputPacketProcessor dispatcher = handler.getErr().getEventsDispatcher();
 
-        if (event.getExitCode() != 0) {
-          // in case process exits abnormally, provide all unprocessed stderr content
-          final String unprocessed;
-          synchronized (myUnprocessedStdErr) {
-            unprocessed = myUnprocessedStdErr.toString();
-            myUnprocessedStdErr.setLength(0);
+        try {
+          if (event.getExitCode() != 0) {
+            // in case process exits abnormally, provide all unprocessed stderr content
+            final String unprocessed;
+            synchronized (myUnprocessedStdErr) {
+              unprocessed = myUnprocessedStdErr.toString();
+              myUnprocessedStdErr.setLength(0);
+            }
+            if (!unprocessed.isEmpty()) {
+              dispatcher.processOutput(new Printable() {
+                public void printOn(Printer printer) {
+                  errorView.outputError(unprocessed, AntBuildMessageView.PRIORITY_ERR);
+                }
+              });
+            }
           }
-          if (!unprocessed.isEmpty()) {
-            dispatcher.processOutput(new Printable() {
-              public void printOn(Printer printer) {
-                errorView.outputError(unprocessed, AntBuildMessageView.PRIORITY_ERR);
-              }
-            });
+          else {
+            synchronized (myUnprocessedStdErr) {
+              myUnprocessedStdErr.setLength(0);
+            }
           }
         }
-        else {
-          synchronized (myUnprocessedStdErr) {
-            myUnprocessedStdErr.setLength(0);
-          }
+        finally {
+          errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener, dispatcher);
         }
-
-        errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener, dispatcher);
       }
     });
     handler.startNotify();
diff --git a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java
index dfa7a59..3bdcbeb 100644
--- a/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java
+++ b/plugins/ant/src/com/intellij/lang/ant/config/impl/AntConfigurationImpl.java
@@ -32,7 +32,6 @@
 import com.intellij.openapi.actionSystem.ex.ActionManagerEx;
 import com.intellij.openapi.application.Application;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.components.*;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicator;
@@ -644,32 +643,32 @@
 
   public static boolean executeTargetSynchronously(final DataContext dataContext, final AntBuildTarget target, final List<BuildFileProperty> additionalProperties) {
     final Semaphore targetDone = new Semaphore();
-    final boolean[] result = new boolean[1];
-    try {
-      ApplicationManager.getApplication().invokeAndWait(new Runnable() {
-
-        public void run() {
-          Project project = CommonDataKeys.PROJECT.getData(dataContext);
+    targetDone.down();
+    final Ref<Boolean> result = Ref.create(Boolean.FALSE);
+    SwingUtilities.invokeLater(new Runnable() {
+      public void run() {
+        try {
+          final Project project = CommonDataKeys.PROJECT.getData(dataContext);
           if (project == null || project.isDisposed()) {
-            result[0] = false;
-            return;
+            targetDone.up();
           }
-          targetDone.down();
-          target.run(dataContext, additionalProperties, new AntBuildListener() {
-            public void buildFinished(int state, int errorCount) {
-              result[0] = (state == AntBuildListener.FINISHED_SUCCESSFULLY) && (errorCount == 0);
-              targetDone.up();
-            }
-          });
+          else {
+            target.run(dataContext, additionalProperties, new AntBuildListener() {
+              public void buildFinished(int state, int errorCount) {
+                result.set((state == AntBuildListener.FINISHED_SUCCESSFULLY) && (errorCount == 0));
+                targetDone.up();
+              }
+            });
+          }
         }
-      }, ModalityState.NON_MODAL);
-    }
-    catch (Exception e) {
-      LOG.error(e);
-      return false;
-    }
+        catch (Throwable e) {
+          targetDone.up();
+          LOG.error(e);
+        }
+      }
+    });
     targetDone.waitFor();
-    return result[0];
+    return result.get();
   }
 
   private List<ExecutionEvent> getEventsByClass(Class eventClass) {
diff --git a/plugins/devkit/src/module/PluginModuleBuilder.java b/plugins/devkit/src/module/PluginModuleBuilder.java
index 172d918..bf6daf1 100644
--- a/plugins/devkit/src/module/PluginModuleBuilder.java
+++ b/plugins/devkit/src/module/PluginModuleBuilder.java
@@ -16,14 +16,18 @@
 package org.jetbrains.idea.devkit.module;
 
 import com.intellij.ide.util.projectWizard.JavaModuleBuilder;
+import com.intellij.ide.util.projectWizard.ModuleWizardStep;
+import com.intellij.ide.util.projectWizard.SettingsStep;
 import com.intellij.openapi.module.JavaModuleType;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleType;
+import com.intellij.openapi.module.StdModuleTypes;
 import com.intellij.openapi.options.ConfigurationException;
 import com.intellij.openapi.projectRoots.SdkTypeId;
 import com.intellij.openapi.roots.ModifiableRootModel;
 import com.intellij.openapi.startup.StartupManager;
 import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.idea.devkit.build.PluginBuildConfiguration;
 import org.jetbrains.idea.devkit.projectRoots.IdeaJdk;
 
@@ -64,4 +68,8 @@
   public int getWeight() {
     return 0;
   }
+
+  public ModuleWizardStep modifyProjectTypeStep(@NotNull SettingsStep settingsStep) {
+    return StdModuleTypes.JAVA.modifyProjectTypeStep(settingsStep, this);
+  }
 }
diff --git a/plugins/git4idea/git4idea.iml b/plugins/git4idea/git4idea.iml
index 76fdf85..1958a71 100644
--- a/plugins/git4idea/git4idea.iml
+++ b/plugins/git4idea/git4idea.iml
@@ -7,9 +7,7 @@
       <sourceFolder url="file://$MODULE_DIR$/resources" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
       <sourceFolder url="file://$MODULE_DIR$/tests" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/testFramework" isTestSource="true" />
       <sourceFolder url="file://$MODULE_DIR$/test-stepdefs" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/gitlog" isTestSource="false" />
     </content>
     <orderEntry type="inheritedJdk" />
     <orderEntry type="sourceFolder" forTests="false" />
diff --git a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/importProject/CloudGitProjectStructureDetector.java b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/importProject/CloudGitProjectStructureDetector.java
index 1cf2be4..2285ad4 100644
--- a/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/importProject/CloudGitProjectStructureDetector.java
+++ b/plugins/git4idea/remote-servers-git/src/com/intellij/remoteServer/util/importProject/CloudGitProjectStructureDetector.java
@@ -65,15 +65,13 @@
   }
 
   private static void detectApplicationRoot(@NotNull File dir, @NotNull List<DetectedProjectRoot> result) {
-    final File gitDir = new File(dir, GitUtil.DOT_GIT);
-    if (!gitDir.exists()) {
-      return;
-    }
-
     VirtualFile repositoryRoot = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(dir);
     if (repositoryRoot == null) {
       return;
     }
+    if (GitUtil.findGitDir(repositoryRoot) == null) {
+      return;
+    }
 
     Project project = ProjectManager.getInstance().getDefaultProject();
     GitRepository repository
diff --git a/plugins/git4idea/src/git4idea/commands/GitImpl.java b/plugins/git4idea/src/git4idea/commands/GitImpl.java
index bc00a5f..b94cef0 100644
--- a/plugins/git4idea/src/git4idea/commands/GitImpl.java
+++ b/plugins/git4idea/src/git4idea/commands/GitImpl.java
@@ -133,16 +133,21 @@
   
   @Override
   @NotNull
-  public GitCommandResult clone(@NotNull Project project, @NotNull File parentDirectory, @NotNull String url,
-                                @NotNull String clonedDirectoryName, @NotNull GitLineHandlerListener... listeners) {
-    GitLineHandlerPasswordRequestAware handler = new GitLineHandlerPasswordRequestAware(project, parentDirectory, GitCommand.CLONE);
-    handler.setStdoutSuppressed(false);
-    handler.setUrl(url);
-    handler.addParameters("--progress");
-    handler.addParameters(url);
-    handler.addParameters(clonedDirectoryName);
-    addListeners(handler, listeners);
-    return run(handler);
+  public GitCommandResult clone(@NotNull final Project project, @NotNull final File parentDirectory, @NotNull final String url,
+                                @NotNull final String clonedDirectoryName, @NotNull final GitLineHandlerListener... listeners) {
+    return run(new Computable<GitLineHandler>() {
+      @Override
+      public GitLineHandler compute() {
+        GitLineHandlerPasswordRequestAware handler = new GitLineHandlerPasswordRequestAware(project, parentDirectory, GitCommand.CLONE);
+        handler.setStdoutSuppressed(false);
+        handler.setUrl(url);
+        handler.addParameters("--progress");
+        handler.addParameters(url);
+        handler.addParameters(clonedDirectoryName);
+        addListeners(handler, listeners);
+        return handler;
+      }
+    });
   }
 
   @NotNull
diff --git a/plugins/git4idea/src/git4idea/history/GitHistoryUtils.java b/plugins/git4idea/src/git4idea/history/GitHistoryUtils.java
index 82f2cf7..3641c51 100644
--- a/plugins/git4idea/src/git4idea/history/GitHistoryUtils.java
+++ b/plugins/git4idea/src/git4idea/history/GitHistoryUtils.java
@@ -531,7 +531,7 @@
                                                  AUTHOR_NAME, AUTHOR_EMAIL);
     h.setStdoutSuppressed(true);
     h.addParameters(parser.getPretty(), "--encoding=UTF-8");
-    h.addParameters("--full-history", "--sparse");
+    h.addParameters("--full-history");
     h.addParameters("--date-order");
     h.addParameters(parameters);
     h.endOptions();
diff --git a/plugins/git4idea/src/git4idea/log/GitLogProvider.java b/plugins/git4idea/src/git4idea/log/GitLogProvider.java
index 07afb4e..5f03de5 100644
--- a/plugins/git4idea/src/git4idea/log/GitLogProvider.java
+++ b/plugins/git4idea/src/git4idea/log/GitLogProvider.java
@@ -165,7 +165,9 @@
       return Collections.emptyList();
     }
 
-    return GitHistoryUtils.readCommits(myProject, root, userRegistry, GitHistoryUtils.LOG_ALL);
+    List<String> parameters = new ArrayList<String>(GitHistoryUtils.LOG_ALL);
+    parameters.add("--sparse");
+    return GitHistoryUtils.readCommits(myProject, root, userRegistry, parameters);
   }
 
   @NotNull
@@ -315,6 +317,7 @@
 
     // note: structure filter must be the last parameter, because it uses "--" which separates parameters from paths
     if (filterCollection.getStructureFilter() != null) {
+      filterParameters.add("--simplify-merges");
       filterParameters.add("--");
       for (VirtualFile file : filterCollection.getStructureFilter().getFiles(root)) {
         filterParameters.add(file.getPath());
diff --git a/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestWorker.java b/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestWorker.java
index d06851c..d2f518c 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestWorker.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/GithubCreatePullRequestWorker.java
@@ -305,18 +305,21 @@
     if (info == null) {
       return true;
     }
+
+    String localBranchName = "'" + getCurrentBranch() + "'";
+    String targetBranchName = "'" + myTargetRemote + ":" + targetBranch + "'";
     if (info.getInfo().getBranchToHeadCommits(myGitRepository).isEmpty()) {
-      GithubNotifications.showWarningDialog(myProject, CANNOT_CREATE_PULL_REQUEST, "Can't create empty pull request: the branch" +
-                                                                                   getCurrentBranch() +
-                                                                                   " in fully merged to the branch " +
-                                                                                   targetBranch +
-                                                                                   ".");
+      GithubNotifications
+        .showWarningDialog(myProject, CANNOT_CREATE_PULL_REQUEST,
+                           "Can't create empty pull request: the branch " + localBranchName +
+                           " is fully merged to the branch " + targetBranchName
+        );
       return false;
     }
-    if (info.getInfo().getHeadToBranchCommits(myGitRepository).isEmpty()) {
+    if (!info.getInfo().getHeadToBranchCommits(myGitRepository).isEmpty()) {
       return GithubNotifications
-               .showYesNoDialog(myProject, "The branch" + targetBranch + " in not fully merged to the branch " + getCurrentBranch(),
-                                "Do you want to proceed anyway?") == Messages.YES;
+               .showYesNoDialog(myProject, "Do you want to proceed anyway?",
+                                "The branch " + targetBranchName + " is not fully merged to the branch " + localBranchName) == Messages.YES;
     }
 
     return true;
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 1d7bbfd..9029cd8 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/api/GithubApiUtil.java
@@ -111,7 +111,7 @@
       String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + path;
       method = doREST(auth, uri, requestBody, headers, verb);
 
-      checkStatusCode(method);
+      checkStatusCode(method, requestBody);
 
       InputStream resp = method.getResponseBodyAsStream();
       if (resp == null) {
@@ -235,7 +235,7 @@
     return client;
   }
 
-  private static void checkStatusCode(@NotNull HttpMethod method) throws IOException {
+  private static void checkStatusCode(@NotNull HttpMethod method, @Nullable String body) throws IOException {
     int code = method.getStatusCode();
     switch (code) {
       case HttpStatus.SC_OK:
@@ -243,7 +243,6 @@
       case HttpStatus.SC_ACCEPTED:
       case HttpStatus.SC_NO_CONTENT:
         return;
-      case HttpStatus.SC_BAD_REQUEST:
       case HttpStatus.SC_UNAUTHORIZED:
       case HttpStatus.SC_PAYMENT_REQUIRED:
       case HttpStatus.SC_FORBIDDEN:
@@ -261,6 +260,12 @@
         }
 
         throw new GithubAuthenticationException("Request response: " + message);
+      case HttpStatus.SC_BAD_REQUEST:
+      case HttpStatus.SC_UNPROCESSABLE_ENTITY:
+        if (body != null) {
+          LOG.info(body);
+        }
+        throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
       default:
         throw new GithubStatusCodeException(code + ": " + getErrorMessage(method), code);
     }
@@ -440,7 +445,7 @@
       String uri = GithubUrlUtil.getApiUrl(auth.getHost()) + "/user";
       method = doREST(auth, uri, null, Collections.<Header>emptyList(), HttpVerb.HEAD);
 
-      checkStatusCode(method);
+      checkStatusCode(method, null);
 
       Header header = method.getResponseHeader("X-OAuth-Scopes");
       if (header == null) {
diff --git a/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java
index f080716..fb8e381 100644
--- a/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java
+++ b/plugins/github/src/org/jetbrains/plugins/github/extensions/GithubHttpAuthDataProvider.java
@@ -70,6 +70,6 @@
 
   @Override
   public void forgetPassword(@NotNull String url) {
-    // TODO
+    GithubSettings.getInstance().setValidGitAuth(false);
   }
 }
diff --git a/plugins/gradle/gradle.iml b/plugins/gradle/gradle.iml
index db31d99..66b5067 100644
--- a/plugins/gradle/gradle.iml
+++ b/plugins/gradle/gradle.iml
@@ -12,7 +12,8 @@
     <orderEntry type="sourceFolder" forTests="false" />
     <orderEntry type="module" module-name="external-system-api" exported="" />
     <orderEntry type="module" module-name="external-system-impl" exported="" />
-    <orderEntry type="module" module-name="gradle-tooling-extension" exported="" />
+    <orderEntry type="module" module-name="gradle-tooling-extension-api" exported="" />
+    <orderEntry type="module" module-name="gradle-tooling-extension-impl" />
     <orderEntry type="module" module-name="idea-ui" />
     <orderEntry type="module" module-name="lang-api" />
     <orderEntry type="module" module-name="compiler-openapi" />
@@ -23,39 +24,41 @@
     <orderEntry type="module" module-name="openapi" />
     <orderEntry type="module" module-name="java-impl" />
     <orderEntry type="module" module-name="maven" />
+    <orderEntry type="module" module-name="junit" />
     <orderEntry type="library" name="swingx" level="project" />
     <orderEntry type="module-library" exported="">
       <library name="Gradle">
         <CLASSES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-tooling-api-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-core-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-messaging-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-wrapper-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-base-services-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-native-1.9.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-tooling-api-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-core-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-messaging-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-wrapper-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-base-services-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-native-1.12-rc-1.jar!/" />
         </CLASSES>
         <JAVADOC />
         <SOURCES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/native/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/wrapper/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/wrapper/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/messaging/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/messaging/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/native/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/wrapper/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/wrapper/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/messaging/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/messaging/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/java" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/test/groovy" />
         </SOURCES>
       </library>
     </orderEntry>
     <orderEntry type="module-library" exported="">
       <library name="Slf4j">
         <CLASSES>
-          <root url="jar://$MODULE_DIR$/lib/slf4j-api-1.7.2.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/slf4j-simple-1.7.2.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/slf4j-api-1.7.5.jar!/" />
         </CLASSES>
         <JAVADOC />
         <SOURCES />
@@ -95,12 +98,7 @@
         <CLASSES>
           <root url="jar://$MODULE_DIR$/lib/jna-3.2.7.jar!/" />
           <root url="jar://$MODULE_DIR$/lib/jna-posix-1.0.3.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/native-platform-0.3-rc-2.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/native-platform-linux-amd64-0.3-rc-2.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/native-platform-linux-i386-0.3-rc-2.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/native-platform-osx-universal-0.3-rc-2.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/native-platform-windows-amd64-0.3-rc-2.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/native-platform-windows-i386-0.3-rc-2.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/native-platform-0.10.jar!/" />
         </CLASSES>
         <JAVADOC />
         <SOURCES />
diff --git a/plugins/gradle/tooling-extension-v1.11/lib/gradle-1.11-rc-1-src.zip b/plugins/gradle/lib/gradle-1.12-rc-1-src.zip
similarity index 70%
rename from plugins/gradle/tooling-extension-v1.11/lib/gradle-1.11-rc-1-src.zip
rename to plugins/gradle/lib/gradle-1.12-rc-1-src.zip
index 355aee4..0e2eb96 100644
--- a/plugins/gradle/tooling-extension-v1.11/lib/gradle-1.11-rc-1-src.zip
+++ b/plugins/gradle/lib/gradle-1.12-rc-1-src.zip
Binary files differ
diff --git a/plugins/gradle/lib/gradle-1.9-src.zip b/plugins/gradle/lib/gradle-1.9-src.zip
deleted file mode 100644
index 961b1df..0000000
--- a/plugins/gradle/lib/gradle-1.9-src.zip
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.12/lib/gradle-base-services-1.12-20140327133732+0000.jar b/plugins/gradle/lib/gradle-base-services-1.12-rc-1.jar
similarity index 85%
rename from plugins/gradle/tooling-extension-v1.12/lib/gradle-base-services-1.12-20140327133732+0000.jar
rename to plugins/gradle/lib/gradle-base-services-1.12-rc-1.jar
index b408e3b..929b4b9 100644
--- a/plugins/gradle/tooling-extension-v1.12/lib/gradle-base-services-1.12-20140327133732+0000.jar
+++ b/plugins/gradle/lib/gradle-base-services-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-base-services-1.9.jar b/plugins/gradle/lib/gradle-base-services-1.9.jar
deleted file mode 100644
index 16ccef0..0000000
--- a/plugins/gradle/lib/gradle-base-services-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.12/lib/gradle-core-1.12-20140327133732+0000.jar b/plugins/gradle/lib/gradle-core-1.12-rc-1.jar
similarity index 82%
rename from plugins/gradle/tooling-extension-v1.12/lib/gradle-core-1.12-20140327133732+0000.jar
rename to plugins/gradle/lib/gradle-core-1.12-rc-1.jar
index 497a6c3..3a4a63f0 100644
--- a/plugins/gradle/tooling-extension-v1.12/lib/gradle-core-1.12-20140327133732+0000.jar
+++ b/plugins/gradle/lib/gradle-core-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-core-1.9.jar b/plugins/gradle/lib/gradle-core-1.9.jar
deleted file mode 100644
index e7f403a..0000000
--- a/plugins/gradle/lib/gradle-core-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/gradle-messaging-1.12-rc-1.jar b/plugins/gradle/lib/gradle-messaging-1.12-rc-1.jar
new file mode 100644
index 0000000..4fe5174
--- /dev/null
+++ b/plugins/gradle/lib/gradle-messaging-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-messaging-1.9.jar b/plugins/gradle/lib/gradle-messaging-1.9.jar
deleted file mode 100644
index 0def32d..0000000
--- a/plugins/gradle/lib/gradle-messaging-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/gradle-native-1.12-rc-1.jar b/plugins/gradle/lib/gradle-native-1.12-rc-1.jar
new file mode 100644
index 0000000..c0a4189
--- /dev/null
+++ b/plugins/gradle/lib/gradle-native-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-native-1.9.jar b/plugins/gradle/lib/gradle-native-1.9.jar
deleted file mode 100644
index 8c21542..0000000
--- a/plugins/gradle/lib/gradle-native-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.12/lib/gradle-tooling-api-1.12-20140327133732+0000.jar b/plugins/gradle/lib/gradle-tooling-api-1.12-rc-1.jar
similarity index 74%
rename from plugins/gradle/tooling-extension-v1.12/lib/gradle-tooling-api-1.12-20140327133732+0000.jar
rename to plugins/gradle/lib/gradle-tooling-api-1.12-rc-1.jar
index 3977e5a..0193006 100644
--- a/plugins/gradle/tooling-extension-v1.12/lib/gradle-tooling-api-1.12-20140327133732+0000.jar
+++ b/plugins/gradle/lib/gradle-tooling-api-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/gradle-tooling-api-1.9.jar b/plugins/gradle/lib/gradle-tooling-api-1.9.jar
deleted file mode 100644
index 0ae460a..0000000
--- a/plugins/gradle/lib/gradle-tooling-api-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/gradle-wrapper-1.9.jar b/plugins/gradle/lib/gradle-wrapper-1.12-rc-1.jar
similarity index 63%
rename from plugins/gradle/lib/gradle-wrapper-1.9.jar
rename to plugins/gradle/lib/gradle-wrapper-1.12-rc-1.jar
index e050199..38392f9 100644
--- a/plugins/gradle/lib/gradle-wrapper-1.9.jar
+++ b/plugins/gradle/lib/gradle-wrapper-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-0.10.jar b/plugins/gradle/lib/native-platform-0.10.jar
new file mode 100644
index 0000000..9186adb
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-0.3-rc-2.jar b/plugins/gradle/lib/native-platform-0.3-rc-2.jar
deleted file mode 100644
index ede1eca..0000000
--- a/plugins/gradle/lib/native-platform-0.3-rc-2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-freebsd-amd64-0.10.jar b/plugins/gradle/lib/native-platform-freebsd-amd64-0.10.jar
new file mode 100644
index 0000000..cf6abf0c
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-freebsd-amd64-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-freebsd-i386-0.10.jar b/plugins/gradle/lib/native-platform-freebsd-i386-0.10.jar
new file mode 100644
index 0000000..f3a06f8
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-freebsd-i386-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-linux-amd64-0.10.jar b/plugins/gradle/lib/native-platform-linux-amd64-0.10.jar
new file mode 100644
index 0000000..fa348fe
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-linux-amd64-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-linux-amd64-0.3-rc-2.jar b/plugins/gradle/lib/native-platform-linux-amd64-0.3-rc-2.jar
deleted file mode 100644
index 14508de..0000000
--- a/plugins/gradle/lib/native-platform-linux-amd64-0.3-rc-2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-linux-i386-0.10.jar b/plugins/gradle/lib/native-platform-linux-i386-0.10.jar
new file mode 100644
index 0000000..bf38f96
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-linux-i386-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-linux-i386-0.3-rc-2.jar b/plugins/gradle/lib/native-platform-linux-i386-0.3-rc-2.jar
deleted file mode 100644
index 4e8c6db..0000000
--- a/plugins/gradle/lib/native-platform-linux-i386-0.3-rc-2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-osx-amd64-0.10.jar b/plugins/gradle/lib/native-platform-osx-amd64-0.10.jar
new file mode 100644
index 0000000..9bef604
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-osx-amd64-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-osx-i386-0.10.jar b/plugins/gradle/lib/native-platform-osx-i386-0.10.jar
new file mode 100644
index 0000000..117578a
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-osx-i386-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-osx-universal-0.3-rc-2.jar b/plugins/gradle/lib/native-platform-osx-universal-0.3-rc-2.jar
deleted file mode 100644
index 5942383..0000000
--- a/plugins/gradle/lib/native-platform-osx-universal-0.3-rc-2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-windows-amd64-0.10.jar b/plugins/gradle/lib/native-platform-windows-amd64-0.10.jar
new file mode 100644
index 0000000..1af9e03
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-windows-amd64-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-windows-amd64-0.3-rc-2.jar b/plugins/gradle/lib/native-platform-windows-amd64-0.3-rc-2.jar
deleted file mode 100644
index d048493..0000000
--- a/plugins/gradle/lib/native-platform-windows-amd64-0.3-rc-2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-windows-i386-0.10.jar b/plugins/gradle/lib/native-platform-windows-i386-0.10.jar
new file mode 100644
index 0000000..65ffaae
--- /dev/null
+++ b/plugins/gradle/lib/native-platform-windows-i386-0.10.jar
Binary files differ
diff --git a/plugins/gradle/lib/native-platform-windows-i386-0.3-rc-2.jar b/plugins/gradle/lib/native-platform-windows-i386-0.3-rc-2.jar
deleted file mode 100644
index 47b6430..0000000
--- a/plugins/gradle/lib/native-platform-windows-i386-0.3-rc-2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/lib/slf4j-api-1.7.2.jar b/plugins/gradle/lib/slf4j-api-1.7.5.jar
similarity index 80%
rename from plugins/gradle/lib/slf4j-api-1.7.2.jar
rename to plugins/gradle/lib/slf4j-api-1.7.5.jar
index 1a88708..8f004d3 100644
--- a/plugins/gradle/lib/slf4j-api-1.7.2.jar
+++ b/plugins/gradle/lib/slf4j-api-1.7.5.jar
Binary files differ
diff --git a/plugins/gradle/lib/slf4j-simple-1.7.2.jar b/plugins/gradle/lib/slf4j-simple-1.7.2.jar
deleted file mode 100644
index 2498c44..0000000
--- a/plugins/gradle/lib/slf4j-simple-1.7.2.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java
index 592b668..7ac9906 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/UseDistributionWithSourcesNotificationProvider.java
@@ -65,14 +65,14 @@
  * @since 9/13/13
  */
 public class UseDistributionWithSourcesNotificationProvider extends EditorNotifications.Provider<EditorNotificationPanel> {
-  public static final Pattern GRADLE_SRC_DISTIBUTION_PATTERN;
+  public static final Pattern GRADLE_SRC_DISTRIBUTION_PATTERN;
   private static final Logger LOG = Logger.getInstance("#" + UseDistributionWithSourcesNotificationProvider.class.getName());
   private static final Key<EditorNotificationPanel> KEY = Key.create("gradle.notifications.use.distribution.with.sources");
   private static final String ALL_ZIP_DISTRIBUTION_URI_SUFFIX = "-all.zip";
   private final Project myProject;
 
   static {
-    GRADLE_SRC_DISTIBUTION_PATTERN = Pattern.compile("http\\\\?://services\\.gradle\\.org.*" + ALL_ZIP_DISTRIBUTION_URI_SUFFIX);
+    GRADLE_SRC_DISTRIBUTION_PATTERN = Pattern.compile("https?\\\\?://services\\.gradle\\.org.*" + ALL_ZIP_DISTRIBUTION_URI_SUFFIX);
   }
 
   public UseDistributionWithSourcesNotificationProvider(Project project, final EditorNotifications notifications) {
@@ -190,7 +190,7 @@
     // currently only wrapped distribution takes into account
     if (wrapperConfiguration == null) return true;
     String distributionUri = wrapperConfiguration.getDistribution().toString();
-    return GRADLE_SRC_DISTIBUTION_PATTERN.matcher(distributionUri).matches();
+    return GRADLE_SRC_DISTRIBUTION_PATTERN.matcher(distributionUri).matches();
   }
 
   @Nullable
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/javaee/JavaEEGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/javaee/JavaEEGradleProjectResolverExtension.java
index 9779d6e..f1230b81 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/javaee/JavaEEGradleProjectResolverExtension.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/javaee/JavaEEGradleProjectResolverExtension.java
@@ -24,7 +24,7 @@
 import com.intellij.util.containers.ContainerUtil;
 import org.gradle.tooling.model.idea.IdeaModule;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.model.WebConfiguration;
+import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
 import org.jetbrains.plugins.gradle.model.data.War;
 import org.jetbrains.plugins.gradle.model.data.WarDirectory;
 import org.jetbrains.plugins.gradle.model.data.WebConfigurationModelData;
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/scala/ScalaGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/scala/ScalaGradleProjectResolverExtension.java
index 657d064..126fde8 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/scala/ScalaGradleProjectResolverExtension.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/scala/ScalaGradleProjectResolverExtension.java
@@ -24,9 +24,9 @@
 import org.jetbrains.annotations.Contract;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.ScalaCompileOptions;
-import org.jetbrains.plugins.gradle.model.ScalaForkOptions;
-import org.jetbrains.plugins.gradle.model.ScalaModel;
+import org.jetbrains.plugins.gradle.model.scala.ScalaCompileOptions;
+import org.jetbrains.plugins.gradle.model.scala.ScalaForkOptions;
+import org.jetbrains.plugins.gradle.model.scala.ScalaModel;
 import org.jetbrains.plugins.gradle.model.data.ScalaCompileOptionsData;
 import org.jetbrains.plugins.gradle.model.data.ScalaModelData;
 import org.jetbrains.plugins.gradle.service.project.AbstractProjectResolverExtension;
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/data/BuildScriptClasspathData.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/data/BuildScriptClasspathData.java
index 0f52cd8..60ff0c4 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/data/BuildScriptClasspathData.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/data/BuildScriptClasspathData.java
@@ -19,13 +19,11 @@
 import com.intellij.openapi.externalSystem.model.ProjectKeys;
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.AbstractExternalEntityData;
-import com.intellij.openapi.util.io.FileUtil;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
-import java.io.File;
 import java.io.Serializable;
 import java.util.List;
+import java.util.Set;
 
 /**
  * @author Vladislav.Soroka
@@ -56,32 +54,32 @@
     private static final long serialVersionUID = 1L;
 
     @NotNull
-    private final File myClassesFile;
+    private final Set<String> myClassesFile;
 
-    @Nullable
-    private final File mySourcesFile;
+    @NotNull
+    private final Set<String> mySourcesFile;
 
-    @Nullable
-    private final File myJavadocFile;
+    @NotNull
+    private final Set<String> myJavadocFile;
 
-    public ClasspathEntry(@NotNull File classesFile, @Nullable File sourcesFile, @Nullable File javadocFile) {
+    public ClasspathEntry(@NotNull Set<String> classesFile, @NotNull Set<String> sourcesFile, @NotNull Set<String> javadocFile) {
       myClassesFile = classesFile;
       mySourcesFile = sourcesFile;
       myJavadocFile = javadocFile;
     }
 
     @NotNull
-    public File getClassesFile() {
+    public Set<String> getClassesFile() {
       return myClassesFile;
     }
 
-    @Nullable
-    public File getSourcesFile() {
+    @NotNull
+    public Set<String> getSourcesFile() {
       return mySourcesFile;
     }
 
-    @Nullable
-    public File getJavadocFile() {
+    @NotNull
+    public Set<String> getJavadocFile() {
       return myJavadocFile;
     }
 
@@ -92,18 +90,18 @@
 
       ClasspathEntry entry = (ClasspathEntry)o;
 
-      if (!FileUtil.filesEqual(myClassesFile, entry.myClassesFile)) return false;
-      if (!FileUtil.filesEqual(myJavadocFile, entry.myJavadocFile)) return false;
-      if (!FileUtil.filesEqual(mySourcesFile, entry.mySourcesFile)) return false;
+      if (!myClassesFile.equals(entry.myClassesFile)) return false;
+      if (!myJavadocFile.equals(entry.myJavadocFile)) return false;
+      if (!mySourcesFile.equals(entry.mySourcesFile)) return false;
 
       return true;
     }
 
     @Override
     public int hashCode() {
-      int result = FileUtil.fileHashCode(myClassesFile);
-      result = 31 * result + FileUtil.fileHashCode(mySourcesFile);
-      result = 31 * result + FileUtil.fileHashCode(myJavadocFile);
+      int result = myClassesFile.hashCode();
+      result = 31 * result + mySourcesFile.hashCode();
+      result = 31 * result + myJavadocFile.hashCode();
       return result;
     }
   }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java
index 542558b..9b1b288 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/BaseGradleProjectResolverExtension.java
@@ -57,6 +57,7 @@
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.gradle.model.*;
 import org.jetbrains.plugins.gradle.model.data.BuildScriptClasspathData;
+import org.jetbrains.plugins.gradle.tooling.internal.init.Init;
 import org.jetbrains.plugins.gradle.util.GradleBundle;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
 import org.jetbrains.plugins.gradle.util.GradleUtil;
@@ -157,7 +158,7 @@
         ContainerUtil.map(buildScriptClasspathModel.getClasspath(), new Function<ClasspathEntryModel, BuildScriptClasspathData.ClasspathEntry>() {
           @Override
           public BuildScriptClasspathData.ClasspathEntry fun(ClasspathEntryModel model) {
-            return new BuildScriptClasspathData.ClasspathEntry(model.getClassesFile(), model.getSourcesFile(), model.getJavadocFile());
+            return new BuildScriptClasspathData.ClasspathEntry(model.getClasses(), model.getSources(), model.getJavadoc());
           }
         });
       BuildScriptClasspathData buildScriptClasspathData =
@@ -236,11 +237,7 @@
   public void populateModuleDependencies(@NotNull IdeaModule gradleModule,
                                          @NotNull DataNode<ModuleData> ideModule,
                                          @NotNull DataNode<ProjectData> ideProject) {
-
-    ProjectDependenciesModel dependenciesModel = resolverCtx.getExtraProject(gradleModule, ProjectDependenciesModel.class);
-
-    final List<? extends IdeaDependency> dependencies =
-      dependenciesModel != null ? dependenciesModel.getDependencies() : gradleModule.getDependencies().getAll();
+    final List<? extends IdeaDependency> dependencies = gradleModule.getDependencies().getAll();
 
     if (dependencies == null) return;
 
@@ -302,7 +299,7 @@
   @Override
   public Set<Class> getExtraProjectModelClasses() {
     return ContainerUtil.<Class>set(
-      GradleBuild.class, ModuleExtendedModel.class, ProjectDependenciesModel.class, BuildScriptClasspathModel.class);
+      GradleBuild.class, ModuleExtendedModel.class, BuildScriptClasspathModel.class);
   }
 
   @NotNull
@@ -372,6 +369,7 @@
     ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ModuleType.class));
     ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(EmptyModuleType.class));
     ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(ProjectImportAction.class));
+    ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(Init.class));
     for (String entry : additionalEntries) {
       classPath.add(entry);
     }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java
index 0af4476..031532a 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/DistributionFactoryExt.java
@@ -40,7 +40,6 @@
   private final File userHomeDir;
 
   public DistributionFactoryExt(File userHomeDir) {
-    super(userHomeDir);
     this.userHomeDir = userHomeDir;
   }
 
@@ -51,7 +50,7 @@
     //noinspection UseOfSystemOutOrSystemErr
     WrapperExecutor wrapper = WrapperExecutor.forWrapperPropertiesFile(propertiesFile, System.out);
     if (wrapper.getDistribution() != null) {
-      return new ZippedDistribution(wrapper.getConfiguration());
+      return new ZippedDistribution(wrapper.getConfiguration(), userHomeDir);
     }
     return getDownloadedDistribution(GradleVersion.current().getVersion());
   }
@@ -96,7 +95,7 @@
       return displayName;
     }
 
-    public ClassPath getToolingImplementationClasspath(ProgressLoggerFactory progressLoggerFactory) {
+    public ClassPath getToolingImplementationClasspath(ProgressLoggerFactory progressLoggerFactory, File userHomeDir) {
       ProgressLogger progressLogger = progressLoggerFactory.newOperation(DistributionFactory.class);
       progressLogger.setDescription("Validate distribution");
       progressLogger.started();
@@ -131,23 +130,27 @@
     }
   }
 
-  private class ZippedDistribution implements Distribution {
-    private final WrapperConfiguration wrapperConfiguration;
+  private static class ZippedDistribution implements Distribution {
     private InstalledDistribution installedDistribution;
+    private final WrapperConfiguration wrapperConfiguration;
+    private final File myUserHomeDir;
 
-    private ZippedDistribution(WrapperConfiguration wrapperConfiguration) {
+    private ZippedDistribution(WrapperConfiguration wrapperConfiguration, File userHomeDir) {
       this.wrapperConfiguration = wrapperConfiguration;
+      myUserHomeDir = userHomeDir;
     }
 
     public String getDisplayName() {
       return String.format("Gradle distribution '%s'", wrapperConfiguration.getDistribution());
     }
 
-    public ClassPath getToolingImplementationClasspath(ProgressLoggerFactory progressLoggerFactory) {
+    public ClassPath getToolingImplementationClasspath(ProgressLoggerFactory progressLoggerFactory, File userHomeDir) {
       if (installedDistribution == null) {
         File installDir;
         try {
-          Install install = new Install(new ProgressReportingDownload(progressLoggerFactory), new PathAssembler(userHomeDir));
+          File realUserHomeDir =
+            userHomeDir != null ? userHomeDir : myUserHomeDir != null ? myUserHomeDir : GradleUserHomeLookup.gradleUserHome();
+          Install install = new Install(new ProgressReportingDownload(progressLoggerFactory), new PathAssembler(realUserHomeDir));
           installDir = install.createDist(wrapperConfiguration);
         }
         catch (FileNotFoundException e) {
@@ -159,7 +162,7 @@
         }
         installedDistribution = new InstalledDistribution(installDir, getDisplayName(), getDisplayName());
       }
-      return installedDistribution.getToolingImplementationClasspath(progressLoggerFactory);
+      return installedDistribution.getToolingImplementationClasspath(progressLoggerFactory, userHomeDir);
     }
   }
 }
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 d358925b..3a761b5 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
@@ -35,10 +35,11 @@
 import org.gradle.tooling.model.build.BuildEnvironment;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.ProjectImportAction;
 import org.jetbrains.plugins.gradle.settings.DistributionType;
 import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
+import org.jetbrains.plugins.gradle.tooling.internal.init.Init;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
+import org.jetbrains.plugins.gradle.util.GradleEnvironment;
 import org.jetbrains.plugins.gradle.util.GradleUtil;
 
 import java.io.File;
@@ -188,16 +189,13 @@
       projectDir = projectPath;
     }
 
-    // This is a workaround to get right base dir in case of 'PROJECT' setting used in case custom wrapper property file location
-    // see org.gradle.wrapper.PathAssembler#getBaseDir for details
     String userDir = null;
-    if (settings != null && settings.getDistributionType() == DistributionType.WRAPPED) {
+    if (!GradleEnvironment.ADJUST_USER_DIR) {
       try {
         userDir = System.getProperty("user.dir");
-        System.setProperty("user.dir", projectDir);
+        if (userDir != null) System.setProperty("user.dir", projectDir);
       }
-      catch (Exception e) {
-        // ignore
+      catch (Exception ignore) {
       }
     }
     ProjectConnection connection = getConnection(projectDir, settings);
@@ -385,7 +383,7 @@
 
   @Nullable
   public static File generateInitScript(boolean isBuildSrcProject) {
-    InputStream stream = ProjectImportAction.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init.gradle");
+    InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init/init.gradle");
     try {
       if (stream == null) {
         LOG.warn("Can't get init script template");
@@ -413,8 +411,7 @@
 
   @Nullable
   public static String getBuildSrcDefaultInitScript() {
-    InputStream stream =
-      ProjectImportAction.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle");
+    InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init/buildSrcInit.gradle");
     try {
       if (stream == null) return null;
       return FileUtil.loadTextAndClose(stream);
@@ -464,8 +461,7 @@
       }
       buf.append(']');
 
-      InputStream stream =
-        ProjectImportAction.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/testFilterInit.gradle");
+      InputStream stream = Init.class.getResourceAsStream("/org/jetbrains/plugins/gradle/tooling/internal/init/testFilterInit.gradle");
       try {
         if (stream == null) {
           LOG.warn("Can't get test filter init script template");
@@ -488,14 +484,10 @@
   @NotNull
   private static String getToolingExtensionsJarPaths() throws ClassNotFoundException {
     final ArrayList<Class<?>> list = ContainerUtil.newArrayList(
-      // add gradle-tooling-extension jar
+      // add gradle-tooling-extension-api jar
       Class.forName("org.jetbrains.plugins.gradle.model.ProjectImportAction"),
-      // add gradle-tooling-extension-v1.9 jar
-      Class.forName("org.jetbrains.plugins.gradle.tooling.v1_9.builder.ModelBuildScriptClasspathBuilderImpl"),
-      // add gradle-tooling-extension-v1.11 jar
-      Class.forName("org.jetbrains.plugins.gradle.tooling.v1_11.builder.ModelBuildScriptClasspathBuilderImpl"),
-      // add gradle-tooling-extension-v1.12 jar
-      Class.forName("org.jetbrains.plugins.gradle.tooling.v1_12.builder.ModelBuildScriptClasspathBuilderImpl")
+      // add gradle-tooling-extension-impl jar
+      Class.forName("org.jetbrains.plugins.gradle.tooling.builder.ModelBuildScriptClasspathBuilderImpl")
     );
 
     StringBuilder buf = new StringBuilder();
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java
index 928a8f9..785159f 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/data/BuildClasspathModuleGradleDataService.java
@@ -121,10 +121,13 @@
         final Set<String> buildClasspath = ContainerUtil.newLinkedHashSet();
         BuildScriptClasspathData buildScriptClasspathData = node.getData();
         for (BuildScriptClasspathData.ClasspathEntry classpathEntry : buildScriptClasspathData.getClasspathEntries()) {
-          if (classpathEntry.getSourcesFile() != null) {
-            buildClasspath.add(FileUtil.toCanonicalPath(classpathEntry.getSourcesFile().getPath()));
+          for (String path : classpathEntry.getSourcesFile()) {
+            buildClasspath.add(FileUtil.toCanonicalPath(path));
           }
-          buildClasspath.add(FileUtil.toCanonicalPath(classpathEntry.getClassesFile().getPath()));
+
+          for (String path : classpathEntry.getClassesFile()) {
+            buildClasspath.add(FileUtil.toCanonicalPath(path));
+          }
         }
 
         ExternalProjectBuildClasspathPojo projectBuildClasspathPojo =
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/GradleProjectImportBuilder.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/GradleProjectImportBuilder.java
index cfb51f9..93955a3 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/GradleProjectImportBuilder.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/wizard/GradleProjectImportBuilder.java
@@ -62,7 +62,7 @@
 
   @Override
   protected void doPrepare(@NotNull WizardContext context) {
-    String pathToUse = context.getProjectFileDirectory();
+    String pathToUse = getFileToImport();
     VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByPath(pathToUse);
     if (file != null && file.isDirectory()) {
       pathToUse = new File(pathToUse, GradleConstants.DEFAULT_SCRIPT_NAME).getAbsolutePath();
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleEnvironment.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleEnvironment.java
index cdd8afb..2c61ac6 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleEnvironment.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleEnvironment.java
@@ -11,6 +11,7 @@
 
   @NonNls public static final boolean DEBUG_GRADLE_HOME_PROCESSING = Boolean.getBoolean("gradle.debug.home.processing");
   @NonNls public static final boolean DISABLE_ENHANCED_TOOLING_API = Boolean.getBoolean("gradle.disable.enhanced.tooling.api");
+  @NonNls public static final boolean ADJUST_USER_DIR = Boolean.getBoolean("gradle.adjust.userdir");
 
   private GradleEnvironment() {
   }
diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandlerTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandlerTest.java
index 7de9362..a8f4267 100644
--- a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandlerTest.java
+++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/service/project/BaseProjectImportErrorHandlerTest.java
@@ -16,7 +16,7 @@
 package org.jetbrains.plugins.gradle.service.project;
 
 import com.intellij.openapi.externalSystem.model.LocationAwareExternalSystemException;
-import org.gradle.api.internal.LocationAwareException;
+import org.gradle.internal.exceptions.LocationAwareException;
 import org.jetbrains.annotations.NotNull;
 import org.junit.Before;
 import org.junit.Test;
diff --git a/plugins/gradle/tooling-extension-api/gradle-tooling-extension-api.iml b/plugins/gradle/tooling-extension-api/gradle-tooling-extension-api.iml
new file mode 100644
index 0000000..d360db2
--- /dev/null
+++ b/plugins/gradle/tooling-extension-api/gradle-tooling-extension-api.iml
@@ -0,0 +1,124 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="external-system-api" />
+    <orderEntry type="module" module-name="annotations" />
+    <orderEntry type="module" module-name="testFramework" scope="TEST" />
+    <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
+    <orderEntry type="module-library">
+      <library name="Gradle">
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/../lib/gradle-tooling-api-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-core-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-messaging-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-wrapper-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-base-services-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-native-1.12-rc-1.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES>
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/buildSrc/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/buildSrc/src/test/resources" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ui/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ui/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ui/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/cli/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/cpp/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/cpp/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ear/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/resources" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ivy/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/osgi/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/osgi/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/antlr/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/jetty/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/maven/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/maven/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/scala/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/scala/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/jacoco/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/native/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/plugins/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/plugins/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/plugins/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/publish/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/wrapper/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/wrapper/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/announce/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/launcher/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/launcher/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/launcher/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/open-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/open-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core-impl/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core-impl/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/messaging/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/messaging/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/reporting/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/resources/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/javascript/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/diagnostics/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/diagnostics/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/diagnostics/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/performance/src/configPlugin" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/performance/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/code-quality/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/tasks" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-jvm/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-base/src/main/groovy/org/gradle/language/base/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-base/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-comparison/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/internal-testing/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services-groovy/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services-groovy/src/test/groovy" />
+        </SOURCES>
+      </library>
+    </orderEntry>
+    <orderEntry type="module-library" scope="PROVIDED">
+      <library name="GradleGuava">
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/../lib/guava-jdk5-14.0.1.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES />
+      </library>
+    </orderEntry>
+    <orderEntry type="library" scope="PROVIDED" name="Groovy" level="project" />
+  </component>
+</module>
+
diff --git a/plugins/gradle/tooling-extension-api/lib/gradle-build-init-1.12-rc-1.jar b/plugins/gradle/tooling-extension-api/lib/gradle-build-init-1.12-rc-1.jar
new file mode 100644
index 0000000..4c0fd38
--- /dev/null
+++ b/plugins/gradle/tooling-extension-api/lib/gradle-build-init-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/tooling-extension-api/lib/gradle-ide-1.12-rc-1.jar b/plugins/gradle/tooling-extension-api/lib/gradle-ide-1.12-rc-1.jar
new file mode 100644
index 0000000..0177613
--- /dev/null
+++ b/plugins/gradle/tooling-extension-api/lib/gradle-ide-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/tooling-extension-api/lib/gradle-plugins-1.12-rc-1.jar b/plugins/gradle/tooling-extension-api/lib/gradle-plugins-1.12-rc-1.jar
new file mode 100644
index 0000000..983c8fe
--- /dev/null
+++ b/plugins/gradle/tooling-extension-api/lib/gradle-plugins-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/tooling-extension-api/lib/gradle-scala-1.12-rc-1.jar b/plugins/gradle/tooling-extension-api/lib/gradle-scala-1.12-rc-1.jar
new file mode 100644
index 0000000..c8382f4
--- /dev/null
+++ b/plugins/gradle/tooling-extension-api/lib/gradle-scala-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/BuildScriptClasspathModel.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/BuildScriptClasspathModel.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/BuildScriptClasspathModel.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/BuildScriptClasspathModel.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ClasspathEntryModel.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ClasspathEntryModel.java
similarity index 82%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ClasspathEntryModel.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ClasspathEntryModel.java
index 09120ca..b36a6e4 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ClasspathEntryModel.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ClasspathEntryModel.java
@@ -16,9 +16,8 @@
 package org.jetbrains.plugins.gradle.model;
 
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
-import java.io.File;
+import java.util.Set;
 
 /**
  * @author Vladislav.Soroka
@@ -26,11 +25,11 @@
  */
 public interface ClasspathEntryModel {
   @NotNull
-  File getClassesFile();
+  Set<String> getClasses();
 
-  @Nullable
-  File getSourcesFile();
+  @NotNull
+  Set<String> getSources();
 
-  @Nullable
-  File getJavadocFile();
+  @NotNull
+  Set<String> getJavadoc();
 }
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ExtIdeaContentRoot.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ExtIdeaContentRoot.java
similarity index 99%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ExtIdeaContentRoot.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ExtIdeaContentRoot.java
index c03433d..45dd0ed 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ExtIdeaContentRoot.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ExtIdeaContentRoot.java
@@ -28,5 +28,6 @@
 public interface ExtIdeaContentRoot extends IdeaContentRoot, Serializable {
 
   DomainObjectSet<? extends IdeaSourceDirectory> getResourceDirectories();
+
   DomainObjectSet<? extends IdeaSourceDirectory> getTestResourceDirectories();
 }
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ModuleExtendedModel.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ModuleExtendedModel.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ModuleExtendedModel.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ModuleExtendedModel.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ProjectImportAction.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ProjectImportAction.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ProjectImportAction.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/ProjectImportAction.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaCompileOptions.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaCompileOptions.java
similarity index 95%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaCompileOptions.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaCompileOptions.java
index 596659a..4e8746c 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaCompileOptions.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaCompileOptions.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model;
+package org.jetbrains.plugins.gradle.model.scala;
 
 import java.io.Serializable;
 import java.util.List;
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaForkOptions.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaForkOptions.java
similarity index 94%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaForkOptions.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaForkOptions.java
index 9dd0cef..f8f36cf 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaForkOptions.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaForkOptions.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model;
+package org.jetbrains.plugins.gradle.model.scala;
 
 import java.io.Serializable;
 import java.util.List;
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaModel.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaModel.java
similarity index 93%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaModel.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaModel.java
index 7e72400..6983913 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ScalaModel.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/scala/ScalaModel.java
@@ -13,11 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model;
+package org.jetbrains.plugins.gradle.model.scala;
 
 import java.io.File;
 import java.io.Serializable;
-import java.util.Map;
 import java.util.Set;
 
 /**
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/WebConfiguration.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/web/WebConfiguration.java
similarity index 96%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/WebConfiguration.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/web/WebConfiguration.java
index c2ed1eb..9d6ef8e 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/WebConfiguration.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/model/web/WebConfiguration.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model;
+package org.jetbrains.plugins.gradle.model.web;
 
 import org.jetbrains.annotations.NotNull;
 
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/ModelBuilderService.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/tooling/ModelBuilderService.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/ModelBuilderService.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/tooling/ModelBuilderService.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/annotation/TargetVersions.java b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/tooling/annotation/TargetVersions.java
similarity index 99%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/annotation/TargetVersions.java
rename to plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/tooling/annotation/TargetVersions.java
index a5d81fb..c9e7287 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/annotation/TargetVersions.java
+++ b/plugins/gradle/tooling-extension-api/src/org/jetbrains/plugins/gradle/tooling/annotation/TargetVersions.java
@@ -24,5 +24,6 @@
 @Target(ElementType.TYPE)
 public @interface TargetVersions {
   String value();
+
   boolean checkBaseVersions() default true;
 }
diff --git a/plugins/gradle/tooling-extension-impl/gradle-tooling-extension-impl.iml b/plugins/gradle/tooling-extension-impl/gradle-tooling-extension-impl.iml
new file mode 100644
index 0000000..6056252
--- /dev/null
+++ b/plugins/gradle/tooling-extension-impl/gradle-tooling-extension-impl.iml
@@ -0,0 +1,135 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<module type="JAVA_MODULE" version="4">
+  <component name="NewModuleRootManager" inherit-compiler-output="true">
+    <exclude-output />
+    <content url="file://$MODULE_DIR$">
+      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
+      <sourceFolder url="file://$MODULE_DIR$/testData" type="java-test-resource" />
+      <sourceFolder url="file://$MODULE_DIR$/testSources" isTestSource="true" />
+    </content>
+    <orderEntry type="inheritedJdk" />
+    <orderEntry type="sourceFolder" forTests="false" />
+    <orderEntry type="module" module-name="annotations" />
+    <orderEntry type="module" module-name="external-system-api" />
+    <orderEntry type="module" module-name="gradle-tooling-extension-api" />
+    <orderEntry type="module" module-name="gradle" scope="TEST" />
+    <orderEntry type="module" module-name="testFramework" scope="TEST" />
+    <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
+    <orderEntry type="module-library">
+      <library name="Gradle">
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/../lib/gradle-tooling-api-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-core-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-messaging-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-wrapper-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-base-services-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-native-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../tooling-extension-api/lib/gradle-build-init-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../tooling-extension-api/lib/gradle-plugins-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../tooling-extension-api/lib/gradle-ide-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/../tooling-extension-api/lib/gradle-scala-1.12-rc-1.jar!/" />
+          <root url="jar://$MODULE_DIR$/lib/gradle-reporting-1.12-rc-1.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES>
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/buildSrc/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/buildSrc/src/test/resources" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ui/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ui/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ui/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/cli/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/cpp/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/cpp/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ear/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/resources" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ivy/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/osgi/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/osgi/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/antlr/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/jetty/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/maven/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/maven/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/scala/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/scala/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/jacoco/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/native/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/plugins/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/plugins/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/plugins/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/publish/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/wrapper/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/wrapper/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/announce/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/launcher/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/launcher/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/launcher/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/open-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/open-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core-impl/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/core-impl/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/messaging/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/messaging/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/reporting/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/resources/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/javascript/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/diagnostics/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/diagnostics/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/diagnostics/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/performance/src/configPlugin" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/performance/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/integTest/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/tooling-api/src/testFixtures/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/code-quality/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/tasks" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-jvm/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-base/src/main/groovy/org/gradle/language/base/plugins" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/language-base/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-comparison/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/internal-testing/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services-groovy/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/base-services-groovy/src/test/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/groovy" />
+          <root url="jar://$MODULE_DIR$/../lib/gradle-1.12-rc-1-src.zip!/gradle-1.12-rc-1/subprojects/ide/src/main/java" />
+        </SOURCES>
+      </library>
+    </orderEntry>
+    <orderEntry type="module-library">
+      <library name="GradleGuava">
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/../lib/guava-jdk5-14.0.1.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES />
+      </library>
+    </orderEntry>
+    <orderEntry type="library" name="Groovy" level="project" />
+  </component>
+</module>
+
diff --git a/plugins/gradle/tooling-extension-v1.9/lib/gradle-reporting-1.9.jar b/plugins/gradle/tooling-extension-impl/lib/gradle-reporting-1.12-rc-1.jar
similarity index 61%
rename from plugins/gradle/tooling-extension-v1.9/lib/gradle-reporting-1.9.jar
rename to plugins/gradle/tooling-extension-impl/lib/gradle-reporting-1.12-rc-1.jar
index 5315525..13f412f 100644
--- a/plugins/gradle/tooling-extension-v1.9/lib/gradle-reporting-1.9.jar
+++ b/plugins/gradle/tooling-extension-impl/lib/gradle-reporting-1.12-rc-1.jar
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.12/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService b/plugins/gradle/tooling-extension-impl/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
similarity index 66%
rename from plugins/gradle/tooling-extension-v1.12/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
rename to plugins/gradle/tooling-extension-impl/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
index 8af48ec..244e58d 100644
--- a/plugins/gradle/tooling-extension-v1.12/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
+++ b/plugins/gradle/tooling-extension-impl/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
@@ -13,5 +13,7 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
-org.jetbrains.plugins.gradle.tooling.v1_12.builder.ModelDependenciesBuilderImpl
-org.jetbrains.plugins.gradle.tooling.v1_12.builder.ModelBuildScriptClasspathBuilderImpl
+org.jetbrains.plugins.gradle.tooling.builder.WarModelBuilderImpl
+org.jetbrains.plugins.gradle.tooling.builder.ModuleExtendedModelBuilderImpl
+org.jetbrains.plugins.gradle.tooling.builder.ModelBuildScriptClasspathBuilderImpl
+org.jetbrains.plugins.gradle.tooling.builder.ScalaModelBuilderImpl
diff --git a/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImpl.java
new file mode 100644
index 0000000..ad3a731
--- /dev/null
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImpl.java
@@ -0,0 +1,106 @@
+/*
+ * Copyright 2000-2014 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.tooling.builder;
+
+import org.gradle.api.Project;
+import org.gradle.api.artifacts.Configuration;
+import org.gradle.plugins.ide.idea.IdeaPlugin;
+import org.gradle.plugins.ide.idea.model.Dependency;
+import org.gradle.plugins.ide.idea.model.ModuleLibrary;
+import org.gradle.plugins.ide.idea.model.Path;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.gradle.model.BuildScriptClasspathModel;
+import org.jetbrains.plugins.gradle.model.ClasspathEntryModel;
+import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
+import org.jetbrains.plugins.gradle.tooling.internal.BuildScriptClasspathModelImpl;
+import org.jetbrains.plugins.gradle.tooling.internal.ClasspathEntryModelImpl;
+
+import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 12/20/13
+ */
+public class ModelBuildScriptClasspathBuilderImpl implements ModelBuilderService {
+
+  private final Map<String, BuildScriptClasspathModelImpl> cache = new ConcurrentHashMap<String, BuildScriptClasspathModelImpl>();
+
+  @Override
+  public boolean canBuild(String modelName) {
+    return BuildScriptClasspathModel.class.getName().equals(modelName);
+  }
+
+  @Nullable
+  @Override
+  public Object buildAll(final String modelName, final Project project) {
+    BuildScriptClasspathModelImpl buildScriptClasspath = cache.get(project.getPath());
+    if (buildScriptClasspath != null) return buildScriptClasspath;
+
+    buildScriptClasspath = new BuildScriptClasspathModelImpl();
+    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
+    if (ideaPlugin != null) {
+      Project parent = project.getParent();
+      if (parent != null) {
+        BuildScriptClasspathModelImpl parentBuildScriptClasspath = (BuildScriptClasspathModelImpl)buildAll(modelName, parent);
+        if (parentBuildScriptClasspath != null) {
+          for (ClasspathEntryModel classpathEntryModel : parentBuildScriptClasspath.getClasspath()) {
+            buildScriptClasspath.add(classpathEntryModel);
+          }
+        }
+      }
+      final Configuration configuration = project.getBuildscript().getConfigurations().findByName("classpath");
+      Collection<Configuration> plusConfigurations = Collections.singletonList(configuration);
+
+      final Map<String, Map<String, Collection<Configuration>>> scopes =
+        new HashMap<String, Map<String, Collection<Configuration>>>(ideaPlugin.getModel().getModule().getScopes());
+
+      Map<String, Map<String, Collection<Configuration>>> buildScriptScope = new HashMap<String, Map<String, Collection<Configuration>>>();
+      Map<String, Collection<Configuration>> plusConfiguration = new HashMap<String, Collection<Configuration>>();
+      plusConfiguration.put("plus", plusConfigurations);
+      if (scopes.get("COMPILE") != null) {
+        plusConfiguration.put("minus", scopes.get("COMPILE").get("plus"));
+      }
+      buildScriptScope.put("COMPILE", plusConfiguration);
+      ideaPlugin.getModel().getModule().setScopes(buildScriptScope);
+      ideaPlugin.getModel().getModule().getProject().getConfigurations().add(configuration);
+      final Set<Dependency> buildScriptDependencies = ideaPlugin.getModel().getModule().resolveDependencies();
+      for (Dependency dependency : buildScriptDependencies) {
+        if (dependency instanceof ModuleLibrary) {
+          ModuleLibrary moduleLibrary = (ModuleLibrary)dependency;
+          if ("COMPILE".equals(moduleLibrary.getScope())) {
+            buildScriptClasspath.add(new ClasspathEntryModelImpl(
+              convert(moduleLibrary.getClasses()), convert(moduleLibrary.getSources()), convert(moduleLibrary.getJavadoc())));
+          }
+        }
+      }
+
+      ideaPlugin.getModel().getModule().setScopes(scopes);
+      ideaPlugin.getModel().getModule().getProject().getConfigurations().remove(configuration);
+    }
+
+    cache.put(project.getPath(), buildScriptClasspath);
+    return buildScriptClasspath;
+  }
+
+  private static Set<String> convert(Set<Path> paths) {
+    Set<String> result = new HashSet<String>(paths.size());
+    for (Path path : paths) {
+      result.add(path.getRelPath());
+    }
+    return result;
+  }
+}
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModuleExtendedModelBuilderImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImpl.java
similarity index 97%
rename from plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModuleExtendedModelBuilderImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImpl.java
index 42d20e9..348c2c7 100644
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModuleExtendedModelBuilderImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.tooling.v1_9.builder;
+package org.jetbrains.plugins.gradle.tooling.builder;
 
 import groovy.lang.GroovyObject;
 import org.gradle.api.Project;
@@ -97,7 +97,7 @@
       if (sourceSets instanceof SourceSetContainer) {
         SourceSetContainer sourceSetContainer = (SourceSetContainer)sourceSets;
         for (SourceSet sourceSet : sourceSetContainer) {
-          for (File javaSrcDir : sourceSet.getJava().getSrcDirs()) {
+          for (File javaSrcDir : sourceSet.getAllJava().getSrcDirs()) {
             boolean isTestDir = isTestDir(sourceSet, testClassesDirs);
             addFilePath(isTestDir ? testDirectories : sourceDirectories, javaSrcDir);
           }
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ScalaModelBuilderImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ScalaModelBuilderImpl.java
similarity index 96%
rename from plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ScalaModelBuilderImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ScalaModelBuilderImpl.java
index b885b7f..37299522 100644
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ScalaModelBuilderImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/ScalaModelBuilderImpl.java
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.tooling.v1_9.builder;
+package org.jetbrains.plugins.gradle.tooling.builder;
 
 import org.gradle.api.Project;
 import org.gradle.api.Task;
@@ -23,7 +23,7 @@
 import org.gradle.api.tasks.scala.ScalaForkOptions;
 import org.jetbrains.annotations.Contract;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.ScalaModel;
+import org.jetbrains.plugins.gradle.model.scala.ScalaModel;
 import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
 import org.jetbrains.plugins.gradle.tooling.internal.scala.ScalaCompileOptionsImpl;
 import org.jetbrains.plugins.gradle.tooling.internal.scala.ScalaForkOptionsImpl;
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/WarModelBuilderImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/WarModelBuilderImpl.java
similarity index 92%
rename from plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/WarModelBuilderImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/WarModelBuilderImpl.java
index 2060653..e8d5d41 100644
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/WarModelBuilderImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/builder/WarModelBuilderImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -13,7 +13,7 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.tooling.v1_9.builder;
+package org.jetbrains.plugins.gradle.tooling.builder;
 
 import org.gradle.api.Action;
 import org.gradle.api.Project;
@@ -25,11 +25,11 @@
 import org.gradle.api.plugins.WarPlugin;
 import org.gradle.api.tasks.bundling.War;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.WebConfiguration;
+import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
 import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.internal.WarModelImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.WebConfigurationImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.WebResourceImpl;
+import org.jetbrains.plugins.gradle.tooling.internal.web.WarModelImpl;
+import org.jetbrains.plugins.gradle.tooling.internal.web.WebConfigurationImpl;
+import org.jetbrains.plugins.gradle.tooling.internal.web.WebResourceImpl;
 
 import java.io.File;
 import java.io.StringWriter;
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/BuildScriptClasspathModelImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/BuildScriptClasspathModelImpl.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/BuildScriptClasspathModelImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/BuildScriptClasspathModelImpl.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ClasspathEntryModelImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ClasspathEntryModelImpl.java
similarity index 62%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ClasspathEntryModelImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ClasspathEntryModelImpl.java
index 2a9783c..59b1e06 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ClasspathEntryModelImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ClasspathEntryModelImpl.java
@@ -16,11 +16,10 @@
 package org.jetbrains.plugins.gradle.tooling.internal;
 
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.gradle.model.ClasspathEntryModel;
 
-import java.io.File;
 import java.io.Serializable;
+import java.util.Set;
 
 /**
  * @author Vladislav.Soroka
@@ -28,33 +27,33 @@
  */
 public class ClasspathEntryModelImpl implements ClasspathEntryModel, Serializable {
   @NotNull
-  private final File classesFile;
-  @Nullable
-  private final File sourcesFile;
-  @Nullable
-  private final File javadocFile;
+  private final Set<String> classes;
+  @NotNull
+  private final Set<String> sources;
+  @NotNull
+  private final Set<String> javadoc;
 
-  public ClasspathEntryModelImpl(@NotNull File classesFile, @Nullable File sourcesFile, @Nullable File javadocFile) {
-    this.classesFile = classesFile;
-    this.sourcesFile = sourcesFile;
-    this.javadocFile = javadocFile;
+  public ClasspathEntryModelImpl(@NotNull Set<String> classes, @NotNull Set<String> sources, @NotNull Set<String> javadoc) {
+    this.classes = classes;
+    this.sources = sources;
+    this.javadoc = javadoc;
   }
 
   @NotNull
   @Override
-  public File getClassesFile() {
-    return classesFile;
+  public Set<String> getClasses() {
+    return classes;
   }
 
-  @Nullable
+  @NotNull
   @Override
-  public File getSourcesFile() {
-    return sourcesFile;
+  public Set<String> getSources() {
+    return sources;
   }
 
-  @Nullable
+  @NotNull
   @Override
-  public File getJavadocFile() {
-    return javadocFile;
+  public Set<String> getJavadoc() {
+    return javadoc;
   }
 }
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilder.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilder.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilder.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilder.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaContentRootImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaContentRootImpl.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaContentRootImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaContentRootImpl.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSourceDirectoryImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSourceDirectoryImpl.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSourceDirectoryImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSourceDirectoryImpl.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ModuleExtendedModelImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ModuleExtendedModelImpl.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ModuleExtendedModelImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/ModuleExtendedModelImpl.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/StubIdeaModule.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/StubIdeaModule.java
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/StubIdeaModule.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/StubIdeaModule.java
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/Init.java
similarity index 77%
copy from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
copy to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/Init.java
index 91140f2..8a6d08c 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/Init.java
@@ -13,13 +13,13 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+package org.jetbrains.plugins.gradle.tooling.internal.init;
 
-allprojects { project ->
-  if(project.name == 'buildSrc') {
-    apply plugin: 'groovy'
-    dependencies {
-      compile gradleApi()
-      compile localGroovy()
-    }
+/**
+ * @author Vladislav.Soroka
+ * @since 4/21/2014
+ */
+public class Init {
+  private Init() {
   }
-}
\ No newline at end of file
+}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/buildSrcInit.gradle
similarity index 94%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/buildSrcInit.gradle
index 91140f2..f2172f1 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/buildSrcInit.gradle
@@ -15,7 +15,7 @@
  */
 
 allprojects { project ->
-  if(project.name == 'buildSrc') {
+  if (project.name == 'buildSrc') {
     apply plugin: 'groovy'
     dependencies {
       compile gradleApi()
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/init.gradle b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/init.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/init.gradle
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/init.gradle
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/testFilterInit.gradle b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/testFilterInit.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/testFilterInit.gradle
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/init/testFilterInit.gradle
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaCompileOptionsImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaCompileOptionsImpl.java
similarity index 96%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaCompileOptionsImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaCompileOptionsImpl.java
index b40d0cb..ff3dc5a 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaCompileOptionsImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaCompileOptionsImpl.java
@@ -15,8 +15,8 @@
  */
 package org.jetbrains.plugins.gradle.tooling.internal.scala;
 
-import org.jetbrains.plugins.gradle.model.ScalaCompileOptions;
-import org.jetbrains.plugins.gradle.model.ScalaForkOptions;
+import org.jetbrains.plugins.gradle.model.scala.ScalaCompileOptions;
+import org.jetbrains.plugins.gradle.model.scala.ScalaForkOptions;
 
 import java.util.List;
 
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaForkOptionsImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaForkOptionsImpl.java
similarity index 95%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaForkOptionsImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaForkOptionsImpl.java
index cd5612d..2474fe6 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaForkOptionsImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaForkOptionsImpl.java
@@ -15,7 +15,7 @@
  */
 package org.jetbrains.plugins.gradle.tooling.internal.scala;
 
-import org.jetbrains.plugins.gradle.model.ScalaForkOptions;
+import org.jetbrains.plugins.gradle.model.scala.ScalaForkOptions;
 
 import java.util.List;
 
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaModelImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaModelImpl.java
similarity index 93%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaModelImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaModelImpl.java
index e019ca5..e52810c 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaModelImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/scala/ScalaModelImpl.java
@@ -15,8 +15,8 @@
  */
 package org.jetbrains.plugins.gradle.tooling.internal.scala;
 
-import org.jetbrains.plugins.gradle.model.ScalaCompileOptions;
-import org.jetbrains.plugins.gradle.model.ScalaModel;
+import org.jetbrains.plugins.gradle.model.scala.ScalaCompileOptions;
+import org.jetbrains.plugins.gradle.model.scala.ScalaModel;
 
 import java.io.File;
 import java.util.Set;
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WarModelImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WarModelImpl.java
similarity index 92%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WarModelImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WarModelImpl.java
index 67d492d..c348564 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WarModelImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WarModelImpl.java
@@ -13,19 +13,19 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.tooling.internal;
+package org.jetbrains.plugins.gradle.tooling.internal.web;
 
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.model.WebConfiguration;
+import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
 
 import java.io.File;
 import java.util.List;
 import java.util.Set;
 
 /**
-* @author Vladislav.Soroka
-* @since 2/10/14
-*/
+ * @author Vladislav.Soroka
+ * @since 2/10/14
+ */
 public class WarModelImpl implements WebConfiguration.WarModel {
   @NotNull
   private final String warName;
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WebConfigurationImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WebConfigurationImpl.java
similarity index 86%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WebConfigurationImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WebConfigurationImpl.java
index 8c0c9a5..8cbdd28 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WebConfigurationImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WebConfigurationImpl.java
@@ -13,14 +13,12 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.tooling.internal;
+package org.jetbrains.plugins.gradle.tooling.internal.web;
 
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.model.WebConfiguration;
+import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
 
-import java.io.File;
 import java.util.List;
-import java.util.Set;
 
 /**
  * @author Vladislav.Soroka
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WebResourceImpl.java b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WebResourceImpl.java
similarity index 92%
rename from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WebResourceImpl.java
rename to plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WebResourceImpl.java
index e449f06..37043c8 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/WebResourceImpl.java
+++ b/plugins/gradle/tooling-extension-impl/src/org/jetbrains/plugins/gradle/tooling/internal/web/WebResourceImpl.java
@@ -13,17 +13,17 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.tooling.internal;
+package org.jetbrains.plugins.gradle.tooling.internal.web;
 
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.model.WebConfiguration;
+import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
 
 import java.io.File;
 
 /**
-* @author Vladislav.Soroka
-* @since 2/10/14
-*/
+ * @author Vladislav.Soroka
+ * @since 2/10/14
+ */
 public class WebResourceImpl implements WebConfiguration.WebResource {
   @NotNull
   private final String myWarDirectory;
diff --git a/plugins/gradle/tooling-extension/testData/testDefaultDependenciesModel/build.gradle b/plugins/gradle/tooling-extension-impl/testData/testDefaultDependenciesModel/build.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testDefaultDependenciesModel/build.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testDefaultDependenciesModel/build.gradle
diff --git a/plugins/gradle/tooling-extension/testData/testDefaultDependenciesModel/settings.gradle b/plugins/gradle/tooling-extension-impl/testData/testDefaultDependenciesModel/settings.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testDefaultDependenciesModel/settings.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testDefaultDependenciesModel/settings.gradle
diff --git a/plugins/gradle/tooling-extension/testData/testDefaultWarModel/build.gradle b/plugins/gradle/tooling-extension-impl/testData/testDefaultWarModel/build.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testDefaultWarModel/build.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testDefaultWarModel/build.gradle
diff --git a/plugins/gradle/tooling-extension/testData/testDefaultWarModel/settings.gradle b/plugins/gradle/tooling-extension-impl/testData/testDefaultWarModel/settings.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testDefaultWarModel/settings.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testDefaultWarModel/settings.gradle
diff --git a/plugins/gradle/tooling-extension/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle b/plugins/gradle/tooling-extension-impl/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
similarity index 77%
rename from plugins/gradle/tooling-extension/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
index d4157ea..83fcd7a 100644
--- a/plugins/gradle/tooling-extension/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
+++ b/plugins/gradle/tooling-extension-impl/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
@@ -45,7 +45,11 @@
 
   idea {
     module {
-      scopes.COMPILE.plus += scopes.TEST.plus
+      if(GradleVersion.current().compareTo(GradleVersion.version('1.11')) > 0) {
+        scopes.COMPILE.plus = [configurations['testCompile'], configurations['testRuntime']]
+      } else {
+        scopes.COMPILE.plus += scopes.TEST.plus
+      }
       scopes.TEST.plus = []
     }
   }
diff --git a/plugins/gradle/tooling-extension/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle b/plugins/gradle/tooling-extension-impl/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle
diff --git a/plugins/gradle/tooling-extension/testData/testGradleSourcesSetsInterpretation/build.gradle b/plugins/gradle/tooling-extension-impl/testData/testGradleSourcesSetsInterpretation/build.gradle
similarity index 92%
rename from plugins/gradle/tooling-extension/testData/testGradleSourcesSetsInterpretation/build.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testGradleSourcesSetsInterpretation/build.gradle
index eb35c27..21dd96d 100644
--- a/plugins/gradle/tooling-extension/testData/testGradleSourcesSetsInterpretation/build.gradle
+++ b/plugins/gradle/tooling-extension-impl/testData/testGradleSourcesSetsInterpretation/build.gradle
@@ -11,6 +11,13 @@
   sourceSets.test.resources.srcDir 'src/test/java'
 }
 
+project("moduleWithSourceSetDirBothAsResourceAndGroovy") {
+  apply plugin: "groovy"
+
+  sourceSets.main.resources.srcDir 'src/main/groovy'
+  sourceSets.test.resources.srcDir 'src/test/groovy'
+}
+
 project("moduleWithCustomSourceSet") {
   apply plugin: "java"
 
diff --git a/plugins/gradle/tooling-extension/testData/testGradleSourcesSetsInterpretation/settings.gradle b/plugins/gradle/tooling-extension-impl/testData/testGradleSourcesSetsInterpretation/settings.gradle
similarity index 83%
rename from plugins/gradle/tooling-extension/testData/testGradleSourcesSetsInterpretation/settings.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testGradleSourcesSetsInterpretation/settings.gradle
index 5e84e50..9f87cdc 100644
--- a/plugins/gradle/tooling-extension/testData/testGradleSourcesSetsInterpretation/settings.gradle
+++ b/plugins/gradle/tooling-extension-impl/testData/testGradleSourcesSetsInterpretation/settings.gradle
@@ -2,6 +2,7 @@
 
 include 'defaultJavaModule'
 include 'moduleWithSourceSetDirBothAsResourceAndJava'
+include 'moduleWithSourceSetDirBothAsResourceAndGroovy'
 include 'moduleWithCustomSourceSet'
 include 'withIntegrationTests'
 include 'withIdeaPluginCustomization1'
diff --git a/plugins/gradle/tooling-extension/testData/testModelBuildScriptClasspathBuilder/build.gradle b/plugins/gradle/tooling-extension-impl/testData/testModelBuildScriptClasspathBuilder/build.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testModelBuildScriptClasspathBuilder/build.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testModelBuildScriptClasspathBuilder/build.gradle
diff --git a/plugins/gradle/tooling-extension/testData/testModelBuildScriptClasspathBuilder/settings.gradle b/plugins/gradle/tooling-extension-impl/testData/testModelBuildScriptClasspathBuilder/settings.gradle
similarity index 100%
rename from plugins/gradle/tooling-extension/testData/testModelBuildScriptClasspathBuilder/settings.gradle
rename to plugins/gradle/tooling-extension-impl/testData/testModelBuildScriptClasspathBuilder/settings.gradle
diff --git a/plugins/gradle/tooling-extension/testSources/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService b/plugins/gradle/tooling-extension-impl/testSources/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
similarity index 100%
rename from plugins/gradle/tooling-extension/testSources/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
rename to plugins/gradle/tooling-extension-impl/testSources/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
diff --git a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java
similarity index 61%
rename from plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java
rename to plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java
index 67f58c9..e961117f 100644
--- a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java
+++ b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/AbstractModelBuilderTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -15,14 +15,16 @@
  */
 package org.jetbrains.plugins.gradle.tooling.builder;
 
-import com.intellij.openapi.application.ex.PathManagerEx;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.testFramework.UsefulTestCase;
+import com.intellij.util.ObjectUtils;
 import org.gradle.tooling.BuildActionExecuter;
 import org.gradle.tooling.GradleConnector;
 import org.gradle.tooling.ProjectConnection;
 import org.gradle.tooling.internal.consumer.DefaultGradleConnector;
+import org.gradle.util.GradleVersion;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.gradle.model.ProjectImportAction;
 import org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
@@ -35,6 +37,8 @@
 
 import java.io.File;
 import java.io.IOException;
+import java.net.URI;
+import java.net.URISyntaxException;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.Set;
@@ -43,7 +47,6 @@
 import java.util.regex.Pattern;
 
 import static org.junit.Assert.assertNotNull;
-import static org.junit.Assume.assumeTrue;
 
 /**
  * @author Vladislav.Soroka
@@ -55,7 +58,7 @@
   public static final String GRADLE_v1_9 = "1.9";
   public static final String GRADLE_v1_10 = "1.10";
   public static final String GRADLE_v1_11 = "1.11";
-  public static final String GRADLE_v1_12 = "1.12-20140327133732+0000";
+  public static final String GRADLE_v1_12 = "1.12-rc-1";
 
   public static final Pattern TEST_METHOD_NAME_PATTERN = Pattern.compile("(.*)\\[(\\d*)\\]");
 
@@ -74,7 +77,6 @@
 
   @Parameterized.Parameters
   public static Collection<Object[]> data() {
-    // keep in sync with download steps of http://buildserver.labs.intellij.net/viewType.html?buildTypeId=IDEATrunk_GradleDownloads
     Object[][] data = {
       {AbstractModelBuilderTest.GRADLE_v1_9},
       {AbstractModelBuilderTest.GRADLE_v1_10},
@@ -87,12 +89,6 @@
 
   @Before
   public void setUp() throws Exception {
-    File distHome = null;
-    if (UsefulTestCase.IS_UNDER_TEAMCITY) {
-      distHome = new File(PathManagerEx.findFileUnderCommunityHome("plugins/gradle"), "_dist/gradle-" + gradleVersion);
-      assumeTrue("Missing: " + distHome.getPath(), distHome.isDirectory());
-    }
-
     ensureTempDirCreated();
 
     String methodName = name.getMethodName();
@@ -115,14 +111,26 @@
     );
 
     GradleConnector connector = GradleConnector.newConnector();
-    if (distHome != null) {
-      connector.useInstallation(distHome);
-    }
-    else {
+
+    String releaseRepoUrl = DistributionLocator.getRepoUrl(false);
+    String snapshotRepoUrl = DistributionLocator.getRepoUrl(true);
+
+    if (releaseRepoUrl == null || snapshotRepoUrl == null) {
       connector.useGradleVersion(gradleVersion);
     }
+    else {
+      final URI distributionUri =
+        new DistributionLocator(releaseRepoUrl, snapshotRepoUrl).getDistributionFor(GradleVersion.version(gradleVersion));
+      connector.useDistribution(distributionUri);
+    }
     connector.forProjectDirectory(testDir);
-    ((DefaultGradleConnector)connector).daemonMaxIdleTime(1, TimeUnit.SECONDS);
+    int daemonMaxIdleTime = 1;
+    try {
+      daemonMaxIdleTime = Integer.parseInt(System.getProperty("gradleDaemonMaxIdleTime", "1"));
+    }
+    catch (NumberFormatException ignore) {}
+
+    ((DefaultGradleConnector)connector).daemonMaxIdleTime(daemonMaxIdleTime, TimeUnit.SECONDS);
     ProjectConnection connection = connector.connect();
 
     final ProjectImportAction projectImportAction = new ProjectImportAction(false);
@@ -151,4 +159,46 @@
     FileUtil.delete(ourTempDir);
     FileUtil.ensureExists(ourTempDir);
   }
+
+  private static class DistributionLocator {
+    private static final String RELEASE_REPOSITORY_ENV = "GRADLE_RELEASE_REPOSITORY";
+    private static final String SNAPSHOT_REPOSITORY_ENV = "GRADLE_SNAPSHOT_REPOSITORY";
+    private static final String INTELLIJ_LABS_GRADLE_RELEASE_MIRROR =
+      "http://services.gradle.org-mirror.labs.intellij.net/distributions";
+    private static final String INTELLIJ_LABS_GRADLE_SNAPSHOT_MIRROR =
+      "http://services.gradle.org-mirror.labs.intellij.net/distributions-snapshots";
+
+    @NotNull private final String myReleaseRepoUrl;
+    @NotNull private final String mySnapshotRepoUrl;
+
+    private DistributionLocator(@NotNull String releaseRepoUrl, @NotNull String snapshotRepoUrl) {
+      myReleaseRepoUrl = releaseRepoUrl;
+      mySnapshotRepoUrl = snapshotRepoUrl;
+    }
+
+    @NotNull
+    public URI getDistributionFor(@NotNull GradleVersion version) throws URISyntaxException {
+      return getDistribution(getDistributionRepository(version), version, "gradle", "bin");
+    }
+
+    @NotNull
+    private String getDistributionRepository(@NotNull GradleVersion version) {
+      return version.isSnapshot() ? mySnapshotRepoUrl : myReleaseRepoUrl;
+    }
+
+    private static URI getDistribution(@NotNull String repositoryUrl,
+                                       @NotNull GradleVersion version,
+                                       @NotNull String archiveName,
+                                       @NotNull String archiveClassifier) throws URISyntaxException {
+      return new URI(String.format("%s/%s-%s-%s.zip", repositoryUrl, archiveName, version.getVersion(), archiveClassifier));
+    }
+
+    @Nullable
+    static String getRepoUrl(boolean isSnapshotUrl) {
+      return ObjectUtils.chooseNotNull(
+        System.getenv(isSnapshotUrl ? SNAPSHOT_REPOSITORY_ENV : RELEASE_REPOSITORY_ENV),
+        UsefulTestCase.IS_UNDER_TEAMCITY ? isSnapshotUrl ? INTELLIJ_LABS_GRADLE_SNAPSHOT_MIRROR : INTELLIJ_LABS_GRADLE_RELEASE_MIRROR : null
+      );
+    }
+  }
 }
diff --git a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImplTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImplTest.java
similarity index 92%
rename from plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImplTest.java
rename to plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImplTest.java
index c624b59..6fc4c5a 100644
--- a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImplTest.java
+++ b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelBuildScriptClasspathBuilderImplTest.java
@@ -24,11 +24,11 @@
 import org.jetbrains.plugins.gradle.model.ClasspathEntryModel;
 import org.junit.Test;
 
+import java.io.File;
 import java.util.List;
 import java.util.Set;
 
-import static junit.framework.Assert.*;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
 
 /**
  * @author Vladislav.Soroka
@@ -56,7 +56,7 @@
             assertEquals(1, classpathModel.getClasspath().size());
 
             ClasspathEntryModel classpathEntry = classpathModel.getClasspath().getAt(0);
-            assertEquals("someDep.jar", classpathEntry.getClassesFile().getName());
+            assertEquals("someDep.jar", new File(classpathEntry.getClasses().iterator().next()).getName());
           }
           else if (module.getName().equals("baseModule") ||
                    module.getName().equals("moduleWithInheritedClasspath")) {
@@ -65,7 +65,7 @@
 
             ClasspathEntryModel classpathEntry = classpathModel.getClasspath().getAt(0);
             assertEquals("Wrong build classpath for module: " + module.getName(), "inheritedDep.jar",
-                         classpathEntry.getClassesFile().getName());
+                         new File(classpathEntry.getClasses().iterator().next()).getName());
           }
           else if (module.getName().equals("moduleWithoutAdditionalClasspath") ||
                    module.getName().equals("testModelBuildScriptClasspathBuilder")) {
diff --git a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelDependenciesBuilderImplTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelDependenciesBuilderImplTest.java
similarity index 84%
rename from plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelDependenciesBuilderImplTest.java
rename to plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelDependenciesBuilderImplTest.java
index b6d892b..0f6000e 100644
--- a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelDependenciesBuilderImplTest.java
+++ b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModelDependenciesBuilderImplTest.java
@@ -23,17 +23,14 @@
 import org.gradle.tooling.model.idea.IdeaModuleDependency;
 import org.gradle.tooling.model.idea.IdeaSingleEntryLibraryDependency;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
 import org.junit.Test;
 
+import java.util.Collections;
 import java.util.List;
 import java.util.Locale;
 import java.util.Set;
 
-import static junit.framework.Assert.*;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.*;
 
 /**
  * @author Vladislav.Soroka
@@ -100,7 +97,7 @@
       else if (ideaModule.getName().equals("service")) {
         assertEquals(1, dependencies.size());
         IdeaDependency apiDependency = dependencies.getAt(0);
-        assertEquals(GradleDependencyScope.COMPILE.getIdeaMappingName(), apiDependency.getScope().getScope().toLowerCase(Locale.ENGLISH));
+        assertEquals("compile", apiDependency.getScope().getScope().toLowerCase(Locale.ENGLISH));
         assertTrue(apiDependency instanceof IdeaModuleDependency);
 
         IdeaModuleDependency apiModuleDependency = (IdeaModuleDependency)apiDependency;
@@ -109,18 +106,18 @@
       }
       else if (ideaModule.getName().equals("withIdeaModelCustomisations")) {
 
-        assertTrue(findLocalLibraries(dependencies, GradleDependencyScope.TEST_COMPILE.getIdeaMappingName()).isEmpty());
+        assertTrue(findLocalLibraries(dependencies, "test").isEmpty());
 
         List<IdeaSingleEntryLibraryDependency> libraryDependencies =
-          findLocalLibraries(dependencies, GradleDependencyScope.COMPILE.getIdeaMappingName());
+          findLocalLibraries(dependencies, "compile");
         assertEquals(2, libraryDependencies.size());
 
         IdeaSingleEntryLibraryDependency someDep = libraryDependencies.get(0);
-        assertEquals(GradleDependencyScope.COMPILE.getIdeaMappingName(), someDep.getScope().getScope().toLowerCase(Locale.ENGLISH));
+        assertEquals("compile", someDep.getScope().getScope().toLowerCase(Locale.ENGLISH));
         assertEquals("someDep.jar", someDep.getFile().getName());
 
         IdeaSingleEntryLibraryDependency someTestDep = libraryDependencies.get(1);
-        assertEquals(GradleDependencyScope.COMPILE.getIdeaMappingName(), someTestDep.getScope().getScope().toLowerCase(Locale.ENGLISH));
+        assertEquals("compile", someTestDep.getScope().getScope().toLowerCase(Locale.ENGLISH));
         assertEquals("someTestDep.jar", someTestDep.getFile().getName());
       }
       else if (ideaModule.getName().equals("withIdeRepoFileDependency")) {
@@ -149,9 +146,9 @@
       new Function<IdeaDependency, IdeaSingleEntryLibraryDependency>() {
         @Override
         public IdeaSingleEntryLibraryDependency fun(IdeaDependency dependency) {
-          return dependency instanceof IdeaSingleEntryLibraryDependency && scope.equals(dependency.getScope().getScope().toLowerCase())
-                 ? (IdeaSingleEntryLibraryDependency)dependency
-                 : null;
+          return dependency instanceof IdeaSingleEntryLibraryDependency &&
+                 scope.equals(dependency.getScope().getScope().toLowerCase(Locale.ENGLISH))
+                 ? (IdeaSingleEntryLibraryDependency)dependency : null;
         }
       }
     );
@@ -159,6 +156,6 @@
 
   @Override
   protected Set<Class> getModels() {
-    return ContainerUtil.<Class>set(ProjectDependenciesModel.class);
+    return Collections.emptySet();
   }
 }
diff --git a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImplTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImplTest.java
similarity index 93%
rename from plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImplTest.java
rename to plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImplTest.java
index 21873319..8a1936a 100644
--- a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImplTest.java
+++ b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/ModuleExtendedModelBuilderImplTest.java
@@ -33,10 +33,7 @@
 import java.util.List;
 import java.util.Set;
 
-import static junit.framework.Assert.assertNotNull;
-import static junit.framework.Assert.fail;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.*;
 
 /**
  * @author Vladislav.Soroka
@@ -50,7 +47,7 @@
 
   @Test
   public void testGradleSourcesSetsInterpretation() throws Exception {
-    final int modulesSize = 8;
+    final int modulesSize = 9;
 
     DomainObjectSet<? extends IdeaModule> ideaModules = allModels.getIdeaProject().getModules();
 
@@ -80,6 +77,13 @@
             assertEquals(ContainerUtil.newArrayList("src/test/resources"), testResourceDirectories);
             assertEquals(ContainerUtil.newArrayList(".gradle", "build"), excludeDirectories);
           }
+          else if (module.getName().equals("moduleWithSourceSetDirBothAsResourceAndGroovy")) {
+            assertEquals(ContainerUtil.newArrayList("src/main/groovy", "src/main/java"), sourceDirectories);
+            assertEquals(ContainerUtil.newArrayList("src/main/resources"), resourceDirectories);
+            assertEquals(ContainerUtil.newArrayList("src/test/groovy", "src/test/java"), testDirectories);
+            assertEquals(ContainerUtil.newArrayList("src/test/resources"), testResourceDirectories);
+            assertEquals(ContainerUtil.newArrayList(".gradle", "build"), excludeDirectories);
+          }
           else if (module.getName().equals("moduleWithCustomSourceSet")) {
             assertEquals(ContainerUtil.newArrayList("src/custom/java", "src/main/java"), sourceDirectories);
             assertEquals(ContainerUtil.newArrayList("src/custom/resources", "src/main/resources"), resourceDirectories);
diff --git a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/WebConfigurationBuilderImplTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/WebConfigurationBuilderImplTest.java
similarity index 96%
rename from plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/WebConfigurationBuilderImplTest.java
rename to plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/WebConfigurationBuilderImplTest.java
index 55e6280..69ff905 100644
--- a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/builder/WebConfigurationBuilderImplTest.java
+++ b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/builder/WebConfigurationBuilderImplTest.java
@@ -20,7 +20,7 @@
 import org.gradle.tooling.model.DomainObjectSet;
 import org.gradle.tooling.model.idea.IdeaModule;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.gradle.model.WebConfiguration;
+import org.jetbrains.plugins.gradle.model.web.WebConfiguration;
 import org.junit.Test;
 
 import java.util.List;
diff --git a/plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilderTest.java b/plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilderTest.java
similarity index 100%
rename from plugins/gradle/tooling-extension/testSources/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilderTest.java
rename to plugins/gradle/tooling-extension-impl/testSources/org/jetbrains/plugins/gradle/tooling/internal/ExtraModelBuilderTest.java
diff --git a/plugins/gradle/tooling-extension-v1.11/gradle-tooling-extension-v1.11.iml b/plugins/gradle/tooling-extension-v1.11/gradle-tooling-extension-v1.11.iml
deleted file mode 100644
index 921ff34..0000000
--- a/plugins/gradle/tooling-extension-v1.11/gradle-tooling-extension-v1.11.iml
+++ /dev/null
@@ -1,124 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="module" module-name="annotations" />
-    <orderEntry type="module" module-name="external-system-api" />
-    <orderEntry type="module" module-name="gradle-tooling-extension" />
-    <orderEntry type="module" module-name="testFramework" scope="TEST" />
-    <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
-    <orderEntry type="module" module-name="gradle" scope="TEST" />
-    <orderEntry type="module-library">
-      <library name="Gradle">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-tooling-api-1.11-rc-1.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-core-1.11-rc-1.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-base-services-1.11-rc-1.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-ide-1.11-rc-1.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/buildSrc/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/buildSrc/src/test/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ui/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ui/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ui/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/cli/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/cpp/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/cpp/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ear/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ide/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ide/src/main/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/ivy/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/core/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/core/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/core/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/core/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/osgi/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/osgi/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/antlr/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/jetty/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/maven/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/maven/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/scala/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/scala/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/jacoco/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/native/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/plugins/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/plugins/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/plugins/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/publish/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/wrapper/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/wrapper/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/announce/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/launcher/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/launcher/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/launcher/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/open-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/open-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/core-impl/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/core-impl/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/messaging/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/messaging/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/reporting/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/resources/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/javascript/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/diagnostics/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/diagnostics/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/diagnostics/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/performance/src/configPlugin" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/performance/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/tooling-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/tooling-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/tooling-api/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/code-quality/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/tasks" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/language-jvm/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/base-services/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/base-services/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/language-base/src/main/groovy/org/gradle/language/base/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/language-base/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-comparison/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/internal-testing/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/base-services-groovy/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.11-rc-1-src.zip!/gradle-1.11-rc-1/subprojects/base-services-groovy/src/test/groovy" />
-        </SOURCES>
-      </library>
-    </orderEntry>
-    <orderEntry type="module-library">
-      <library name="GradleGuava">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/../lib/guava-jdk5-14.0.1.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES />
-      </library>
-    </orderEntry>
-    <orderEntry type="library" name="Groovy" level="project" />
-  </component>
-</module>
-
diff --git a/plugins/gradle/tooling-extension-v1.11/lib/gradle-base-services-1.11-rc-1.jar b/plugins/gradle/tooling-extension-v1.11/lib/gradle-base-services-1.11-rc-1.jar
deleted file mode 100644
index 27283d8..0000000
--- a/plugins/gradle/tooling-extension-v1.11/lib/gradle-base-services-1.11-rc-1.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.11/lib/gradle-core-1.11-rc-1.jar b/plugins/gradle/tooling-extension-v1.11/lib/gradle-core-1.11-rc-1.jar
deleted file mode 100644
index 19d2356..0000000
--- a/plugins/gradle/tooling-extension-v1.11/lib/gradle-core-1.11-rc-1.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.11/lib/gradle-ide-1.11-rc-1.jar b/plugins/gradle/tooling-extension-v1.11/lib/gradle-ide-1.11-rc-1.jar
deleted file mode 100644
index 881d355..0000000
--- a/plugins/gradle/tooling-extension-v1.11/lib/gradle-ide-1.11-rc-1.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.11/lib/gradle-tooling-api-1.11-rc-1.jar b/plugins/gradle/tooling-extension-v1.11/lib/gradle-tooling-api-1.11-rc-1.jar
deleted file mode 100644
index 25557d7..0000000
--- a/plugins/gradle/tooling-extension-v1.11/lib/gradle-tooling-api-1.11-rc-1.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.11/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService b/plugins/gradle/tooling-extension-v1.11/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
deleted file mode 100644
index b8b70b01..0000000
--- a/plugins/gradle/tooling-extension-v1.11/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
+++ /dev/null
@@ -1,17 +0,0 @@
-#
-# Copyright 2000-2014 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.
-#
-org.jetbrains.plugins.gradle.tooling.v1_11.builder.ModelDependenciesBuilderImpl
-org.jetbrains.plugins.gradle.tooling.v1_11.builder.ModelBuildScriptClasspathBuilderImpl
diff --git a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/builder/ModelBuildScriptClasspathBuilderImpl.java b/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/builder/ModelBuildScriptClasspathBuilderImpl.java
deleted file mode 100644
index a0d3c3e..0000000
--- a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/builder/ModelBuildScriptClasspathBuilderImpl.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_11.builder;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.plugins.ide.idea.IdeaPlugin;
-import org.gradle.plugins.ide.idea.model.IdeaModel;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.gradle.plugins.ide.internal.resolver.model.IdeLocalFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeRepoFileDependency;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.BuildScriptClasspathModel;
-import org.jetbrains.plugins.gradle.model.ClasspathEntryModel;
-import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions;
-import org.jetbrains.plugins.gradle.tooling.internal.BuildScriptClasspathModelImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.ClasspathEntryModelImpl;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Vladislav.Soroka
- * @since 12/20/13
- */
-@TargetVersions("1.11")
-public class ModelBuildScriptClasspathBuilderImpl implements ModelBuilderService {
-
-  private final Map<String, BuildScriptClasspathModelImpl> cache = new ConcurrentHashMap<String, BuildScriptClasspathModelImpl>();
-
-  @Override
-  public boolean canBuild(String modelName) {
-    return BuildScriptClasspathModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(final String modelName, final Project project) {
-    BuildScriptClasspathModelImpl buildScriptClasspath = cache.get(project.getPath());
-    if (buildScriptClasspath != null) return buildScriptClasspath;
-
-    boolean offline = false;
-    boolean downloadJavadoc = false;
-    boolean downloadSources = true;
-
-    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
-
-    if (ideaPlugin != null) {
-      IdeaModel ideaModel = ideaPlugin.getModel();
-      if (ideaModel != null && ideaModel.getModule() != null) {
-        offline = ideaModel.getModule().isOffline();
-        downloadJavadoc = ideaModel.getModule().isDownloadJavadoc();
-        downloadSources = ideaModel.getModule().isDownloadSources();
-      }
-    }
-
-    buildScriptClasspath = new BuildScriptClasspathModelImpl();
-    Project parent = project.getParent();
-    if (parent != null) {
-      BuildScriptClasspathModelImpl parentBuildScriptClasspath = (BuildScriptClasspathModelImpl)buildAll(modelName, parent);
-      if (parentBuildScriptClasspath != null) {
-        for (ClasspathEntryModel classpathEntryModel : parentBuildScriptClasspath.getClasspath()) {
-          buildScriptClasspath.add(classpathEntryModel);
-        }
-      }
-    }
-
-    final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor();
-
-    final Configuration configuration = project.getBuildscript().getConfigurations().findByName("classpath");
-    Collection<Configuration> plusConfigurations = Collections.singletonList(configuration);
-
-    if (!offline) {
-      // download sources and/or javadoc
-      List<IdeRepoFileDependency> repoFileDependencies = dependenciesExtractor.extractRepoFileDependencies(
-        project.getConfigurations(), plusConfigurations, new ArrayList<Configuration>(), downloadSources, downloadJavadoc);
-
-      for (IdeRepoFileDependency dependency : repoFileDependencies) {
-        if (dependency.getFile() == null) continue;
-
-        buildScriptClasspath.add(
-          new ClasspathEntryModelImpl(dependency.getFile(), dependency.getSourceFile(), dependency.getJavadocFile()));
-      }
-    }
-
-    final Collection<IdeLocalFileDependency> localFileDependencies =
-      dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
-
-    for (IdeLocalFileDependency dependency : localFileDependencies) {
-      if (dependency.getFile() == null) continue;
-      buildScriptClasspath.add(new ClasspathEntryModelImpl(dependency.getFile(), null, null));
-    }
-
-    cache.put(project.getPath(), buildScriptClasspath);
-    return buildScriptClasspath;
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/builder/ModelDependenciesBuilderImpl.java b/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/builder/ModelDependenciesBuilderImpl.java
deleted file mode 100644
index caaae15..0000000
--- a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/builder/ModelDependenciesBuilderImpl.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_11.builder;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.plugins.ide.idea.IdeaPlugin;
-import org.gradle.plugins.ide.idea.model.IdeaModel;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.gradle.plugins.ide.internal.resolver.model.IdeLocalFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeProjectDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeRepoFileDependency;
-import org.gradle.tooling.model.idea.IdeaDependency;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
-import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions;
-import org.jetbrains.plugins.gradle.tooling.internal.*;
-import org.jetbrains.plugins.gradle.tooling.v1_11.internal.InternalDependencyVersionId;
-
-import java.util.*;
-
-import static org.jetbrains.plugins.gradle.tooling.v1_11.internal.ModelDependenciesBuilderImplHelper.*;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/5/13
- */
-@TargetVersions("1.11")
-public class ModelDependenciesBuilderImpl implements ModelBuilderService {
-
-  @Override
-  public boolean canBuild(String modelName) {
-    return ProjectDependenciesModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(final String modelName, final Project project) {
-    final List<IdeaDependency> dependencies = new ArrayList<IdeaDependency>();
-
-    final Map<InternalDependencyVersionId, Scopes> scopesMap = new LinkedHashMap<InternalDependencyVersionId, Scopes>();
-    final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor();
-
-    boolean offline = false;
-    boolean downloadJavadoc = false;
-    boolean downloadSources = true;
-
-    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
-    Map<String, Map<String, Collection<Configuration>>> userScopes = Collections.emptyMap();
-    if (ideaPlugin != null) {
-      IdeaModel ideaModel = ideaPlugin.getModel();
-      if (ideaModel != null && ideaModel.getModule() != null) {
-        offline = ideaModel.getModule().isOffline();
-        downloadJavadoc = ideaModel.getModule().isDownloadJavadoc();
-        downloadSources = ideaModel.getModule().isDownloadSources();
-        userScopes = ideaModel.getModule().getScopes();
-      }
-    }
-
-    for (final Configuration configuration : project.getConfigurations()) {
-      Collection<Configuration> plusConfigurations = new ArrayList<Configuration>();
-      plusConfigurations.add(configuration);
-
-      final Collection<IdeProjectDependency> ideProjectDependencies =
-        dependenciesExtractor.extractProjectDependencies(project, plusConfigurations, new ArrayList<Configuration>());
-
-      for (IdeProjectDependency ideProjectDependency : ideProjectDependencies) {
-        merge(scopesMap, ideProjectDependency, userScopes);
-      }
-
-      if (!offline) {
-        final Collection<IdeRepoFileDependency> ideRepoFileDependencies =
-          dependenciesExtractor.extractRepoFileDependencies(
-            project.getConfigurations(), plusConfigurations, new ArrayList<Configuration>(), downloadSources, downloadJavadoc);
-        for (IdeRepoFileDependency repoFileDependency : ideRepoFileDependencies) {
-          merge(scopesMap, repoFileDependency, userScopes);
-        }
-      }
-
-      final Collection<IdeLocalFileDependency> ideLocalFileDependencies =
-        dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
-      for (IdeLocalFileDependency fileDependency : ideLocalFileDependencies) {
-        merge(scopesMap, fileDependency, userScopes);
-      }
-    }
-
-    for (Map.Entry<InternalDependencyVersionId, Scopes> entry : scopesMap.entrySet()) {
-      InternalDependencyVersionId versionId = entry.getKey();
-      for (GradleDependencyScope scope : entry.getValue().getScopes()) {
-        if (versionId.getIdeDependency() instanceof IdeRepoFileDependency) {
-          IdeRepoFileDependency repoFileDependency =
-            (IdeRepoFileDependency)versionId.getIdeDependency();
-          IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            versionId.getName(),
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          libraryDependency.setFile(repoFileDependency.getFile());
-          libraryDependency.setSource(repoFileDependency.getSourceFile());
-          libraryDependency.setJavadoc(repoFileDependency.getJavadocFile());
-          dependencies.add(libraryDependency);
-        }
-        else if (versionId.getIdeDependency() instanceof IdeProjectDependency) {
-          IdeProjectDependency projectDependency =
-            (IdeProjectDependency)versionId.getIdeDependency();
-
-          String ideaModuleName = findDeDuplicatedModuleName(projectDependency.getProject());
-          if (ideaModuleName == null) {
-            ideaModuleName = versionId.getName();
-          }
-
-          IdeaModuleDependencyImpl moduleDependency = new IdeaModuleDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            ideaModuleName,
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          moduleDependency.setIdeaModule(new StubIdeaModule(ideaModuleName));
-          dependencies.add(moduleDependency);
-        }
-        else if (versionId.getIdeDependency() instanceof IdeLocalFileDependency) {
-          IdeLocalFileDependency fileDependency =
-            (IdeLocalFileDependency)versionId.getIdeDependency();
-          IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            versionId.getName(),
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          libraryDependency.setFile(fileDependency.getFile());
-          attachGradleSdkSources(libraryDependency, fileDependency);
-          dependencies.add(libraryDependency);
-        }
-      }
-    }
-
-    return new ProjectDependenciesModelImpl(project.getPath(), dependencies);
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/internal/InternalDependencyVersionId.java b/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/internal/InternalDependencyVersionId.java
deleted file mode 100644
index 80e6a67..0000000
--- a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/internal/InternalDependencyVersionId.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_11.internal;
-
-import org.gradle.plugins.ide.internal.resolver.model.IdeDependency;
-import org.jetbrains.plugins.gradle.tooling.internal.DependencyVersionId;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class InternalDependencyVersionId extends DependencyVersionId {
-  private final IdeDependency myIdeDependency;
-
-  public InternalDependencyVersionId(IdeDependency dependency,
-                                     String id,
-                                     String name,
-                                     String artifactName,
-                                     String group,
-                                     String version,
-                                     String classifier) {
-    super(id, name, artifactName, group, version, classifier);
-    myIdeDependency = dependency;
-  }
-
-  public IdeDependency getIdeDependency() {
-    return myIdeDependency;
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/internal/ModelDependenciesBuilderImplHelper.java b/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/internal/ModelDependenciesBuilderImplHelper.java
deleted file mode 100644
index f30bef4..0000000
--- a/plugins/gradle/tooling-extension-v1.11/src/org/jetbrains/plugins/gradle/tooling/v1_11/internal/ModelDependenciesBuilderImplHelper.java
+++ /dev/null
@@ -1,229 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_11.internal;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.api.artifacts.ModuleIdentifier;
-import org.gradle.api.artifacts.ModuleVersionIdentifier;
-import org.gradle.plugins.ide.idea.GenerateIdeaModule;
-import org.gradle.plugins.ide.internal.resolver.model.IdeLocalFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeProjectDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeRepoFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.UnresolvedIdeRepoFileDependency;
-import org.gradle.util.GradleVersion;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.tooling.internal.IdeaSingleEntryLibraryDependencyImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.Scopes;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * @author Vladislav.Soroka
- * @since 2/3/14
- */
-public class ModelDependenciesBuilderImplHelper {
-
-  private static final String MODULE_PROPERTY = "ideaModule";
-  private static final String VERSION_PROPERTY = "version";
-  private static final String GROUP_PROPERTY = "group";
-
-
-  public static void attachGradleSdkSources(IdeaSingleEntryLibraryDependencyImpl libraryDependency,
-                                            IdeLocalFileDependency localFileDependency) {
-    final String libName = localFileDependency.getFile().getName();
-    if (localFileDependency.getFile() == null || !libName.startsWith("gradle-")) return;
-
-    File libOrPluginsFile = localFileDependency.getFile().getParentFile();
-    if (libOrPluginsFile != null && ("plugins".equals(libOrPluginsFile.getName()))) {
-      libOrPluginsFile = libOrPluginsFile.getParentFile();
-    }
-
-    if (libOrPluginsFile != null && "lib".equals(libOrPluginsFile.getName()) && libOrPluginsFile.getParentFile() != null) {
-      File srcDir = new File(libOrPluginsFile.getParentFile(), "src");
-      if (GradleVersion.current().compareTo(GradleVersion.version("1.9")) >= 0) {
-        int endIndex = libName.indexOf(GradleVersion.current().getVersion() + ".jar");
-        if (endIndex != -1) {
-          String srcDirChild = libName.substring("gradle-".length(), endIndex - 1);
-          srcDir = new File(srcDir, srcDirChild);
-        }
-      }
-
-      if (srcDir.isDirectory()) {
-        libraryDependency.setSource(srcDir);
-      }
-    }
-  }
-
-  @Nullable
-  public static String findDeDuplicatedModuleName(Project project) {
-    if (project.hasProperty(MODULE_PROPERTY)) {
-      Object ideaModule = project.property(MODULE_PROPERTY);
-      if (ideaModule instanceof GenerateIdeaModule) {
-        GenerateIdeaModule generateIdeaModule = (GenerateIdeaModule)ideaModule;
-        return generateIdeaModule.getModule().getName();
-      }
-    }
-    return null;
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeProjectDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    final Project project = dependency.getProject();
-    final String version = project.hasProperty(VERSION_PROPERTY) ? str(project.property(VERSION_PROPERTY)) : "";
-    final String group = project.hasProperty(GROUP_PROPERTY) ? str(project.property(GROUP_PROPERTY)) : "";
-
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, project.getPath(), project.getName(), null, group, version, null);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  public static String str(Object o) {
-    return String.valueOf(o == null ? "" : o);
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeRepoFileDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    final ModuleVersionIdentifier dependencyId;
-    if (dependency instanceof UnresolvedIdeRepoFileDependency) {
-      UnresolvedIdeRepoFileDependency unresolvedDependency =
-        (UnresolvedIdeRepoFileDependency)dependency;
-      dependencyId = new MyModuleVersionIdentifier(unresolvedDependency.getFile().getName());
-    }
-    else {
-      dependencyId = dependency.getId();
-    }
-
-    String classifier = parseClassifier(dependencyId, dependency.getFile());
-    String dependencyFileName = null;
-    if (dependency.getFile() != null) {
-      dependencyFileName = dependency.getFile().getName();
-    }
-
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, dependencyId.getName(), dependencyId.getName(), dependencyFileName, dependencyId.getGroup(), dependencyId.getVersion(),
-                                      classifier);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  public static String parseClassifier(ModuleVersionIdentifier dependencyId, File dependencyFile) {
-    if (dependencyFile == null) return null;
-    String dependencyFileName = dependencyFile.getName();
-    int i = dependencyFileName.indexOf(dependencyId.getName() + '-' + dependencyId.getVersion() + '-');
-    return i != -1 ? dependencyFileName.substring(i, dependencyFileName.length()) : null;
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeLocalFileDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    String path = dependency.getFile().getPath();
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, path, path, dependency.getFile().getName(), "", "", null);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  /**
-   * Deduce configuration scope based on configuration name using gradle conventions.
-   * IDEA gradle plugin only 'plus' configuration used to support configuration based on a custom configuration (not conventional)
-   *
-   * @param configurationName gradle configuration name
-   * @param userScopes        gradle IDEA plugin scopes map
-   * @return deduced scope
-   */
-  public static GradleDependencyScope deduceScope(String configurationName,
-                                                  Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName);
-    for (Map.Entry<String, Map<String, Collection<Configuration>>> entry : userScopes.entrySet()) {
-      Collection<Configuration> plusConfigurations = entry.getValue().get("plus");
-      if (plusConfigurations == null) continue;
-
-      for (Configuration plus : plusConfigurations) {
-        if (plus.getName().equals(configurationName)) {
-          return GradleDependencyScope.fromIdeaMappingName(entry.getKey().toLowerCase(Locale.ENGLISH));
-        }
-      }
-    }
-
-    return scope;
-  }
-
-  public static class MyModuleVersionIdentifier implements ModuleVersionIdentifier, Serializable {
-    private final String myName;
-
-    public MyModuleVersionIdentifier(String name) {
-
-      myName = name;
-    }
-
-    @Override
-    public String getVersion() {
-      return null;
-    }
-
-    @Override
-    public String getGroup() {
-      return null;
-    }
-
-    @Override
-    public String getName() {
-      return myName;
-    }
-
-    @Override
-    public ModuleIdentifier getModule() {
-      return null;
-    }
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.12/gradle-tooling-extension-v1.12.iml b/plugins/gradle/tooling-extension-v1.12/gradle-tooling-extension-v1.12.iml
deleted file mode 100644
index 946fb96..0000000
--- a/plugins/gradle/tooling-extension-v1.12/gradle-tooling-extension-v1.12.iml
+++ /dev/null
@@ -1,124 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="module" module-name="annotations" />
-    <orderEntry type="module" module-name="external-system-api" />
-    <orderEntry type="module" module-name="gradle-tooling-extension" />
-    <orderEntry type="module" module-name="testFramework" scope="TEST" />
-    <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
-    <orderEntry type="module" module-name="gradle" scope="TEST" />
-    <orderEntry type="module-library">
-      <library name="Gradle">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-tooling-api-1.12-20140327133732+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-core-1.12-20140327133732+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-base-services-1.12-20140327133732+0000.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-ide-1.12-20140327133732+0000.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES>
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/buildSrc/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/buildSrc/src/test/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ui/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ui/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ui/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/cli/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/cpp/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/cpp/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ear/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ide/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ide/src/main/resources" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/ivy/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/core/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/core/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/core/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/core/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/osgi/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/osgi/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/antlr/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/jetty/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/maven/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/maven/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/scala/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/scala/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/jacoco/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/native/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/plugins/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/plugins/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/plugins/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/publish/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/wrapper/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/wrapper/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/announce/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/launcher/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/launcher/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/launcher/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/open-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/open-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/core-impl/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/core-impl/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/messaging/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/messaging/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/reporting/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/resources/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/javascript/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/diagnostics/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/diagnostics/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/diagnostics/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/performance/src/configPlugin" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/performance/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/tooling-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/tooling-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/tooling-api/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/code-quality/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/tasks" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/language-jvm/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/base-services/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/base-services/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/language-base/src/main/groovy/org/gradle/language/base/plugins" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/language-base/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-comparison/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/internal-testing/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/base-services-groovy/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-1.12-20140327133732+0000-src.zip!/gradle-1.12-20140327133732+0000/subprojects/base-services-groovy/src/test/groovy" />
-        </SOURCES>
-      </library>
-    </orderEntry>
-    <orderEntry type="module-library">
-      <library name="GradleGuava">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/../lib/guava-jdk5-14.0.1.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES />
-      </library>
-    </orderEntry>
-    <orderEntry type="library" name="Groovy" level="project" />
-  </component>
-</module>
-
diff --git a/plugins/gradle/tooling-extension-v1.12/lib/gradle-1.12-20140327133732+0000-src.zip b/plugins/gradle/tooling-extension-v1.12/lib/gradle-1.12-20140327133732+0000-src.zip
deleted file mode 100644
index 22e4989..0000000
--- a/plugins/gradle/tooling-extension-v1.12/lib/gradle-1.12-20140327133732+0000-src.zip
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.12/lib/gradle-ide-1.12-20140327133732+0000.jar b/plugins/gradle/tooling-extension-v1.12/lib/gradle-ide-1.12-20140327133732+0000.jar
deleted file mode 100644
index e6cdb13..0000000
--- a/plugins/gradle/tooling-extension-v1.12/lib/gradle-ide-1.12-20140327133732+0000.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/builder/ModelBuildScriptClasspathBuilderImpl.java b/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/builder/ModelBuildScriptClasspathBuilderImpl.java
deleted file mode 100644
index 76bb616..0000000
--- a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/builder/ModelBuildScriptClasspathBuilderImpl.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_12.builder;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.plugins.ide.idea.IdeaPlugin;
-import org.gradle.plugins.ide.idea.model.IdeaModel;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.gradle.plugins.ide.internal.resolver.model.IdeExtendedRepoFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeLocalFileDependency;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.BuildScriptClasspathModel;
-import org.jetbrains.plugins.gradle.model.ClasspathEntryModel;
-import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions;
-import org.jetbrains.plugins.gradle.tooling.internal.BuildScriptClasspathModelImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.ClasspathEntryModelImpl;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Vladislav.Soroka
- * @since 12/20/13
- */
-@TargetVersions("1.12+")
-public class ModelBuildScriptClasspathBuilderImpl implements ModelBuilderService {
-
-  private final Map<String, BuildScriptClasspathModelImpl> cache = new ConcurrentHashMap<String, BuildScriptClasspathModelImpl>();
-
-  @Override
-  public boolean canBuild(String modelName) {
-    return BuildScriptClasspathModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(final String modelName, final Project project) {
-    BuildScriptClasspathModelImpl buildScriptClasspath = cache.get(project.getPath());
-    if (buildScriptClasspath != null) return buildScriptClasspath;
-
-    boolean offline = false;
-    boolean downloadJavadoc = false;
-    boolean downloadSources = true;
-
-    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
-
-    if (ideaPlugin != null) {
-      IdeaModel ideaModel = ideaPlugin.getModel();
-      if (ideaModel != null && ideaModel.getModule() != null) {
-        offline = ideaModel.getModule().isOffline();
-        downloadJavadoc = ideaModel.getModule().isDownloadJavadoc();
-        downloadSources = ideaModel.getModule().isDownloadSources();
-      }
-    }
-
-    buildScriptClasspath = new BuildScriptClasspathModelImpl();
-    Project parent = project.getParent();
-    if (parent != null) {
-      BuildScriptClasspathModelImpl parentBuildScriptClasspath = (BuildScriptClasspathModelImpl)buildAll(modelName, parent);
-      if (parentBuildScriptClasspath != null) {
-        for (ClasspathEntryModel classpathEntryModel : parentBuildScriptClasspath.getClasspath()) {
-          buildScriptClasspath.add(classpathEntryModel);
-        }
-      }
-    }
-
-    final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor();
-
-    final Configuration configuration = project.getBuildscript().getConfigurations().findByName("classpath");
-    Collection<Configuration> plusConfigurations = Collections.singletonList(configuration);
-
-    if (!offline) {
-      // download sources and/or javadoc
-      Collection<IdeExtendedRepoFileDependency> repoFileDependencies = dependenciesExtractor.extractRepoFileDependencies(
-        project.getDependencies(), plusConfigurations, Collections.<Configuration>emptyList(), downloadSources, downloadJavadoc);
-
-      for (IdeExtendedRepoFileDependency dependency : repoFileDependencies) {
-        if (dependency.getFile() == null) continue;
-
-        buildScriptClasspath.add(
-          new ClasspathEntryModelImpl(dependency.getFile(), dependency.getSourceFile(), dependency.getJavadocFile()));
-      }
-    }
-
-    final Collection<IdeLocalFileDependency> localFileDependencies =
-      dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
-
-    for (IdeLocalFileDependency dependency : localFileDependencies) {
-      if (dependency.getFile() == null) continue;
-      buildScriptClasspath.add(new ClasspathEntryModelImpl(dependency.getFile(), null, null));
-    }
-
-    cache.put(project.getPath(), buildScriptClasspath);
-    return buildScriptClasspath;
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/builder/ModelDependenciesBuilderImpl.java b/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/builder/ModelDependenciesBuilderImpl.java
deleted file mode 100644
index 07c65955..0000000
--- a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/builder/ModelDependenciesBuilderImpl.java
+++ /dev/null
@@ -1,158 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_12.builder;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.plugins.ide.idea.IdeaPlugin;
-import org.gradle.plugins.ide.idea.model.IdeaModel;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.gradle.plugins.ide.internal.resolver.model.IdeExtendedRepoFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeLocalFileDependency;
-import org.gradle.plugins.ide.internal.resolver.model.IdeProjectDependency;
-import org.gradle.tooling.model.idea.IdeaDependency;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
-import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions;
-import org.jetbrains.plugins.gradle.tooling.internal.*;
-import org.jetbrains.plugins.gradle.tooling.v1_12.internal.InternalDependencyVersionId;
-
-import java.util.*;
-
-import static org.jetbrains.plugins.gradle.tooling.v1_12.internal.ModelDependenciesBuilderImplHelper.*;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/5/13
- */
-@TargetVersions("1.12+")
-public class ModelDependenciesBuilderImpl implements ModelBuilderService {
-
-  @Override
-  public boolean canBuild(String modelName) {
-    return ProjectDependenciesModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(final String modelName, final Project project) {
-    final List<IdeaDependency> dependencies = new ArrayList<IdeaDependency>();
-
-    final Map<InternalDependencyVersionId, Scopes> scopesMap = new LinkedHashMap<InternalDependencyVersionId, Scopes>();
-    final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor();
-
-    boolean offline = false;
-    boolean downloadJavadoc = false;
-    boolean downloadSources = true;
-
-    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
-    Map<String, Map<String, Collection<Configuration>>> userScopes = Collections.emptyMap();
-    if (ideaPlugin != null) {
-      IdeaModel ideaModel = ideaPlugin.getModel();
-      if (ideaModel != null && ideaModel.getModule() != null) {
-        offline = ideaModel.getModule().isOffline();
-        downloadJavadoc = ideaModel.getModule().isDownloadJavadoc();
-        downloadSources = ideaModel.getModule().isDownloadSources();
-        userScopes = ideaModel.getModule().getScopes();
-      }
-    }
-
-    for (final Configuration configuration : project.getConfigurations()) {
-      Collection<Configuration> plusConfigurations = new ArrayList<Configuration>();
-      plusConfigurations.add(configuration);
-
-      final Collection<IdeProjectDependency> ideProjectDependencies =
-        dependenciesExtractor.extractProjectDependencies(project, plusConfigurations, new ArrayList<Configuration>());
-
-      for (IdeProjectDependency ideProjectDependency : ideProjectDependencies) {
-        merge(scopesMap, ideProjectDependency, userScopes);
-      }
-
-      if (!offline) {
-        final Collection<IdeExtendedRepoFileDependency> ideRepoFileDependencies =
-          dependenciesExtractor.extractRepoFileDependencies(
-            project.getDependencies(), plusConfigurations, new ArrayList<Configuration>(), downloadSources, downloadJavadoc);
-        for (IdeExtendedRepoFileDependency repoFileDependency : ideRepoFileDependencies) {
-          merge(scopesMap, repoFileDependency, userScopes);
-        }
-      }
-
-      final Collection<IdeLocalFileDependency> ideLocalFileDependencies =
-        dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
-      for (IdeLocalFileDependency fileDependency : ideLocalFileDependencies) {
-        merge(scopesMap, fileDependency, userScopes);
-      }
-    }
-
-    for (Map.Entry<InternalDependencyVersionId, Scopes> entry : scopesMap.entrySet()) {
-      InternalDependencyVersionId versionId = entry.getKey();
-      for (GradleDependencyScope scope : entry.getValue().getScopes()) {
-        if (versionId.getIdeDependency() instanceof IdeExtendedRepoFileDependency) {
-          IdeExtendedRepoFileDependency repoFileDependency =
-            (IdeExtendedRepoFileDependency)versionId.getIdeDependency();
-          IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            versionId.getName(),
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          libraryDependency.setFile(repoFileDependency.getFile());
-          libraryDependency.setSource(repoFileDependency.getSourceFile());
-          libraryDependency.setJavadoc(repoFileDependency.getJavadocFile());
-          dependencies.add(libraryDependency);
-        }
-        else if (versionId.getIdeDependency() instanceof IdeProjectDependency) {
-          IdeProjectDependency projectDependency =
-            (IdeProjectDependency)versionId.getIdeDependency();
-
-          String ideaModuleName = findDeDuplicatedModuleName(projectDependency.getProject());
-          if (ideaModuleName == null) {
-            ideaModuleName = versionId.getName();
-          }
-
-          IdeaModuleDependencyImpl moduleDependency = new IdeaModuleDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            ideaModuleName,
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          moduleDependency.setIdeaModule(new StubIdeaModule(ideaModuleName));
-          dependencies.add(moduleDependency);
-        }
-        else if (versionId.getIdeDependency() instanceof IdeLocalFileDependency) {
-          IdeLocalFileDependency fileDependency =
-            (IdeLocalFileDependency)versionId.getIdeDependency();
-          IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            versionId.getName(),
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          libraryDependency.setFile(fileDependency.getFile());
-          attachGradleSdkSources(libraryDependency, fileDependency);
-          dependencies.add(libraryDependency);
-        }
-      }
-    }
-
-    return new ProjectDependenciesModelImpl(project.getPath(), dependencies);
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/internal/InternalDependencyVersionId.java b/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/internal/InternalDependencyVersionId.java
deleted file mode 100644
index 42563d8..0000000
--- a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/internal/InternalDependencyVersionId.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_12.internal;
-
-import org.gradle.plugins.ide.internal.resolver.model.IdeDependency;
-import org.jetbrains.plugins.gradle.tooling.internal.DependencyVersionId;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class InternalDependencyVersionId extends DependencyVersionId {
-  private final IdeDependency myIdeDependency;
-
-  public InternalDependencyVersionId(IdeDependency dependency,
-                                     String id,
-                                     String name,
-                                     String artifactName,
-                                     String group,
-                                     String version,
-                                     String classifier) {
-    super(id, name, artifactName, group, version, classifier);
-    myIdeDependency = dependency;
-  }
-
-  public IdeDependency getIdeDependency() {
-    return myIdeDependency;
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/internal/ModelDependenciesBuilderImplHelper.java b/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/internal/ModelDependenciesBuilderImplHelper.java
deleted file mode 100644
index 847bf71..0000000
--- a/plugins/gradle/tooling-extension-v1.12/src/org/jetbrains/plugins/gradle/tooling/v1_12/internal/ModelDependenciesBuilderImplHelper.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_12.internal;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.api.artifacts.ModuleIdentifier;
-import org.gradle.api.artifacts.ModuleVersionIdentifier;
-import org.gradle.plugins.ide.idea.GenerateIdeaModule;
-import org.gradle.plugins.ide.internal.resolver.model.*;
-import org.gradle.util.GradleVersion;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.tooling.internal.IdeaSingleEntryLibraryDependencyImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.Scopes;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * @author Vladislav.Soroka
- * @since 2/3/14
- */
-public class ModelDependenciesBuilderImplHelper {
-
-  private static final String MODULE_PROPERTY = "ideaModule";
-  private static final String VERSION_PROPERTY = "version";
-  private static final String GROUP_PROPERTY = "group";
-
-
-  public static void attachGradleSdkSources(IdeaSingleEntryLibraryDependencyImpl libraryDependency,
-                                            IdeLocalFileDependency localFileDependency) {
-    final String libName = localFileDependency.getFile().getName();
-    if (localFileDependency.getFile() == null || !libName.startsWith("gradle-")) return;
-
-    File libOrPluginsFile = localFileDependency.getFile().getParentFile();
-    if (libOrPluginsFile != null && ("plugins".equals(libOrPluginsFile.getName()))) {
-      libOrPluginsFile = libOrPluginsFile.getParentFile();
-    }
-
-    if (libOrPluginsFile != null && "lib".equals(libOrPluginsFile.getName()) && libOrPluginsFile.getParentFile() != null) {
-      File srcDir = new File(libOrPluginsFile.getParentFile(), "src");
-      if (GradleVersion.current().compareTo(GradleVersion.version("1.9")) >= 0) {
-        int endIndex = libName.indexOf(GradleVersion.current().getVersion() + ".jar");
-        if (endIndex != -1) {
-          String srcDirChild = libName.substring("gradle-".length(), endIndex - 1);
-          srcDir = new File(srcDir, srcDirChild);
-        }
-      }
-
-      if (srcDir.isDirectory()) {
-        libraryDependency.setSource(srcDir);
-      }
-    }
-  }
-
-  @Nullable
-  public static String findDeDuplicatedModuleName(Project project) {
-    if (project.hasProperty(MODULE_PROPERTY)) {
-      Object ideaModule = project.property(MODULE_PROPERTY);
-      if (ideaModule instanceof GenerateIdeaModule) {
-        GenerateIdeaModule generateIdeaModule = (GenerateIdeaModule)ideaModule;
-        return generateIdeaModule.getModule().getName();
-      }
-    }
-    return null;
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeProjectDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    final Project project = dependency.getProject();
-    final String version = project.hasProperty(VERSION_PROPERTY) ? str(project.property(VERSION_PROPERTY)) : "";
-    final String group = project.hasProperty(GROUP_PROPERTY) ? str(project.property(GROUP_PROPERTY)) : "";
-
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, project.getPath(), project.getName(), null, group, version, null);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  public static String str(Object o) {
-    return String.valueOf(o == null ? "" : o);
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeExtendedRepoFileDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    final ModuleVersionIdentifier dependencyId;
-    if (dependency instanceof UnresolvedIdeRepoFileDependency) {
-      UnresolvedIdeRepoFileDependency unresolvedDependency =
-        (UnresolvedIdeRepoFileDependency)dependency;
-      dependencyId = new MyModuleVersionIdentifier(unresolvedDependency.getFile().getName());
-    }
-    else {
-      dependencyId = dependency.getId();
-    }
-
-    String classifier = parseClassifier(dependencyId, dependency.getFile());
-    String dependencyFileName = null;
-    if (dependency.getFile() != null) {
-      dependencyFileName = dependency.getFile().getName();
-    }
-
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, dependencyId.getName(), dependencyId.getName(), dependencyFileName, dependencyId.getGroup(), dependencyId.getVersion(),
-                                      classifier);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  public static String parseClassifier(ModuleVersionIdentifier dependencyId, File dependencyFile) {
-    if (dependencyFile == null) return null;
-    String dependencyFileName = dependencyFile.getName();
-    int i = dependencyFileName.indexOf(dependencyId.getName() + '-' + dependencyId.getVersion() + '-');
-    return i != -1 ? dependencyFileName.substring(i, dependencyFileName.length()) : null;
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeLocalFileDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    String path = dependency.getFile().getPath();
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, path, path, dependency.getFile().getName(), "", "", null);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  /**
-   * Deduce configuration scope based on configuration name using gradle conventions.
-   * IDEA gradle plugin only 'plus' configuration used to support configuration based on a custom configuration (not conventional)
-   *
-   * @param configurationName gradle configuration name
-   * @param userScopes        gradle IDEA plugin scopes map
-   * @return deduced scope
-   */
-  public static GradleDependencyScope deduceScope(String configurationName,
-                                                  Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName);
-    for (Map.Entry<String, Map<String, Collection<Configuration>>> entry : userScopes.entrySet()) {
-      Collection<Configuration> plusConfigurations = entry.getValue().get("plus");
-      if (plusConfigurations == null) continue;
-
-      for (Configuration plus : plusConfigurations) {
-        if (plus.getName().equals(configurationName)) {
-          return GradleDependencyScope.fromIdeaMappingName(entry.getKey().toLowerCase(Locale.ENGLISH));
-        }
-      }
-    }
-
-    return scope;
-  }
-
-  public static class MyModuleVersionIdentifier implements ModuleVersionIdentifier, Serializable {
-    private final String myName;
-
-    public MyModuleVersionIdentifier(String name) {
-
-      myName = name;
-    }
-
-    @Override
-    public String getVersion() {
-      return null;
-    }
-
-    @Override
-    public String getGroup() {
-      return null;
-    }
-
-    @Override
-    public String getName() {
-      return myName;
-    }
-
-    @Override
-    public ModuleIdentifier getModule() {
-      return null;
-    }
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.9/gradle-tooling-extension-v1.9.iml b/plugins/gradle/tooling-extension-v1.9/gradle-tooling-extension-v1.9.iml
deleted file mode 100644
index ab382ff..0000000
--- a/plugins/gradle/tooling-extension-v1.9/gradle-tooling-extension-v1.9.iml
+++ /dev/null
@@ -1,131 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="module" module-name="annotations" />
-    <orderEntry type="module" module-name="external-system-api" />
-    <orderEntry type="module" module-name="gradle" />
-    <orderEntry type="module" module-name="gradle-tooling-extension" />
-    <orderEntry type="module" module-name="testFramework" scope="TEST" />
-    <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
-    <orderEntry type="module-library">
-      <library name="Gradle">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/../lib/gradle-tooling-api-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-core-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-messaging-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-wrapper-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-base-services-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-native-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-build-init-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-plugins-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-ide-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-scala-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/lib/gradle-reporting-1.9.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES>
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/buildSrc/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/buildSrc/src/test/resources" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ui/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ui/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ui/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/cli/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/cpp/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/cpp/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ear/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ide/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ide/src/main/resources" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ivy/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/osgi/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/osgi/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/antlr/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/jetty/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/maven/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/maven/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/scala/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/scala/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/jacoco/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/native/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/plugins/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/plugins/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/plugins/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/publish/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/wrapper/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/wrapper/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/announce/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/launcher/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/launcher/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/launcher/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/open-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/open-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core-impl/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core-impl/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/messaging/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/messaging/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/reporting/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/resources/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/javascript/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/diagnostics/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/diagnostics/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/diagnostics/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/performance/src/configPlugin" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/performance/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/code-quality/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/tasks" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-jvm/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-base/src/main/groovy/org/gradle/language/base/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-base/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-comparison/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/internal-testing/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services-groovy/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services-groovy/src/test/groovy" />
-        </SOURCES>
-      </library>
-    </orderEntry>
-    <orderEntry type="module-library">
-      <library name="GradleGuava">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/../lib/guava-jdk5-14.0.1.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES />
-      </library>
-    </orderEntry>
-    <orderEntry type="library" name="Groovy" level="project" />
-  </component>
-</module>
-
diff --git a/plugins/gradle/tooling-extension-v1.9/lib/gradle-build-init-1.9.jar b/plugins/gradle/tooling-extension-v1.9/lib/gradle-build-init-1.9.jar
deleted file mode 100644
index 421eb96f..0000000
--- a/plugins/gradle/tooling-extension-v1.9/lib/gradle-build-init-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.9/lib/gradle-ide-1.9.jar b/plugins/gradle/tooling-extension-v1.9/lib/gradle-ide-1.9.jar
deleted file mode 100644
index 7f818b6..0000000
--- a/plugins/gradle/tooling-extension-v1.9/lib/gradle-ide-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.9/lib/gradle-plugins-1.9.jar b/plugins/gradle/tooling-extension-v1.9/lib/gradle-plugins-1.9.jar
deleted file mode 100644
index 17b11d0..0000000
--- a/plugins/gradle/tooling-extension-v1.9/lib/gradle-plugins-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.9/lib/gradle-scala-1.9.jar b/plugins/gradle/tooling-extension-v1.9/lib/gradle-scala-1.9.jar
deleted file mode 100644
index aa6a20a..0000000
--- a/plugins/gradle/tooling-extension-v1.9/lib/gradle-scala-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension-v1.9/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService b/plugins/gradle/tooling-extension-v1.9/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
deleted file mode 100644
index 88d8207..0000000
--- a/plugins/gradle/tooling-extension-v1.9/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
+++ /dev/null
@@ -1,20 +0,0 @@
-#
-# Copyright 2000-2014 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.
-#
-org.jetbrains.plugins.gradle.tooling.v1_9.builder.WarModelBuilderImpl
-org.jetbrains.plugins.gradle.tooling.v1_9.builder.ModelDependenciesBuilderImpl
-org.jetbrains.plugins.gradle.tooling.v1_9.builder.ModuleExtendedModelBuilderImpl
-org.jetbrains.plugins.gradle.tooling.v1_9.builder.ModelBuildScriptClasspathBuilderImpl
-org.jetbrains.plugins.gradle.tooling.v1_9.builder.ScalaModelBuilderImpl
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModelBuildScriptClasspathBuilderImpl.java b/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModelBuildScriptClasspathBuilderImpl.java
deleted file mode 100644
index b4de8ba..0000000
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModelBuildScriptClasspathBuilderImpl.java
+++ /dev/null
@@ -1,109 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_9.builder;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.plugins.ide.idea.IdeaPlugin;
-import org.gradle.plugins.ide.idea.model.IdeaModel;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.BuildScriptClasspathModel;
-import org.jetbrains.plugins.gradle.model.ClasspathEntryModel;
-import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions;
-import org.jetbrains.plugins.gradle.tooling.internal.BuildScriptClasspathModelImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.ClasspathEntryModelImpl;
-
-import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
-
-/**
- * @author Vladislav.Soroka
- * @since 12/20/13
- */
-@TargetVersions("1.8 <=> 1.10")
-public class ModelBuildScriptClasspathBuilderImpl implements ModelBuilderService {
-
-  private final Map<String, BuildScriptClasspathModelImpl> cache = new ConcurrentHashMap<String, BuildScriptClasspathModelImpl>();
-
-  @Override
-  public boolean canBuild(String modelName) {
-    return BuildScriptClasspathModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(final String modelName, final Project project) {
-    BuildScriptClasspathModelImpl buildScriptClasspath = cache.get(project.getPath());
-    if (buildScriptClasspath != null) return buildScriptClasspath;
-
-    boolean offline = false;
-    boolean downloadJavadoc = false;
-    boolean downloadSources = true;
-
-    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
-
-    if (ideaPlugin != null) {
-      IdeaModel ideaModel = ideaPlugin.getModel();
-      if (ideaModel != null && ideaModel.getModule() != null) {
-        offline = ideaModel.getModule().isOffline();
-        downloadJavadoc = ideaModel.getModule().isDownloadJavadoc();
-        downloadSources = ideaModel.getModule().isDownloadSources();
-      }
-    }
-
-    buildScriptClasspath = new BuildScriptClasspathModelImpl();
-    Project parent = project.getParent();
-    if (parent != null) {
-      BuildScriptClasspathModelImpl parentBuildScriptClasspath = (BuildScriptClasspathModelImpl)buildAll(modelName, parent);
-      if (parentBuildScriptClasspath != null) {
-        for (ClasspathEntryModel classpathEntryModel : parentBuildScriptClasspath.getClasspath()) {
-          buildScriptClasspath.add(classpathEntryModel);
-        }
-      }
-    }
-
-    final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor();
-
-    final Configuration configuration = project.getBuildscript().getConfigurations().findByName("classpath");
-    Collection<Configuration> plusConfigurations = Collections.singletonList(configuration);
-
-    if (!offline) {
-      // download sources and/or javadoc
-      List<IdeDependenciesExtractor.IdeRepoFileDependency> repoFileDependencies = dependenciesExtractor.extractRepoFileDependencies(
-        project.getConfigurations(), plusConfigurations, new ArrayList<Configuration>(), downloadSources, downloadJavadoc);
-
-      for (IdeDependenciesExtractor.IdeRepoFileDependency dependency : repoFileDependencies) {
-        if (dependency.getFile() == null) continue;
-
-        buildScriptClasspath.add(
-          new ClasspathEntryModelImpl(dependency.getFile(), dependency.getSourceFile(), dependency.getJavadocFile()));
-      }
-    }
-
-    final List<IdeDependenciesExtractor.IdeLocalFileDependency> localFileDependencies =
-      dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
-
-    for (IdeDependenciesExtractor.IdeLocalFileDependency dependency : localFileDependencies) {
-      if (dependency.getFile() == null) continue;
-      buildScriptClasspath.add(new ClasspathEntryModelImpl(dependency.getFile(), null, null));
-    }
-
-    cache.put(project.getPath(), buildScriptClasspath);
-    return buildScriptClasspath;
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModelDependenciesBuilderImpl.java b/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModelDependenciesBuilderImpl.java
deleted file mode 100644
index 72c3ddb..0000000
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/builder/ModelDependenciesBuilderImpl.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_9.builder;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.plugins.ide.idea.IdeaPlugin;
-import org.gradle.plugins.ide.idea.model.IdeaModel;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.gradle.tooling.model.idea.IdeaDependency;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
-import org.jetbrains.plugins.gradle.tooling.ModelBuilderService;
-import org.jetbrains.plugins.gradle.tooling.annotation.TargetVersions;
-import org.jetbrains.plugins.gradle.tooling.internal.*;
-import org.jetbrains.plugins.gradle.tooling.v1_9.internal.InternalDependencyVersionId;
-import org.jetbrains.plugins.gradle.tooling.v1_9.internal.ModelDependenciesBuilderImplHelper;
-
-import java.util.*;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/5/13
- */
-@TargetVersions("1.8 <=> 1.10")
-public class ModelDependenciesBuilderImpl implements ModelBuilderService {
-  @Override
-  public boolean canBuild(String modelName) {
-    return ProjectDependenciesModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(final String modelName, final Project project) {
-
-    final List<IdeaDependency> dependencies = new ArrayList<IdeaDependency>();
-
-    final Map<InternalDependencyVersionId, Scopes> scopesMap = new LinkedHashMap<InternalDependencyVersionId, Scopes>();
-    final IdeDependenciesExtractor dependenciesExtractor = new IdeDependenciesExtractor();
-
-    boolean offline = false;
-    boolean downloadJavadoc = false;
-    boolean downloadSources = true;
-
-    final IdeaPlugin ideaPlugin = project.getPlugins().getPlugin(IdeaPlugin.class);
-    Map<String, Map<String, Collection<Configuration>>> userScopes = Collections.emptyMap();
-    if (ideaPlugin != null) {
-      IdeaModel ideaModel = ideaPlugin.getModel();
-      if (ideaModel != null && ideaModel.getModule() != null) {
-        offline = ideaModel.getModule().isOffline();
-        downloadJavadoc = ideaModel.getModule().isDownloadJavadoc();
-        downloadSources = ideaModel.getModule().isDownloadSources();
-        userScopes = ideaModel.getModule().getScopes();
-      }
-    }
-
-    for (final Configuration configuration : project.getConfigurations()) {
-      Collection<Configuration> plusConfigurations = new ArrayList<Configuration>();
-      plusConfigurations.add(configuration);
-
-      final List<IdeDependenciesExtractor.IdeProjectDependency> ideProjectDependencies =
-        dependenciesExtractor.extractProjectDependencies(plusConfigurations, new ArrayList<Configuration>());
-
-      for (IdeDependenciesExtractor.IdeProjectDependency ideProjectDependency : ideProjectDependencies) {
-        ModelDependenciesBuilderImplHelper.merge(scopesMap, ideProjectDependency, userScopes);
-      }
-
-      if (!offline) {
-        final Collection<IdeDependenciesExtractor.IdeRepoFileDependency> ideRepoFileDependencies =
-          dependenciesExtractor.extractRepoFileDependencies(
-            project.getConfigurations(), plusConfigurations, new ArrayList<Configuration>(), downloadSources, downloadJavadoc);
-        for (IdeDependenciesExtractor.IdeRepoFileDependency repoFileDependency : ideRepoFileDependencies) {
-          ModelDependenciesBuilderImplHelper.merge(scopesMap, repoFileDependency, userScopes);
-        }
-      }
-
-      final List<IdeDependenciesExtractor.IdeLocalFileDependency> ideLocalFileDependencies =
-        dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
-      for (IdeDependenciesExtractor.IdeLocalFileDependency fileDependency : ideLocalFileDependencies) {
-        ModelDependenciesBuilderImplHelper.merge(scopesMap, fileDependency, userScopes);
-      }
-    }
-
-    for (Map.Entry<InternalDependencyVersionId, Scopes> entry : scopesMap.entrySet()) {
-      InternalDependencyVersionId versionId = entry.getKey();
-      for (GradleDependencyScope scope : entry.getValue().getScopes()) {
-        if (versionId.getIdeDependency() instanceof IdeDependenciesExtractor.IdeRepoFileDependency) {
-          IdeDependenciesExtractor.IdeRepoFileDependency repoFileDependency =
-            (IdeDependenciesExtractor.IdeRepoFileDependency)versionId.getIdeDependency();
-          IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            versionId.getName(),
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          libraryDependency.setFile(repoFileDependency.getFile());
-          libraryDependency.setSource(repoFileDependency.getSourceFile());
-          libraryDependency.setJavadoc(repoFileDependency.getJavadocFile());
-          dependencies.add(libraryDependency);
-        }
-        else if (versionId.getIdeDependency() instanceof IdeDependenciesExtractor.IdeProjectDependency) {
-          IdeDependenciesExtractor.IdeProjectDependency projectDependency =
-            (IdeDependenciesExtractor.IdeProjectDependency)versionId.getIdeDependency();
-
-          String ideaModuleName = ModelDependenciesBuilderImplHelper.findDeDuplicatedModuleName(projectDependency.getProject());
-          if (ideaModuleName == null) {
-            ideaModuleName = versionId.getName();
-          }
-
-          IdeaModuleDependencyImpl moduleDependency = new IdeaModuleDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            ideaModuleName,
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          moduleDependency.setIdeaModule(new StubIdeaModule(ideaModuleName));
-          dependencies.add(moduleDependency);
-        }
-        else if (versionId.getIdeDependency() instanceof IdeDependenciesExtractor.IdeLocalFileDependency) {
-          IdeDependenciesExtractor.IdeLocalFileDependency fileDependency =
-            (IdeDependenciesExtractor.IdeLocalFileDependency)versionId.getIdeDependency();
-          IdeaSingleEntryLibraryDependencyImpl libraryDependency = new IdeaSingleEntryLibraryDependencyImpl(
-            new IdeaDependencyScopeImpl(scope),
-            versionId.getName(),
-            versionId.getGroup(),
-            versionId.getVersion(),
-            versionId.getClassifier()
-          );
-          libraryDependency.setFile(fileDependency.getFile());
-          ModelDependenciesBuilderImplHelper.attachGradleSdkSources(libraryDependency, fileDependency);
-          dependencies.add(libraryDependency);
-        }
-      }
-    }
-
-    return new ProjectDependenciesModelImpl(project.getPath(), dependencies);
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/internal/InternalDependencyVersionId.java b/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/internal/InternalDependencyVersionId.java
deleted file mode 100644
index 3ee4d66..0000000
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/internal/InternalDependencyVersionId.java
+++ /dev/null
@@ -1,42 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_9.internal;
-
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.jetbrains.plugins.gradle.tooling.internal.DependencyVersionId;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class InternalDependencyVersionId extends DependencyVersionId {
-  private final IdeDependenciesExtractor.IdeDependency myIdeDependency;
-
-  public InternalDependencyVersionId(IdeDependenciesExtractor.IdeDependency dependency,
-                                     String id,
-                                     String name,
-                                     String artifactName,
-                                     String group,
-                                     String version,
-                                     String classifier) {
-    super(id, name, artifactName, group, version, classifier);
-    myIdeDependency = dependency;
-  }
-
-  public IdeDependenciesExtractor.IdeDependency getIdeDependency() {
-    return myIdeDependency;
-  }
-}
diff --git a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/internal/ModelDependenciesBuilderImplHelper.java b/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/internal/ModelDependenciesBuilderImplHelper.java
deleted file mode 100644
index d49b35a..0000000
--- a/plugins/gradle/tooling-extension-v1.9/src/org/jetbrains/plugins/gradle/tooling/v1_9/internal/ModelDependenciesBuilderImplHelper.java
+++ /dev/null
@@ -1,226 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.v1_9.internal;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.Configuration;
-import org.gradle.api.artifacts.ModuleIdentifier;
-import org.gradle.api.artifacts.ModuleVersionIdentifier;
-import org.gradle.plugins.ide.idea.GenerateIdeaModule;
-import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
-import org.gradle.util.GradleVersion;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-import org.jetbrains.plugins.gradle.tooling.internal.IdeaSingleEntryLibraryDependencyImpl;
-import org.jetbrains.plugins.gradle.tooling.internal.Scopes;
-
-import java.io.File;
-import java.io.Serializable;
-import java.util.Collection;
-import java.util.Locale;
-import java.util.Map;
-
-/**
- * @author Vladislav.Soroka
- * @since 2/3/14
- */
-public class ModelDependenciesBuilderImplHelper {
-
-  private static final String MODULE_PROPERTY = "ideaModule";
-  private static final String VERSION_PROPERTY = "version";
-  private static final String GROUP_PROPERTY = "group";
-
-
-  public static void attachGradleSdkSources(IdeaSingleEntryLibraryDependencyImpl libraryDependency,
-                                            IdeDependenciesExtractor.IdeLocalFileDependency localFileDependency) {
-    final String libName = localFileDependency.getFile().getName();
-    if (localFileDependency.getFile() == null || !libName.startsWith("gradle-")) return;
-
-    File libOrPluginsFile = localFileDependency.getFile().getParentFile();
-    if (libOrPluginsFile != null && ("plugins".equals(libOrPluginsFile.getName()))) {
-      libOrPluginsFile = libOrPluginsFile.getParentFile();
-    }
-
-    if (libOrPluginsFile != null && "lib".equals(libOrPluginsFile.getName()) && libOrPluginsFile.getParentFile() != null) {
-      File srcDir = new File(libOrPluginsFile.getParentFile(), "src");
-      if (GradleVersion.current().compareTo(GradleVersion.version("1.9")) >= 0) {
-        int endIndex = libName.indexOf(GradleVersion.current().getVersion() + ".jar");
-        if (endIndex != -1) {
-          String srcDirChild = libName.substring("gradle-".length(), endIndex - 1);
-          srcDir = new File(srcDir, srcDirChild);
-        }
-      }
-
-      if (srcDir.isDirectory()) {
-        libraryDependency.setSource(srcDir);
-      }
-    }
-  }
-
-  @Nullable
-  public static String findDeDuplicatedModuleName(Project project) {
-    if (project.hasProperty(MODULE_PROPERTY)) {
-      Object ideaModule = project.property(MODULE_PROPERTY);
-      if (ideaModule instanceof GenerateIdeaModule) {
-        GenerateIdeaModule generateIdeaModule = (GenerateIdeaModule)ideaModule;
-        return generateIdeaModule.getModule().getName();
-      }
-    }
-    return null;
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeDependenciesExtractor.IdeProjectDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    final Project project = dependency.getProject();
-    final String version = project.hasProperty(VERSION_PROPERTY) ? str(project.property(VERSION_PROPERTY)) : "";
-    final String group = project.hasProperty(GROUP_PROPERTY) ? str(project.property(GROUP_PROPERTY)) : "";
-
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, project.getPath(), project.getName(), null, group, version, null);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  public static String str(Object o) {
-    return String.valueOf(o == null ? "" : o);
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeDependenciesExtractor.IdeRepoFileDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    final ModuleVersionIdentifier dependencyId;
-    if (dependency instanceof IdeDependenciesExtractor.UnresolvedIdeRepoFileDependency) {
-      IdeDependenciesExtractor.UnresolvedIdeRepoFileDependency unresolvedDependency =
-        (IdeDependenciesExtractor.UnresolvedIdeRepoFileDependency)dependency;
-      dependencyId = new MyModuleVersionIdentifier(unresolvedDependency.getFile().getName());
-    }
-    else {
-      dependencyId = dependency.getId();
-    }
-
-    String classifier = parseClassifier(dependencyId, dependency.getFile());
-    String dependencyFileName = null;
-    if (dependency.getFile() != null) {
-      dependencyFileName = dependency.getFile().getName();
-    }
-
-    InternalDependencyVersionId versionId = new InternalDependencyVersionId(
-      dependency, dependencyId.getName(), dependencyId.getName(), dependencyFileName,
-      dependencyId.getGroup(), dependencyId.getVersion(), classifier);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  public static String parseClassifier(ModuleVersionIdentifier dependencyId, File dependencyFile) {
-    if (dependencyFile == null) return null;
-    String dependencyFileName = dependencyFile.getName();
-    int i = dependencyFileName.indexOf(dependencyId.getName() + '-' + dependencyId.getVersion() + '-');
-    return i != -1 ? dependencyFileName.substring(i, dependencyFileName.length()) : null;
-  }
-
-  public static void merge(Map<InternalDependencyVersionId, Scopes> map,
-                           IdeDependenciesExtractor.IdeLocalFileDependency dependency,
-                           Map<String, Map<String, Collection<Configuration>>> userScopes) {
-
-    final String configurationName = dependency.getDeclaredConfiguration().getName();
-    final GradleDependencyScope scope = deduceScope(configurationName, userScopes);
-    if (scope == null) return;
-
-    String path = dependency.getFile().getPath();
-    InternalDependencyVersionId versionId =
-      new InternalDependencyVersionId(dependency, path, path, dependency.getFile().getName(), "", "", null);
-    Scopes scopes = map.get(versionId);
-    if (scopes == null) {
-      map.put(versionId, new Scopes(scope));
-    }
-    else {
-      scopes.add(scope);
-    }
-  }
-
-  /**
-   * Deduce configuration scope based on configuration name using gradle conventions.
-   * IDEA gradle plugin only 'plus' configuration used to support configuration based on a custom configuration (not conventional)
-   *
-   * @param configurationName gradle configuration name
-   * @param userScopes        gradle IDEA plugin scopes map
-   * @return deduced scope
-   */
-  public static GradleDependencyScope deduceScope(String configurationName,
-                                                  Map<String, Map<String, Collection<Configuration>>> userScopes) {
-    GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName);
-    for (Map.Entry<String, Map<String, Collection<Configuration>>> entry : userScopes.entrySet()) {
-      Collection<Configuration> plusConfigurations = entry.getValue().get("plus");
-      if (plusConfigurations == null) continue;
-
-      for (Configuration plus : plusConfigurations) {
-        if (plus.getName().equals(configurationName)) {
-          return GradleDependencyScope.fromIdeaMappingName(entry.getKey().toLowerCase(Locale.ENGLISH));
-        }
-      }
-    }
-
-    return scope;
-  }
-
-  public static class MyModuleVersionIdentifier implements ModuleVersionIdentifier, Serializable {
-    private final String myName;
-
-    public MyModuleVersionIdentifier(String name) {
-
-      myName = name;
-    }
-
-    @Override
-    public String getVersion() {
-      return null;
-    }
-
-    @Override
-    public String getGroup() {
-      return null;
-    }
-
-    @Override
-    public String getName() {
-      return myName;
-    }
-
-    @Override
-    public ModuleIdentifier getModule() {
-      return null;
-    }
-  }
-}
diff --git a/plugins/gradle/tooling-extension/gradle-tooling-extension.iml b/plugins/gradle/tooling-extension/gradle-tooling-extension.iml
deleted file mode 100644
index d6300f1..0000000
--- a/plugins/gradle/tooling-extension/gradle-tooling-extension.iml
+++ /dev/null
@@ -1,130 +0,0 @@
-<?xml version="1.0" encoding="UTF-8"?>
-<module type="JAVA_MODULE" version="4">
-  <component name="NewModuleRootManager" inherit-compiler-output="true">
-    <exclude-output />
-    <content url="file://$MODULE_DIR$">
-      <sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
-      <sourceFolder url="file://$MODULE_DIR$/testSources" isTestSource="true" />
-      <sourceFolder url="file://$MODULE_DIR$/testData" type="java-test-resource" />
-    </content>
-    <orderEntry type="inheritedJdk" />
-    <orderEntry type="sourceFolder" forTests="false" />
-    <orderEntry type="module" module-name="external-system-api" />
-    <orderEntry type="module" module-name="annotations" />
-    <orderEntry type="module" module-name="testFramework" scope="TEST" />
-    <orderEntry type="module" module-name="testFramework-java" scope="TEST" />
-    <orderEntry type="module-library">
-      <library name="Gradle">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/../lib/gradle-tooling-api-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-core-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-messaging-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-wrapper-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-base-services-1.9.jar!/" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-native-1.9.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES>
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/buildSrc/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/buildSrc/src/test/resources" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ui/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ui/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ui/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/cli/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/cpp/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/cpp/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ear/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ide/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ide/src/main/resources" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/tasks" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ivy/src/main/java/org/gradle/api/publish/ivy/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/ivy/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/osgi/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/osgi/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/antlr/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/jetty/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/maven/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/maven/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/scala/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/scala/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/jacoco/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/native/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/plugins/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/plugins/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/plugins/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/publish/src/main/groovy/org/gradle/api/publish/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/publish/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/wrapper/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/wrapper/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/announce/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/launcher/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/launcher/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/launcher/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/open-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/open-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core-impl/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/core-impl/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/messaging/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/messaging/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/reporting/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/resources/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/javascript/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/testjar/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/multiModule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/singleModule/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/enforcerplugin/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-init/src/integTest/resources/org/gradle/buildinit/plugins/MavenConversionIntegrationTest/flatmultimodule/webinar-impl/src/test/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/diagnostics/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/diagnostics/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/diagnostics/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/performance/src/configPlugin" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/performance/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/integTest/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/tooling-api/src/testFixtures/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/code-quality/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/tasks" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-jvm/src/main/groovy/org/gradle/language/jvm/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-jvm/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services/src/test/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-base/src/main/groovy/org/gradle/language/base/plugins" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/language-base/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-comparison/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/source/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/build-comparison/src/integTest/resources/org/gradle/api/plugins/buildcomparison/gradle/BuildComparisonIntegrationSpec/compareArchives/target/src/main/java" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/internal-testing/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services-groovy/src/main/groovy" />
-          <root url="jar://$MODULE_DIR$/../lib/gradle-1.9-src.zip!/gradle-1.9/subprojects/base-services-groovy/src/test/groovy" />
-        </SOURCES>
-      </library>
-    </orderEntry>
-    <orderEntry type="module-library" scope="PROVIDED">
-      <library name="GradleGuava">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/../lib/guava-jdk5-14.0.1.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES />
-      </library>
-    </orderEntry>
-    <orderEntry type="library" scope="PROVIDED" name="Groovy" level="project" />
-    <orderEntry type="module" module-name="gradle" scope="TEST" />
-    <orderEntry type="module" module-name="gradle-tooling-extension-v1.9" scope="RUNTIME" />
-    <orderEntry type="module" module-name="gradle-tooling-extension-v1.11" scope="RUNTIME" />
-    <orderEntry type="module" module-name="gradle-tooling-extension-v1.12" scope="RUNTIME" />
-  </component>
-</module>
-
diff --git a/plugins/gradle/tooling-extension/lib/gradle-build-init-1.9.jar b/plugins/gradle/tooling-extension/lib/gradle-build-init-1.9.jar
deleted file mode 100644
index 421eb96f..0000000
--- a/plugins/gradle/tooling-extension/lib/gradle-build-init-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension/lib/gradle-ide-1.9.jar b/plugins/gradle/tooling-extension/lib/gradle-ide-1.9.jar
deleted file mode 100644
index 7f818b6..0000000
--- a/plugins/gradle/tooling-extension/lib/gradle-ide-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension/lib/gradle-plugins-1.9.jar b/plugins/gradle/tooling-extension/lib/gradle-plugins-1.9.jar
deleted file mode 100644
index 17b11d0..0000000
--- a/plugins/gradle/tooling-extension/lib/gradle-plugins-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension/lib/gradle-scala-1.9.jar b/plugins/gradle/tooling-extension/lib/gradle-scala-1.9.jar
deleted file mode 100644
index aa6a20a..0000000
--- a/plugins/gradle/tooling-extension/lib/gradle-scala-1.9.jar
+++ /dev/null
Binary files differ
diff --git a/plugins/gradle/tooling-extension/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService b/plugins/gradle/tooling-extension/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
deleted file mode 100644
index 8a3203c..0000000
--- a/plugins/gradle/tooling-extension/src/META-INF/services/org.jetbrains.plugins.gradle.tooling.ModelBuilderService
+++ /dev/null
@@ -1,15 +0,0 @@
-#
-# Copyright 2000-2014 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.
-#
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java
deleted file mode 100644
index b1a7c1c..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java
+++ /dev/null
@@ -1,115 +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.model;
-
-import org.jetbrains.annotations.Nullable;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public enum GradleDependencyScope {
-  // Java Plugin Scopes
-  /**
-   * Compile time dependencies
-   */
-  COMPILE("compile", "compile", true, true, true, true),
-  /**
-   * Runtime dependencies
-   */
-  RUNTIME("runtime", "runtime", false, true, false, true),
-  /**
-   * Additional dependencies for compiling tests.
-   */
-  TEST_COMPILE("testCompile", "test", false, false, true, true),
-  /**
-   * Additional dependencies for running tests only.
-   */
-  TEST_RUNTIME("testRuntime", "test", false, false, false, true),
-
-
-  // War Plugin Scopes
-  /**
-   * the same scope as the compile scope dependencies, except that they are not added to the WAR archive.
-   */
-  PROVIDED_COMPILE("providedCompile", "provided", true, true, true, true),
-  /**
-   * the same scope as the runtime scope dependencies, except that they are not added to the WAR archive.
-   */
-  PROVIDED_RUNTIME("providedRuntime", "provided", false, true, false, true);
-
-  private final String myGradleName;
-  private final String myIdeaMappingName;
-  private final boolean myForProductionCompile;
-  private final boolean myForProductionRuntime;
-  private final boolean myForTestCompile;
-  private final boolean myForTestRuntime;
-
-  GradleDependencyScope(String gradleName,
-                        String ideaMappingName,
-                        boolean forProductionCompile,
-                        boolean forProductionRuntime,
-                        boolean forTestCompile,
-                        boolean forTestRuntime) {
-    myGradleName = gradleName;
-    myIdeaMappingName = ideaMappingName;
-    myForProductionCompile = forProductionCompile;
-    myForProductionRuntime = forProductionRuntime;
-    myForTestCompile = forTestCompile;
-    myForTestRuntime = forTestRuntime;
-  }
-
-  public boolean isForProductionCompile() {
-    return myForProductionCompile;
-  }
-
-  public boolean isForProductionRuntime() {
-    return myForProductionRuntime;
-  }
-
-  public boolean isForTestCompile() {
-    return myForTestCompile;
-  }
-
-  public boolean isForTestRuntime() {
-    return myForTestRuntime;
-  }
-
-  @Nullable
-  public static GradleDependencyScope fromName(final String scopeName) {
-    for (GradleDependencyScope scope : values()) {
-      if (scope.myGradleName.equals(scopeName)) return scope;
-    }
-    return null;
-  }
-
-  @Nullable
-  public static GradleDependencyScope fromIdeaMappingName(final String ideaMappingName) {
-    for (GradleDependencyScope scope : values()) {
-      if (scope.myIdeaMappingName.equals(ideaMappingName)) return scope;
-    }
-    return null;
-  }
-
-  public String getIdeaMappingName() {
-    return myIdeaMappingName;
-  }
-
-  @Override
-  public String toString() {
-    return myGradleName;
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java
deleted file mode 100644
index 45828b4..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java
+++ /dev/null
@@ -1,32 +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.model;
-
-import org.gradle.tooling.model.idea.IdeaDependency;
-
-import java.io.Serializable;
-import java.util.List;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/5/13
- */
-public interface ProjectDependenciesModel extends Serializable {
-
-  String getProjectName();
-
-  List<IdeaDependency> getDependencies();
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/AbstractGradleDependency.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/AbstractGradleDependency.java
deleted file mode 100644
index 16cef89..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/AbstractGradleDependency.java
+++ /dev/null
@@ -1,105 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-import org.gradle.tooling.model.idea.IdeaDependencyScope;
-
-import java.io.Serializable;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/8/13
- */
-public abstract class AbstractGradleDependency implements Serializable {
-  private final IdeaDependencyScope myScope;
-  private final String myDependencyName;
-  private final String myDependencyGroup;
-  private final String myDependencyVersion;
-  private final String myClassifier;
-
-  public AbstractGradleDependency(IdeaDependencyScope scope, String dependencyName,
-                                  String dependencyGroup, String dependencyVersion, String classifier) {
-    myScope = scope;
-    myDependencyName = dependencyName;
-    myDependencyGroup = dependencyGroup;
-    myDependencyVersion = dependencyVersion;
-    myClassifier = classifier;
-  }
-
-  public IdeaDependencyScope getScope() {
-    return myScope;
-  }
-
-  public boolean getExported() {
-    return "compile".equals(myScope.getScope()) || "runtime".equals(myScope.getScope());
-  }
-
-  public String getDependencyName() {
-    return myDependencyName;
-  }
-
-  public String getDependencyGroup() {
-    return myDependencyGroup;
-  }
-
-  public String getDependencyVersion() {
-    return myDependencyVersion;
-  }
-
-  public String getClassifier() {
-    return myClassifier;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (!(o instanceof AbstractGradleDependency)) return false;
-
-    AbstractGradleDependency that = (AbstractGradleDependency)o;
-
-    if (myDependencyGroup != null ? !myDependencyGroup.equals(that.myDependencyGroup) : that.myDependencyGroup != null) return false;
-    if (myDependencyName != null ? !myDependencyName.equals(that.myDependencyName) : that.myDependencyName != null) return false;
-    if (myDependencyVersion != null ? !myDependencyVersion.equals(that.myDependencyVersion) : that.myDependencyVersion != null) {
-      return false;
-    }
-    if (myScope != null ? !myScope.equals(that.myScope) : that.myScope != null) return false;
-    if (myClassifier != null ? !myClassifier.equals(that.myClassifier) : that.myClassifier != null) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    int result = myScope != null ? myScope.hashCode() : 0;
-    result = 31 * result + (myDependencyName != null ? myDependencyName.hashCode() : 0);
-    result = 31 * result + (myDependencyGroup != null ? myDependencyGroup.hashCode() : 0);
-    result = 31 * result + (myDependencyVersion != null ? myDependencyVersion.hashCode() : 0);
-    result = 31 * result + (myClassifier != null ? myClassifier.hashCode() : 0);
-    return result;
-  }
-
-  @Override
-  public String toString() {
-    return "GradleDependency{" +
-           "myScope=" + myScope +
-           ", dependencyName='" + myDependencyName + '\'' +
-           ", dependencyGroup='" + myDependencyGroup + '\'' +
-           ", dependencyVersion='" + myDependencyVersion + '\'' +
-           ", classifier='" + myClassifier + '\'' +
-           ", exported=" + getExported() +
-           '}';
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/DependencyVersionId.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/DependencyVersionId.java
deleted file mode 100644
index 160cc64..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/DependencyVersionId.java
+++ /dev/null
@@ -1,107 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class DependencyVersionId {
-  private final String myId;
-  private final String myName;
-  private final String myArtifactName;
-  private final String myGroup;
-  private final String myVersion;
-  private final String myClassifier;
-
-  public DependencyVersionId(String id,
-                             String name,
-                             String artifactName,
-                             String group,
-                             String version,
-                             String classifier) {
-    myId = id;
-    myName = name;
-    myArtifactName = artifactName;
-    myGroup = group;
-    myVersion = version;
-    myClassifier = classifier;
-  }
-
-  public String getId() {
-    return myId;
-  }
-
-  public String getName() {
-    return myName;
-  }
-
-  public String getArtifactName() {
-    return myArtifactName;
-  }
-
-  public String getGroup() {
-    return myGroup;
-  }
-
-  public String getVersion() {
-    return myVersion;
-  }
-
-  public String getClassifier() {
-    return myClassifier;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (!(o instanceof DependencyVersionId)) return false;
-
-    DependencyVersionId id = (DependencyVersionId)o;
-
-    if (myId != null ? !myId.equals(id.myId) : id.myId != null) return false;
-    if (myGroup != null ? !myGroup.equals(id.myGroup) : id.myGroup != null) return false;
-    if (myName != null ? !myName.equals(id.myName) : id.myName != null) return false;
-    if (myArtifactName != null ? !myArtifactName.equals(id.myArtifactName) : id.myArtifactName != null) return false;
-    if (myVersion != null ? !myVersion.equals(id.myVersion) : id.myVersion != null) return false;
-    if (myClassifier != null ? !myClassifier.equals(id.myClassifier) : id.myClassifier != null) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    int result = myId != null ? myId.hashCode() : 0;
-    result = 31 * result + (myName != null ? myName.hashCode() : 0);
-    result = 31 * result + (myArtifactName != null ? myArtifactName.hashCode() : 0);
-    result = 31 * result + (myGroup != null ? myGroup.hashCode() : 0);
-    result = 31 * result + (myVersion != null ? myVersion.hashCode() : 0);
-    result = 31 * result + (myClassifier != null ? myClassifier.hashCode() : 0);
-    return result;
-  }
-
-  @Override
-  public String toString() {
-    return "DependencyVersionId{" +
-           "id='" + myId + '\'' +
-           ", name='" + myName + '\'' +
-           ", artifactName='" + myArtifactName + '\'' +
-           ", group='" + myGroup + '\'' +
-           ", version='" + myVersion + '\'' +
-           ", classifier='" + myClassifier + '\'' +
-           '}';
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaDependencyScopeImpl.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaDependencyScopeImpl.java
deleted file mode 100644
index 6e10e56..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaDependencyScopeImpl.java
+++ /dev/null
@@ -1,61 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-import org.gradle.tooling.model.idea.IdeaDependencyScope;
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-
-import java.io.Serializable;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class IdeaDependencyScopeImpl implements IdeaDependencyScope, Serializable {
-
-  private final GradleDependencyScope myDependencyScope;
-
-  public IdeaDependencyScopeImpl(GradleDependencyScope scope) {
-    myDependencyScope = scope;
-  }
-
-  @Override
-  public String getScope() {
-    return myDependencyScope.getIdeaMappingName();
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (!(o instanceof IdeaDependencyScopeImpl)) return false;
-
-    IdeaDependencyScopeImpl scope = (IdeaDependencyScopeImpl)o;
-
-    if (myDependencyScope != scope.myDependencyScope) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    return myDependencyScope != null ? myDependencyScope.hashCode() : 0;
-  }
-
-  @Override
-  public String toString() {
-    return "IdeaDependencyScope{" + myDependencyScope + '}';
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaModuleDependencyImpl.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaModuleDependencyImpl.java
deleted file mode 100644
index 5b5d0df..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaModuleDependencyImpl.java
+++ /dev/null
@@ -1,48 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-import org.gradle.tooling.model.idea.IdeaDependencyScope;
-import org.gradle.tooling.model.idea.IdeaModule;
-import org.gradle.tooling.model.idea.IdeaModuleDependency;
-
-import java.io.Serializable;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class IdeaModuleDependencyImpl extends AbstractGradleDependency
-  implements IdeaModuleDependency, Serializable {
-  private IdeaModule myIdeaModule;
-
-  public IdeaModuleDependencyImpl(IdeaDependencyScope myScope,
-                                  String dependencyName,
-                                  String dependencyGroup,
-                                  String dependencyVersion,
-                                  String classifier) {
-    super(myScope, dependencyName, dependencyGroup, dependencyVersion, classifier);
-  }
-
-  @Override
-  public IdeaModule getDependencyModule() {
-    return myIdeaModule;
-  }
-
-  public void setIdeaModule(IdeaModule ideaModule) {
-    myIdeaModule = ideaModule;
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSingleEntryLibraryDependencyImpl.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSingleEntryLibraryDependencyImpl.java
deleted file mode 100644
index 13025c9..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/IdeaSingleEntryLibraryDependencyImpl.java
+++ /dev/null
@@ -1,75 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-import org.gradle.tooling.model.GradleModuleVersion;
-import org.gradle.tooling.model.idea.IdeaDependencyScope;
-import org.gradle.tooling.model.idea.IdeaSingleEntryLibraryDependency;
-
-import java.io.File;
-import java.io.Serializable;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class IdeaSingleEntryLibraryDependencyImpl extends AbstractGradleDependency
-  implements IdeaSingleEntryLibraryDependency, Serializable {
-
-  private File myFile;
-  private File mySource;
-  private File myJavadoc;
-
-  public IdeaSingleEntryLibraryDependencyImpl(IdeaDependencyScope myScope,
-                                              String dependencyName,
-                                              String dependencyGroup,
-                                              String dependencyVersion,
-                                              String classifier) {
-    super(myScope, dependencyName, dependencyGroup, dependencyVersion, classifier);
-  }
-
-  @Override
-  public File getFile() {
-    return myFile;
-  }
-
-  @Override
-  public File getSource() {
-    return mySource;
-  }
-
-  @Override
-  public File getJavadoc() {
-    return myJavadoc;
-  }
-
-  public void setFile(File file) {
-    myFile = file;
-  }
-
-  public void setSource(File source) {
-    mySource = source;
-  }
-
-  public void setJavadoc(File javadoc) {
-    myJavadoc = javadoc;
-  }
-
-  @Override
-  public GradleModuleVersion getGradleModuleVersion() {
-    return null;
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ProjectDependenciesModelImpl.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ProjectDependenciesModelImpl.java
deleted file mode 100644
index 1a57dc5..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/ProjectDependenciesModelImpl.java
+++ /dev/null
@@ -1,52 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-import org.gradle.tooling.model.idea.IdeaDependency;
-import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
-
-import java.util.List;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/8/13
- */
-public class ProjectDependenciesModelImpl implements ProjectDependenciesModel {
-  private final String projectName;
-  private final List<IdeaDependency> myDependencies;
-
-  public ProjectDependenciesModelImpl(String projectName, List<IdeaDependency> dependencies) {
-    this.projectName = projectName;
-    myDependencies = dependencies;
-  }
-
-  @Override
-  public String getProjectName() {
-    return projectName;
-  }
-
-  @Override
-  public List<IdeaDependency> getDependencies() {
-    return myDependencies;
-  }
-
-  @Override
-  public String toString() {
-    return "ProjectDependenciesModelImpl{" +
-           "projectName='" + projectName + '\'' +
-           '}';
-  }
-}
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/Scopes.java b/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/Scopes.java
deleted file mode 100644
index 0bce9e3..0000000
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/Scopes.java
+++ /dev/null
@@ -1,82 +0,0 @@
-/*
- * Copyright 2000-2014 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.tooling.internal;
-
-import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/25/13
- */
-public class Scopes {
-  private boolean myForProductionCompile;
-  private boolean myForProductionRuntime;
-  private boolean myForTestCompile;
-  private boolean myForTestRuntime;
-  private boolean myIsProvided;
-
-  public Scopes(GradleDependencyScope scope) {
-    myForProductionCompile = scope.isForProductionCompile();
-    myForProductionRuntime = scope.isForProductionRuntime();
-    myForTestCompile = scope.isForTestCompile();
-    myForTestRuntime = scope.isForTestRuntime();
-    myIsProvided = scope == GradleDependencyScope.PROVIDED_COMPILE ||
-                   scope == GradleDependencyScope.PROVIDED_RUNTIME;
-  }
-
-  public GradleDependencyScope[] getScopes() {
-    if (myIsProvided) {
-      if (myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) {
-        return new GradleDependencyScope[]{GradleDependencyScope.PROVIDED_COMPILE};
-      }
-      else if (!myForProductionCompile && myForProductionRuntime && !myForTestCompile && myForTestRuntime) {
-        return new GradleDependencyScope[]{GradleDependencyScope.PROVIDED_RUNTIME};
-      }
-      else if (!myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) {
-        return new GradleDependencyScope[]{GradleDependencyScope.TEST_COMPILE, GradleDependencyScope.PROVIDED_RUNTIME};
-      }
-    }
-
-    if (myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) {
-      return new GradleDependencyScope[]{GradleDependencyScope.COMPILE};
-    }
-    else if (!myForProductionCompile && myForProductionRuntime && !myForTestCompile && myForTestRuntime) {
-      return new GradleDependencyScope[]{GradleDependencyScope.RUNTIME};
-    }
-    else if (!myForProductionCompile && !myForProductionRuntime && myForTestCompile && myForTestRuntime) {
-      return new GradleDependencyScope[]{GradleDependencyScope.TEST_COMPILE};
-    }
-    else if (!myForProductionCompile && !myForProductionRuntime && !myForTestCompile && myForTestRuntime) {
-      return new GradleDependencyScope[]{GradleDependencyScope.TEST_RUNTIME};
-    }
-    else if (!myForProductionCompile && myForProductionRuntime && myForTestCompile && myForTestRuntime) {
-      return new GradleDependencyScope[]{GradleDependencyScope.TEST_COMPILE, GradleDependencyScope.RUNTIME};
-    }
-    else {
-      return new GradleDependencyScope[]{GradleDependencyScope.COMPILE};
-    }
-  }
-
-  public void add(GradleDependencyScope scope) {
-    myForProductionCompile = myForProductionCompile || scope.isForProductionCompile();
-    myForProductionRuntime = myForProductionRuntime || scope.isForProductionRuntime();
-    myForTestCompile = myForTestCompile || scope.isForTestCompile();
-    myForTestRuntime = myForTestRuntime || scope.isForTestRuntime();
-    myIsProvided = myIsProvided ||
-                   scope == GradleDependencyScope.PROVIDED_COMPILE ||
-                   scope == GradleDependencyScope.PROVIDED_RUNTIME;
-  }
-}
diff --git a/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties b/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties
index f0be716..d04ad38 100644
--- a/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties
+++ b/plugins/hg4idea/resources/org/zmlx/hg4idea/HgVcsMessages.properties
@@ -55,6 +55,8 @@
 hg4idea.run.success.title=Hg Executed Successfully
 hg4idea.run.failed.title=Hg Execution Failed
 
+hg4idea.configuration.ignore.whitespace.in.annotate=Ignore &whitespace differences in annotations
+
 hg4idea.command.executable.error=Error executing \"{0}\". Make sure you have setup the right executable in Mercurial configuration
 
 hg4idea.commit.success=Repository \"{0}\" committed
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java b/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java
index 246a3f6..ff82720 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/HgProjectSettings.java
@@ -16,6 +16,8 @@
 import com.intellij.openapi.components.State;
 import com.intellij.openapi.components.Storage;
 import com.intellij.openapi.components.StoragePathMacros;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.vcs.changes.VcsAnnotationRefresher;
 import org.jetbrains.annotations.NotNull;
 
 @State(
@@ -23,11 +25,14 @@
   storages = @Storage(file = StoragePathMacros.WORKSPACE_FILE)
 )
 public class HgProjectSettings implements PersistentStateComponent<HgProjectSettings.State> {
- @NotNull private final HgGlobalSettings myAppSettings;
+
+  @NotNull private final HgGlobalSettings myAppSettings;
+  @NotNull private final Project myProject;
 
   private State myState = new State();
 
-  public HgProjectSettings(@NotNull HgGlobalSettings appSettings) {
+  public HgProjectSettings(@NotNull Project project, @NotNull HgGlobalSettings appSettings) {
+    myProject = project;
     myAppSettings = appSettings;
   }
 
@@ -35,6 +40,7 @@
     public boolean myCheckIncoming = true;
     public boolean myCheckOutgoing = true;
     public Boolean CHECK_INCOMING_OUTGOING = null;
+    public boolean myIgnoreWhitespacesInAnnotations = true;
   }
 
   public State getState() {
@@ -52,10 +58,22 @@
     return myState.CHECK_INCOMING_OUTGOING != null && myState.CHECK_INCOMING_OUTGOING.booleanValue();
   }
 
+  public boolean isWhitespacesIgnoredInAnnotations() {
+    return myState.myIgnoreWhitespacesInAnnotations;
+  }
+
   public void setCheckIncomingOutgoing(boolean checkIncomingOutgoing) {
     myState.CHECK_INCOMING_OUTGOING = checkIncomingOutgoing;
   }
 
+  public void setIgnoreWhitespacesInAnnotations(boolean ignoreWhitespacesInAnnotations) {
+    final boolean changed = myState.myIgnoreWhitespacesInAnnotations != ignoreWhitespacesInAnnotations;
+    myState.myIgnoreWhitespacesInAnnotations = ignoreWhitespacesInAnnotations;
+    if (changed) {
+      myProject.getMessageBus().syncPublisher(VcsAnnotationRefresher.LOCAL_CHANGES_CHANGED).configurationChanged(HgVcs.getKey());
+    }
+  }
+
   public String getHgExecutable() {
     return myAppSettings.getHgExecutable();
   }
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/action/HgBranchPopupActions.java b/plugins/hg4idea/src/org/zmlx/hg4idea/action/HgBranchPopupActions.java
index 62d5981..45dd12b 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/action/HgBranchPopupActions.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/action/HgBranchPopupActions.java
@@ -25,7 +25,6 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Function;
 import com.intellij.util.PlatformIcons;
@@ -48,7 +47,8 @@
 
 import java.util.*;
 
-import static org.zmlx.hg4idea.util.HgUtil.*;
+import static org.zmlx.hg4idea.util.HgUtil.getNamesWithoutHashes;
+import static org.zmlx.hg4idea.util.HgUtil.getNewBranchNameFromUser;
 
 public class HgBranchPopupActions {
 
@@ -62,8 +62,8 @@
 
   ActionGroup createActions(@Nullable DefaultActionGroup toInsert) {
     DefaultActionGroup popupGroup = new DefaultActionGroup(null, false);
-    popupGroup.addAction(new HgNewBranchAction(myProject, Collections.singletonList(myRepository), myRepository.getRoot()));
-    popupGroup.addAction(new HgNewBookmarkAction(myProject, Collections.singletonList(myRepository), myRepository.getRoot()));
+    popupGroup.addAction(new HgNewBranchAction(myProject, Collections.singletonList(myRepository), myRepository));
+    popupGroup.addAction(new HgNewBookmarkAction(myProject, Collections.singletonList(myRepository), myRepository));
     popupGroup.addAction(new HgShowUnnamedHeadsForCurrentBranchAction(myProject, myRepository));
     if (toInsert != null) {
       popupGroup.addAll(toInsert);
@@ -92,24 +92,24 @@
   }
 
   private static class HgNewBranchAction extends NewBranchAction<HgRepository> {
-    @NotNull final VirtualFile myPreselectedRepo;
+    @NotNull final HgRepository myPreselectedRepo;
 
-    HgNewBranchAction(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull VirtualFile preselectedRepo) {
+    HgNewBranchAction(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull HgRepository preselectedRepo) {
       super(project, repositories);
       myPreselectedRepo = preselectedRepo;
     }
 
     @Override
     public void actionPerformed(AnActionEvent e) {
-      final String name = getNewBranchNameFromUser(myProject, "Create New Branch");
+      final String name = getNewBranchNameFromUser(myPreselectedRepo, "Create New Branch");
       if (name == null) {
         return;
       }
       try {
-        new HgBranchCreateCommand(myProject, myPreselectedRepo, name).execute(new HgCommandResultHandler() {
+        new HgBranchCreateCommand(myProject, myPreselectedRepo.getRoot(), name).execute(new HgCommandResultHandler() {
           @Override
           public void process(@Nullable HgCommandResult result) {
-            getRepositoryManager(myProject).updateRepository(myPreselectedRepo);
+            myPreselectedRepo.update();
             if (HgErrorUtil.hasErrorsInCommandExecution(result)) {
               new HgCommandResultNotifier(myProject)
                 .notifyError(result, "Creation failed", "Branch creation [" + name + "] failed");
@@ -124,11 +124,11 @@
   }
 
   private static class HgNewBookmarkAction extends DumbAwareAction {
-    protected final List<HgRepository> myRepositories;
-    protected Project myProject;
-    @NotNull final VirtualFile myPreselectedRepo;
+    @NotNull protected final List<HgRepository> myRepositories;
+    @NotNull protected Project myProject;
+    @NotNull final HgRepository myPreselectedRepo;
 
-    HgNewBookmarkAction(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull VirtualFile preselectedRepo) {
+    HgNewBookmarkAction(@NotNull Project project, @NotNull List<HgRepository> repositories, @NotNull HgRepository preselectedRepo) {
       super("New Bookmark", "Create new bookmark", null);
       myProject = project;
       myRepositories = repositories;
@@ -146,12 +146,12 @@
     @Override
     public void actionPerformed(AnActionEvent e) {
 
-      final HgBookmarkDialog bookmarkDialog = new HgBookmarkDialog(myProject);
+      final HgBookmarkDialog bookmarkDialog = new HgBookmarkDialog(myPreselectedRepo);
       bookmarkDialog.show();
       if (bookmarkDialog.isOK()) {
         try {
           final String name = bookmarkDialog.getName();
-          new HgBookmarkCommand(myProject, myPreselectedRepo, name).createBookmark(bookmarkDialog.isActive());
+          new HgBookmarkCommand(myProject, myPreselectedRepo.getRoot(), name).createBookmark(bookmarkDialog.isActive());
         }
         catch (HgCommandException exception) {
           HgAbstractGlobalAction.handleException(myProject, exception);
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgAnnotateCommand.java b/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgAnnotateCommand.java
index d1a9c0f..c546fb4 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgAnnotateCommand.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgAnnotateCommand.java
@@ -19,6 +19,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.zmlx.hg4idea.HgFile;
 import org.zmlx.hg4idea.HgRevisionNumber;
+import org.zmlx.hg4idea.HgVcs;
 import org.zmlx.hg4idea.execution.HgCommandExecutor;
 import org.zmlx.hg4idea.execution.HgCommandResult;
 import org.zmlx.hg4idea.provider.annotate.HgAnnotationLine;
@@ -55,6 +56,12 @@
   public List<HgAnnotationLine> execute(@NotNull HgFile hgFile, VcsFileRevision revision) {
     final List<String> arguments = new ArrayList<String>();
     arguments.add("-cvnudl");
+    HgVcs vcs = HgVcs.getInstance(myProject);
+    if (vcs != null &&
+        vcs.getProjectSettings().isWhitespacesIgnoredInAnnotations() &&
+        vcs.getVersion().isIgnoreWhitespaceDiffInAnnotationsSupported()) {
+      arguments.add("-w");
+    }
     if (revision != null) {
       arguments.add("-r");
       HgRevisionNumber revisionNumber = (HgRevisionNumber)revision.getRevisionNumber();
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java b/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java
index 84b070e..9554e9c 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java
@@ -38,6 +38,8 @@
 import java.text.SimpleDateFormat;
 import java.util.*;
 
+import static org.zmlx.hg4idea.util.HgUtil.TIP_REFERENCE;
+
 public class HgLogProvider implements VcsLogProvider {
 
   private static final Logger LOG = Logger.getInstance(HgLogProvider.class);
@@ -47,8 +49,6 @@
   @NotNull private final VcsLogRefManager myRefSorter;
   @NotNull private final VcsLogObjectsFactory myVcsObjectsFactory;
 
-  private static final String RECENT_HEAD = "tip";
-
   public HgLogProvider(@NotNull Project project, @NotNull HgRepositoryManager repositoryManager, @NotNull VcsLogObjectsFactory factory) {
     myProject = project;
     myRepositoryManager = repositoryManager;
@@ -119,7 +119,7 @@
     }
     String currentRevision = repository.getCurrentRevision();
     if (currentRevision != null) { // null => fresh repository
-      refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(currentRevision), RECENT_HEAD, HgRefManager.HEAD, root));
+      refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(currentRevision), TIP_REFERENCE, HgRefManager.HEAD, root));
     }
     for (HgNameWithHashInfo tagInfo : tags) {
       refs.add(myVcsObjectsFactory.createRef(tagInfo.getHash(), tagInfo.getName(), HgRefManager.TAG, root));
@@ -172,7 +172,7 @@
 
       boolean atLeastOneBranchExists = false;
       for (String branchName : filterCollection.getBranchFilter().getBranchNames()) {
-        if (branchName.equals(RECENT_HEAD) || branchExists(repository, branchName)) {
+        if (branchName.equals(TIP_REFERENCE) || branchExists(repository, branchName)) {
           filterParameters.add(prepareParameter("branch", branchName));
           atLeastOneBranchExists = true;
         }
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgBookmarkDialog.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgBookmarkDialog.java
index 6c471f1..8addb55 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgBookmarkDialog.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgBookmarkDialog.java
@@ -1,9 +1,7 @@
 package org.zmlx.hg4idea.ui;
 
-import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.ValidationInfo;
-import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.ui.DocumentAdapter;
 import com.intellij.ui.components.JBCheckBox;
 import com.intellij.ui.components.JBLabel;
 import com.intellij.ui.components.JBTextField;
@@ -11,8 +9,11 @@
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
+import org.zmlx.hg4idea.repo.HgRepository;
+import org.zmlx.hg4idea.util.HgReferenceValidator;
 
 import javax.swing.*;
+import javax.swing.event.DocumentEvent;
 import java.awt.*;
 
 import static com.intellij.util.ui.UIUtil.DEFAULT_HGAP;
@@ -22,11 +23,13 @@
  * @author Nadya Zabrodina
  */
 public class HgBookmarkDialog extends DialogWrapper {
+  @NotNull private HgRepository myRepository;
   @NotNull private JBTextField myBookmarkName;
   @NotNull private JBCheckBox myActiveCheckbox;
 
-  public HgBookmarkDialog(@Nullable Project project) {
-    super(project, false);
+  public HgBookmarkDialog(@NotNull HgRepository repository) {
+    super(repository.getProject(), false);
+    myRepository = repository;
     setTitle("Create Bookmark");
     setResizable(false);
     init();
@@ -62,6 +65,12 @@
 
     JLabel icon = new JLabel(UIUtil.getQuestionIcon(), SwingConstants.LEFT);
     myBookmarkName = new JBTextField(13);
+    myBookmarkName.getDocument().addDocumentListener(new DocumentAdapter() {
+      @Override
+      public void textChanged(DocumentEvent e) {
+        validateFields();
+      }
+    });
 
     JBLabel bookmarkLabel = new JBLabel("Bookmark name:");
     bookmarkLabel.setLabelFor(myBookmarkName);
@@ -75,6 +84,19 @@
     return contentPanel;
   }
 
+  private void validateFields() {
+    HgReferenceValidator validator = HgReferenceValidator.newInstance(myRepository);
+    String name = getName();
+    if (!validator.checkInput(name)) {
+      String message = validator.getErrorText(name);
+      setErrorText(message == null ? "You have to specify bookmark name." : message);
+      setOKActionEnabled(false);
+      return;
+    }
+    setErrorText(null);
+    setOKActionEnabled(true);
+  }
+
   public boolean isActive() {
     return !myActiveCheckbox.isSelected();
   }
@@ -83,14 +105,4 @@
   public String getName() {
     return myBookmarkName.getText();
   }
-
-  @Override
-  @Nullable
-  protected ValidationInfo doValidate() {
-    String message = "You have to specify bookmark name.";
-    if (StringUtil.isEmptyOrSpaces(getName())) {
-      return new ValidationInfo(message, myBookmarkName);
-    }
-    return null;
-  }
 }
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCommonDialogWithChoices.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCommonDialogWithChoices.java
index 4c7ff62..2c28d4c 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCommonDialogWithChoices.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgCommonDialogWithChoices.java
@@ -31,6 +31,8 @@
 import java.awt.event.ActionListener;
 import java.util.Collection;
 
+import static org.zmlx.hg4idea.util.HgUtil.TIP_REFERENCE;
+
 public class HgCommonDialogWithChoices extends DialogWrapper {
 
 
@@ -119,7 +121,8 @@
     HgRepository repo = hgRepositorySelectorComponent.getRepository();
     branchSelector.setModel(new DefaultComboBoxModel(repo.getOpenedBranches().toArray()));
     DefaultComboBoxModel tagComboBoxModel = new DefaultComboBoxModel(HgUtil.getNamesWithoutHashes(repo.getTags()).toArray());
-    tagComboBoxModel.addElement("tip");    //HgRepository does not store 'tip' tag because it is internal and not included in tags file
+    tagComboBoxModel
+      .addElement(TIP_REFERENCE);    //HgRepository does not store 'tip' tag because it is internal and not included in tags file
     tagSelector.setModel(tagComboBoxModel);
     bookmarkSelector.setModel(new DefaultComboBoxModel(HgUtil.getNamesWithoutHashes(repo.getBookmarks()).toArray()));
     update();
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.form b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.form
index a9fbc33..38dc6eb 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.form
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.form
@@ -8,7 +8,7 @@
     <properties/>
     <border type="none"/>
     <children>
-      <grid id="8c1f" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+      <grid id="8c1f" 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="0" bottom="0" right="0"/>
         <constraints>
           <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="8" fill="2" indent="0" use-parent-layout="false"/>
@@ -28,6 +28,15 @@
               <text value="Check for &amp;incoming and outgoing changesets"/>
             </properties>
           </component>
+          <component id="36003" class="javax.swing.JCheckBox" binding="myIgnoredWhitespacesInAnnotationsCbx">
+            <constraints>
+              <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="3" anchor="8" fill="0" indent="0" use-parent-layout="false"/>
+            </constraints>
+            <properties>
+              <selected value="true"/>
+              <text resource-bundle="org/zmlx/hg4idea/HgVcsMessages" key="hg4idea.configuration.ignore.whitespace.in.annotate"/>
+            </properties>
+          </component>
         </children>
       </grid>
       <grid id="4e3f3" layout-manager="GridLayoutManager" row-count="1" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.java
index d906808..2aff907 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgConfigurationProjectPanel.java
@@ -33,6 +33,7 @@
 
   private JPanel myMainPanel;
   private JCheckBox myCheckIncomingOutgoingCbx;
+  private JCheckBox myIgnoredWhitespacesInAnnotationsCbx;
   private TextFieldWithBrowseButton myPathSelector;
   private JButton myTestButton;
   private final HgVcs myVcs;
@@ -61,11 +62,14 @@
 
   public boolean isModified() {
     boolean executableModified = !getCurrentPath().equals(myProjectSettings.getHgExecutable());
-    return executableModified || myCheckIncomingOutgoingCbx.isSelected() != myProjectSettings.isCheckIncomingOutgoing();
+    return executableModified ||
+           myCheckIncomingOutgoingCbx.isSelected() != myProjectSettings.isCheckIncomingOutgoing() ||
+           myIgnoredWhitespacesInAnnotationsCbx.isSelected() != myProjectSettings.isWhitespacesIgnoredInAnnotations();
   }
 
   public void saveSettings() {
     myProjectSettings.setCheckIncomingOutgoing(myCheckIncomingOutgoingCbx.isSelected());
+    myProjectSettings.setIgnoreWhitespacesInAnnotations(myIgnoredWhitespacesInAnnotationsCbx.isSelected());
     myProjectSettings.setHgExecutable(getCurrentPath());
     myVcs.checkVersion();
   }
@@ -75,7 +79,8 @@
   }
 
   public void loadSettings() {
-    myCheckIncomingOutgoingCbx.setSelected(myProjectSettings.isCheckIncomingOutgoing() );
+    myCheckIncomingOutgoingCbx.setSelected(myProjectSettings.isCheckIncomingOutgoing());
+    myIgnoredWhitespacesInAnnotationsCbx.setSelected(myProjectSettings.isWhitespacesIgnoredInAnnotations());
     myPathSelector.setText(myProjectSettings.getGlobalSettings().getHgExecutable());
   }
 
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgTagDialog.java b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgTagDialog.java
index df4bb61..3a986e5 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgTagDialog.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/ui/HgTagDialog.java
@@ -14,11 +14,12 @@
 
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.ui.DocumentAdapter;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.zmlx.hg4idea.repo.HgRepository;
+import org.zmlx.hg4idea.util.HgReferenceValidator;
 
 import javax.swing.*;
 import javax.swing.event.DocumentEvent;
@@ -34,17 +35,10 @@
   public HgTagDialog(@NotNull Project project, @NotNull Collection<HgRepository> repos, @Nullable HgRepository selectedRepo) {
     super(project, false);
     hgRepositorySelectorComponent.setTitle("Select repository to tag");
-    DocumentListener documentListener = new DocumentListener() {
-      public void insertUpdate(DocumentEvent e) {
-        update();
-      }
-
-      public void removeUpdate(DocumentEvent e) {
-        update();
-      }
-
-      public void changedUpdate(DocumentEvent e) {
-        update();
+    DocumentListener documentListener = new DocumentAdapter() {
+      @Override
+      protected void textChanged(DocumentEvent e) {
+        validateFields();
       }
     };
 
@@ -67,19 +61,23 @@
   private void setRoots(@NotNull Collection<HgRepository> repos, @Nullable HgRepository selectedRepo) {
     hgRepositorySelectorComponent.setRoots(repos);
     hgRepositorySelectorComponent.setSelectedRoot(selectedRepo);
-    update();
   }
 
   protected JComponent createCenterPanel() {
     return contentPanel;
   }
 
-  private void update() {
-    setOKActionEnabled(validateOptions());
-  }
-
-  private boolean validateOptions() {
-    return !StringUtil.isEmptyOrSpaces(tagTxt.getText());
+  private void validateFields() {
+    HgReferenceValidator validator = HgReferenceValidator.newInstance(hgRepositorySelectorComponent.getRepository());
+    String name = getTagName();
+    if (!validator.checkInput(name)) {
+      String message = validator.getErrorText(name);
+      setErrorText(message == null ? "You have to specify tag name." : message);
+      setOKActionEnabled(false);
+      return;
+    }
+    setErrorText(null);
+    setOKActionEnabled(true);
   }
 
   @Override
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgReferenceValidator.java b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgReferenceValidator.java
new file mode 100644
index 0000000..27dadb5
--- /dev/null
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgReferenceValidator.java
@@ -0,0 +1,82 @@
+/*
+ * Copyright 2000-2014 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.zmlx.hg4idea.util;
+
+import com.intellij.openapi.ui.InputValidatorEx;
+import com.intellij.openapi.util.text.StringUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.zmlx.hg4idea.repo.HgRepository;
+
+import java.util.Collection;
+import java.util.regex.Pattern;
+
+import static org.zmlx.hg4idea.util.HgUtil.TIP_REFERENCE;
+
+public class HgReferenceValidator implements InputValidatorEx {
+
+  private final HgRepository myRepository;
+  private String myErrorText;
+
+  private static final Pattern ILLEGAL = Pattern.compile(
+    ".*:.*|" + // colon character is not allowed
+    "[0-9]*" // reference name couldn't contain only digits
+  );
+
+  private HgReferenceValidator(@NotNull HgRepository repository) {
+    myRepository = repository;
+  }
+
+  public static HgReferenceValidator newInstance(@NotNull HgRepository repository) {
+    return new HgReferenceValidator(repository);
+  }
+
+  @Override
+  public boolean checkInput(@Nullable String name) {
+    if (StringUtil.isEmptyOrSpaces(name)) {
+      return false;
+    }
+    if (ILLEGAL.matcher(name).matches()) {
+      myErrorText = "Invalid name for branch/tag";
+      return false;
+    }
+    return !isReservedWord(name) && !hasConflictsWithAnotherBranch(name);
+  }
+
+  @Override
+  public boolean canClose(@Nullable String name) {
+    return checkInput(name);
+  }
+
+  boolean isReservedWord(@Nullable String name) {
+    myErrorText = TIP_REFERENCE.equals(name) ? String.format("The name \'%s\' is reserved.", name) : null;
+    return myErrorText != null;
+  }
+
+  boolean hasConflictsWithAnotherBranch(@Nullable String name) {
+    Collection<String> branches = myRepository.getBranches().keySet();
+    String currentBranch = myRepository.getCurrentBranch(); //  branches set doesn't contain uncommitted branch -> need an addition check
+    myErrorText = currentBranch.equals(name) || branches.contains(name)
+                  ? String.format("A branch with the \'%s\' name already exists", name) : null;
+    return myErrorText != null;
+  }
+
+  @Nullable
+  @Override
+  public String getErrorText(@Nullable String inputString) {
+    return myErrorText;
+  }
+}
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java
index ad1ad61..d0c52d7 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgUtil.java
@@ -72,6 +72,7 @@
   public static final int MANY_FILES = 100;
   private static final Logger LOG = Logger.getInstance(HgUtil.class);
   public static final String DOT_HG = ".hg";
+  public static final String TIP_REFERENCE = "tip";
 
   public static File copyResourceToTempFile(String basename, String extension) throws IOException {
     final InputStream in = HgUtil.class.getClassLoader().getResourceAsStream("python/" + basename + extension);
@@ -323,14 +324,17 @@
   }
 
   /**
-    * Shows a message dialog to enter the name of new branch.
-    * @return name of new branch or {@code null} if user has cancelled the dialog.
-    */
-   @Nullable
-   public static String getNewBranchNameFromUser(@NotNull Project project,
-                                                 @NotNull String dialogTitle) {
-     return Messages.showInputDialog(project, "Enter the name of new branch:", dialogTitle, Messages.getQuestionIcon());
-   }
+   * Shows a message dialog to enter the name of new branch.
+   *
+   * @return name of new branch or {@code null} if user has cancelled the dialog.
+   */
+  @Nullable
+  public static String getNewBranchNameFromUser(@NotNull HgRepository repository,
+                                                @NotNull String dialogTitle) {
+    return Messages.showInputDialog(repository.getProject(), "Enter the name of new branch:", dialogTitle, Messages.getQuestionIcon(), "",
+                                    HgReferenceValidator.newInstance(repository));
+  }
+
   /**
    * Checks is a merge operation is in progress on the given repository.
    * Actually gets the number of parents of the current revision. If there are 2 parents, then a merge is going on. Otherwise there is
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java
index 1883f29..a01e654 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java
@@ -56,6 +56,7 @@
   public static final HgVersion PARENT_REVISION_TEMPLATES_SUPPORTED = new HgVersion(2, 4, 0);
   public static final HgVersion BRANCH_HEADS_BASE_SERVED_FILE_EXIST = new HgVersion(2, 5, 0);
   public static final HgVersion BRANCH2_FILE_EXIST = new HgVersion(2, 9, 0);
+  public static final HgVersion IGNORE_WHITESPACE_DIFF_IN_ANNOTATIONS = new HgVersion(2, 1, 0);
 
   //see http://selenic.com/pipermail/mercurial-devel/2013-May/051209.html  fixed since 2.7
   private static final HgVersion LARGEFILES_WITH_FOLLOW_SUPPORTED = new HgVersion(2, 7, 0);
@@ -163,6 +164,10 @@
     return compareTo(PARENT_REVISION_TEMPLATES_SUPPORTED) >= 0;
   }
 
+  public boolean isIgnoreWhitespaceDiffInAnnotationsSupported() {
+    return compareTo(IGNORE_WHITESPACE_DIFF_IN_ANNOTATIONS) >= 0;
+  }
+
   public boolean hasBranchHeadsBaseServed() {
     return compareTo(BRANCH_HEADS_BASE_SERVED_FILE_EXIST) >= 0 && compareTo(BRANCH2_FILE_EXIST) < 0;
   }
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/HgExecutor.java b/plugins/hg4idea/testSrc/hg4idea/test/HgExecutor.java
index eb2c592..2a654c4 100644
--- a/plugins/hg4idea/testSrc/hg4idea/test/HgExecutor.java
+++ b/plugins/hg4idea/testSrc/hg4idea/test/HgExecutor.java
@@ -25,9 +25,6 @@
 import java.util.Arrays;
 import java.util.List;
 
-/**
- * @author Nadya Zabrodina
- */
 public class HgExecutor extends Executor {
 
   private static final String HG_EXECUTABLE_ENV = "IDEA_TEST_HG_EXECUTABLE";
@@ -61,16 +58,24 @@
   }
 
   public static String hg(String command) {
+    return hg(command, false);
+  }
+
+  public static String hg(String command, boolean ignoreNonZeroExitCode) {
     List<String> split = splitCommandInParameters(command);
     split.add(0, HG_EXECUTABLE);
     debug("hg " + command);
-    return run(split, true);
+    return run(split, ignoreNonZeroExitCode);
   }
 
   public static void updateProject() {
     hg("pull");
-    hg("update");
-    hg("merge");
+    hg("update", true);
+    hgMergeWith("");
+  }
+
+  public static void hgMergeWith(@NotNull String mergeWith) {
+    hg("merge " + mergeWith, true);
   }
 
   @NotNull
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/annotation/HgAnnotationTest.java b/plugins/hg4idea/testSrc/hg4idea/test/annotation/HgAnnotationTest.java
index 8648791..eec9de1 100644
--- a/plugins/hg4idea/testSrc/hg4idea/test/annotation/HgAnnotationTest.java
+++ b/plugins/hg4idea/testSrc/hg4idea/test/annotation/HgAnnotationTest.java
@@ -14,13 +14,9 @@
 import java.util.Date;
 import java.util.List;
 
-import static com.intellij.openapi.vcs.Executor.cd;
-import static com.intellij.openapi.vcs.Executor.echo;
+import static com.intellij.openapi.vcs.Executor.*;
 import static hg4idea.test.HgExecutor.hg;
 
-/**
- * @author Nadya Zabrodina
- */
 public class HgAnnotationTest extends HgPlatformTest {
   String firstCreatedFile = "file.txt";
   static final String author1 = "[email protected]";
@@ -53,4 +49,32 @@
       assertEquals(date, line.get(HgAnnotation.FIELD.DATE));
     }
   }
+
+  public void testAnnotationWithIgnoredWhitespaces() {
+    annotationWithWhitespaceOption(true);
+  }
+
+  public void testAnnotationWithoutIgnoredWhitespaces() {
+    annotationWithWhitespaceOption(false);
+  }
+
+  private void annotationWithWhitespaceOption(boolean ignoreWhitespaces) {
+    cd(myRepository);
+    String whitespaceFile = "whitespaces.txt";
+    touch(whitespaceFile, "not whitespaces");
+    myRepository.refresh(false, true);
+    String whiteSpaceAuthor = "Mr.Whitespace";
+    final VirtualFile file = myRepository.findFileByRelativePath(whitespaceFile);
+    assert file != null;
+    hg("add " + whitespaceFile);
+    hg("commit -m modify -u '" + defaultAuthor + "'");
+    echo(whitespaceFile, "    ");//add several whitespaces
+    hg("commit -m whitespaces -u '" + whiteSpaceAuthor + "'");
+    final HgFile hgFile = new HgFile(myRepository, VfsUtilCore.virtualToIoFile(file));
+    myVcs.getProjectSettings().setIgnoreWhitespacesInAnnotations(ignoreWhitespaces);
+    List<HgAnnotationLine> annotationLines =
+      new HgAnnotateCommand(myProject).execute(hgFile, null);
+    HgAnnotationLine line = annotationLines.get(0);
+    assertEquals(ignoreWhitespaces ? defaultAuthor : whiteSpaceAuthor, line.get(HgAnnotation.FIELD.USER));
+  }
 }
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/merge/HgMergeProviderTest.java b/plugins/hg4idea/testSrc/hg4idea/test/merge/HgMergeProviderTest.java
index 1fc377d..ff07a3a 100644
--- a/plugins/hg4idea/testSrc/hg4idea/test/merge/HgMergeProviderTest.java
+++ b/plugins/hg4idea/testSrc/hg4idea/test/merge/HgMergeProviderTest.java
@@ -27,13 +27,11 @@
 
 import java.io.IOException;
 
-import static com.intellij.openapi.vcs.Executor.*;
-import static hg4idea.test.HgExecutor.hg;
-import static hg4idea.test.HgExecutor.updateProject;
+import static com.intellij.openapi.vcs.Executor.cd;
+import static com.intellij.openapi.vcs.Executor.echo;
+import static com.intellij.openapi.vcs.Executor.touch;
+import static hg4idea.test.HgExecutor.*;
 
-/**
- * @author Nadya Zabrodina
- */
 public class HgMergeProviderTest extends HgPlatformTest {
   protected MergeProvider myMergeProvider;
 
@@ -59,7 +57,7 @@
     touch(aFile, "default");
     hg("add " + aFile);
     hg("commit -m 'create file in default branch'");
-    hg("merge branchA");
+    hgMergeWith("branchA");
     verifyMergeData(myRepository.findChild(aFile), "", "default", "a");
   }
 
@@ -76,7 +74,7 @@
     hg("up default");
     echo(aFile, " modify with b");
     hg("commit -m 'modify file in default'");
-    hg("merge branchA");
+    hgMergeWith("branchA");
     verifyMergeData(myRepository.findChild(aFile), "base", "base modify with b", "base modify with a");
   }
 
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/repo/HgRealRepositoryReaderTest.java b/plugins/hg4idea/testSrc/hg4idea/test/repo/HgRealRepositoryReaderTest.java
index 0702f44..0792a96 100644
--- a/plugins/hg4idea/testSrc/hg4idea/test/repo/HgRealRepositoryReaderTest.java
+++ b/plugins/hg4idea/testSrc/hg4idea/test/repo/HgRealRepositoryReaderTest.java
@@ -29,10 +29,8 @@
 
 import static com.intellij.openapi.vcs.Executor.*;
 import static hg4idea.test.HgExecutor.hg;
+import static hg4idea.test.HgExecutor.hgMergeWith;
 
-/**
- * @author Nadya Zabrodina
- */
 public class HgRealRepositoryReaderTest extends HgPlatformTest {
 
   @NotNull private HgRepositoryReader myRepositoryReader;
@@ -47,7 +45,7 @@
   }
 
   public void testMergeState() {
-    hg("merge branchB");
+    hgMergeWith("branchB");
     assertEquals(myRepositoryReader.readState(), Repository.State.MERGING);
   }
 
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/validator/HgReferenceValidatorTest.java b/plugins/hg4idea/testSrc/hg4idea/test/validator/HgReferenceValidatorTest.java
new file mode 100644
index 0000000..3bec11a
--- /dev/null
+++ b/plugins/hg4idea/testSrc/hg4idea/test/validator/HgReferenceValidatorTest.java
@@ -0,0 +1,116 @@
+/*
+ * Copyright 2000-2014 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 hg4idea.test.validator;
+
+import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.ui.UIUtil;
+import hg4idea.test.HgPlatformTest;
+import hg4idea.test.HgTestUtil;
+import org.jetbrains.annotations.NotNull;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.zmlx.hg4idea.repo.HgRepository;
+import org.zmlx.hg4idea.util.HgReferenceValidator;
+import org.zmlx.hg4idea.util.HgUtil;
+
+import java.util.Collection;
+
+import static com.intellij.openapi.vcs.Executor.cd;
+import static com.intellij.openapi.vcs.Executor.echo;
+import static hg4idea.test.HgExecutor.hg;
+
+@RunWith(Parameterized.class)
+public class HgReferenceValidatorTest extends HgPlatformTest {
+
+  private HgReferenceValidator myValidator;
+  private static final String BRANCH_NAME = "Abranch";
+  private static final String UNCOMMITTED_BRANCH = "uncommitted new branch";
+
+  @NotNull private final String myBranchName;
+  private final boolean myExpected;
+
+
+  @Override
+  @Before
+  public void setUp() throws Exception {
+    super.setUp();
+    HgTestUtil.updateDirectoryMappings(myProject, myRepository);
+    HgRepository hgRepository = HgUtil.getRepositoryManager(myProject).getRepositoryForRoot(myRepository);
+    assertNotNull(hgRepository);
+    myValidator = HgReferenceValidator.newInstance(hgRepository);
+    cd(myRepository);
+    hg("branch '" + BRANCH_NAME + "'");
+    String firstFile = "file.txt";
+    echo(firstFile, BRANCH_NAME);
+    hg("commit -m 'createdBranch " + BRANCH_NAME + "' ");
+    hg("branch '" + UNCOMMITTED_BRANCH + "'");
+    hgRepository.update();
+  }
+
+  @Override
+  @After
+  public void tearDown() throws Exception {
+    UIUtil.invokeAndWaitIfNeeded(new Runnable() {
+      @Override
+      public void run() {
+        try {
+          HgReferenceValidatorTest.super.tearDown();
+        }
+        catch (Exception e) {
+          throw new RuntimeException(e);
+        }
+      }
+    });
+  }
+
+  @SuppressWarnings({"JUnitTestCaseWithNonTrivialConstructors", "UnusedParameters"})
+  public HgReferenceValidatorTest(@NotNull String name, @NotNull String branchName, boolean expected) {
+    myBranchName = branchName;
+    myExpected = expected;
+  }
+
+
+  @Parameterized.Parameters(name = "{0}")
+  public static Collection<Object[]> createData() {
+    return ContainerUtil.newArrayList(new Object[][]{
+      {"WORD", "branch", true},
+      {"UNDERSCORED_WORD", "new_branch", true},
+      {"HIERARCHY", "user/branch", true},
+      {"HIERARCHY_2", "user/branch/sub_branch", true},
+      {"BEGINS_WITH_SLASH", "/branch", true},
+      {"WITH_DOTS", "complex.branch.name", true},
+      {"WITH_WHITESPACES", "branch with whitespaces", true},
+      {"WITH_SPECIAL_CHARS", "bra~nch-^%$", true},
+      {"NOT_RESERVED", "TIP", true},
+      {"CONTAINS_COLON", "bra:nch", false},
+      {"ONLY_DIGITS", "876876", false},
+      {"START_WITH_COLON", ":branch", false},
+      {"ENDS_WITH_COLON", "branch:", false},
+      {"RESERVED_WORD", "tip", false},
+      {"BRANCH_CONFLICT", BRANCH_NAME, false},
+      {"UNCOMMITTED_BRANCH_CONFLICT", UNCOMMITTED_BRANCH, false},
+    });
+  }
+
+  @Test
+  public void testValid() {
+    assertEquals(" Wrong validation for " + myBranchName, myExpected, myValidator.checkInput(myBranchName));
+    assertEquals(" Should be valid " + myBranchName, myExpected, myValidator.canClose(myBranchName));
+  }
+}
diff --git a/plugins/java-i18n/src/META-INF/plugin.xml b/plugins/java-i18n/src/META-INF/plugin.xml
index 02c6b05..399a142 100644
--- a/plugins/java-i18n/src/META-INF/plugin.xml
+++ b/plugins/java-i18n/src/META-INF/plugin.xml
@@ -37,7 +37,7 @@
     <globalInspection shortName="InconsistentResourceBundle" bundle="messages.InspectionsBundle"
                       key="inconsistent.resource.bundle.display.name" groupBundle="messages.PropertiesBundle"
                       groupKey="properties.files.inspection.group.display.name" enabledByDefault="true" level="ERROR"
-                      implementationClass="com.intellij.codeInspection.i18n.InconsistentResourceBundleInspection"/>
+                      implementationClass="com.intellij.codeInspection.i18n.inconsistentResourceBundle.InconsistentResourceBundleInspection"/>
     <localInspection language="Properties" shortName="UnusedMessageFormatParameter" bundle="messages.PropertiesBundle"
                      key="unused.message.format.parameter.display.name" groupKey="properties.files.inspection.group.display.name"
                      enabledByDefault="true" level="WARNING"
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/InconsistentResourceBundleInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/InconsistentResourceBundleInspection.java
deleted file mode 100644
index f04eac7..0000000
--- a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/InconsistentResourceBundleInspection.java
+++ /dev/null
@@ -1,236 +0,0 @@
-/*
- * Copyright 2000-2009 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.codeInspection.i18n;
-
-import com.intellij.codeHighlighting.HighlightDisplayLevel;
-import com.intellij.codeInspection.*;
-import com.intellij.codeInspection.reference.RefManager;
-import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
-import com.intellij.lang.properties.*;
-import com.intellij.lang.properties.psi.PropertiesFile;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Key;
-import com.intellij.psi.PsiFile;
-import com.intellij.util.containers.BidirectionalMap;
-import gnu.trove.THashMap;
-import gnu.trove.THashSet;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import javax.swing.*;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-
-/**
- * @author max
- */
-public class InconsistentResourceBundleInspection extends GlobalSimpleInspectionTool {
-  @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_MISSING_TRANSLATIONS = true;
-  @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_INCONSISTENT_PROPERTIES = true;
-  @SuppressWarnings({"WeakerAccess"}) public boolean REPORT_DUPLICATED_PROPERTIES = true;
-
-  @Override
-  @NotNull
-  public String getGroupDisplayName() {
-    return PropertiesBundle.message("properties.files.inspection.group.display.name");
-  }
-
-  @Override
-  @NotNull
-  public String getDisplayName() {
-    return InspectionsBundle.message("inconsistent.resource.bundle.display.name");
-  }
-
-  @Override
-  @NotNull
-  public String getShortName() {
-    return "InconsistentResourceBundle";
-  }
-
-  @Override
-  @NotNull
-  public HighlightDisplayLevel getDefaultLevel() {
-    return HighlightDisplayLevel.ERROR;
-  }
-
-  @Override
-  @Nullable
-  public JComponent createOptionsPanel() {
-    final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this);
-    panel.addCheckbox(InspectionsBundle.message("inconsistent.bundle.report.inconsistent.properties"), "REPORT_INCONSISTENT_PROPERTIES");
-    panel.addCheckbox(InspectionsBundle.message("inconsistent.bundle.report.missing.translations"), "REPORT_MISSING_TRANSLATIONS");
-    panel.addCheckbox(InspectionsBundle.message("inconsistent.bundle.report.duplicate.properties.values"), "REPORT_DUPLICATED_PROPERTIES");
-    return panel;
-  }
-
-
-  private static final Key<Set<ResourceBundle>> VISITED_BUNDLES_KEY = Key.create("VISITED_BUNDLES_KEY");
-  @Override
-  public void inspectionStarted(@NotNull InspectionManager manager,
-                                @NotNull GlobalInspectionContext globalContext,
-                                @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
-    globalContext.putUserData(VISITED_BUNDLES_KEY, new THashSet<ResourceBundle>());
-  }
-
-  @Override
-  public void checkFile(@NotNull PsiFile file,
-                        @NotNull InspectionManager manager,
-                        @NotNull ProblemsHolder problemsHolder,
-                        @NotNull GlobalInspectionContext globalContext,
-                        @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
-    Set<ResourceBundle> visitedBundles = globalContext.getUserData(VISITED_BUNDLES_KEY);
-    checkFile(file, manager, visitedBundles, globalContext.getRefManager(), problemDescriptionsProcessor);
-  }
-
-  private void checkFile(@NotNull final PsiFile file,
-                         @NotNull final InspectionManager manager,
-                         @NotNull Set<ResourceBundle> visitedBundles,
-                         RefManager refManager, ProblemDescriptionsProcessor processor) {
-    if (!(file instanceof PropertiesFile)) return;
-    final PropertiesFile propertiesFile = (PropertiesFile)file;
-    ResourceBundle resourceBundle = propertiesFile.getResourceBundle();
-    if (!visitedBundles.add(resourceBundle)) return;
-    List<PropertiesFile> files = resourceBundle.getPropertiesFiles(manager.getProject());
-    if (files.size() < 2) return;
-    BidirectionalMap<PropertiesFile, PropertiesFile> parents = new BidirectionalMap<PropertiesFile, PropertiesFile>();
-    for (PropertiesFile f : files) {
-      PropertiesFile parent = PropertiesUtil.getParent(f, files);
-      if (parent != null) {
-        parents.put(f, parent);
-      }
-    }
-    Map<PropertiesFile, Set<String>> keysUpToParent = new THashMap<PropertiesFile, Set<String>>();
-    for (PropertiesFile f : files) {
-      Set<String> keys = new THashSet<String>(f.getNamesMap().keySet());
-      PropertiesFile parent = parents.get(f);
-      while (parent != null) {
-        keys.addAll(parent.getNamesMap().keySet());
-        parent = parents.get(parent);
-      }
-      keysUpToParent.put(f, keys);
-    }
-    if (REPORT_MISSING_TRANSLATIONS) {
-      checkMissingTranslations(parents, files, keysUpToParent, manager, refManager, processor);
-    }
-    if (REPORT_INCONSISTENT_PROPERTIES) {
-      checkConsistency(parents, files, keysUpToParent, manager, refManager, processor);
-    }
-    if (REPORT_DUPLICATED_PROPERTIES) {
-      checkDuplicatedProperties(parents, files, keysUpToParent, manager, refManager, processor);
-    }
-  }
-
-  private static void checkDuplicatedProperties(final BidirectionalMap<PropertiesFile, PropertiesFile> parents,
-                                                final List<PropertiesFile> files,
-                                                final Map<PropertiesFile, Set<String>> keysUpToParent,
-                                                final InspectionManager manager,
-                                                RefManager refManager,
-                                                ProblemDescriptionsProcessor processor) {
-    for (PropertiesFile file : files) {
-      PropertiesFile parent = parents.get(file);
-      if (parent == null) continue;
-      Set<String> parentKeys = keysUpToParent.get(parent);
-      Set<String> overriddenKeys = new THashSet<String>(file.getNamesMap().keySet());
-      overriddenKeys.retainAll(parentKeys);
-      for (String overriddenKey : overriddenKeys) {
-        IProperty property = file.findPropertyByKey(overriddenKey);
-        assert property != null;
-        while (parent != null) {
-          IProperty parentProperty = parent.findPropertyByKey(overriddenKey);
-          if (parentProperty != null && Comparing.strEqual(property.getValue(), parentProperty.getValue())) {
-            String message = InspectionsBundle.message("inconsistent.bundle.property.inherited.with.the.same.value", parent.getName());
-            ProblemDescriptor descriptor = manager.createProblemDescriptor(property.getPsiElement(), message,
-                                                                           RemovePropertyLocalFix.INSTANCE,
-                                                                           ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false);
-            processor.addProblemElement(refManager.getReference(file.getContainingFile()), descriptor);
-          }
-          parent = parents.get(parent);
-        }
-      }
-    }
-  }
-
-  private static void checkConsistency(final BidirectionalMap<PropertiesFile, PropertiesFile> parents, final List<PropertiesFile> files,
-                                       final Map<PropertiesFile, Set<String>> keysUpToParent,
-                                       final InspectionManager manager,
-                                       RefManager refManager, ProblemDescriptionsProcessor processor) {
-    for (PropertiesFile file : files) {
-      PropertiesFile parent = parents.get(file);
-      Set<String> parentKeys = keysUpToParent.get(parent);
-      if (parent == null) {
-        parentKeys = new THashSet<String>();
-        for (PropertiesFile otherTopLevelFile : files) {
-          if (otherTopLevelFile != file && parents.get(otherTopLevelFile) == null) {
-            parent = otherTopLevelFile;
-            parentKeys.addAll(otherTopLevelFile.getNamesMap().keySet());
-          }
-        }
-        if (parent == null) continue;
-      }
-      Set<String> keys = new THashSet<String>(file.getNamesMap().keySet());
-      keys.removeAll(parentKeys);
-      for (String inconsistentKey : keys) {
-        IProperty property = file.findPropertyByKey(inconsistentKey);
-        assert property != null;
-        String message = InspectionsBundle.message("inconsistent.bundle.property.error", inconsistentKey, parent.getName());
-        ProblemDescriptor descriptor = manager.createProblemDescriptor(property.getPsiElement(), message, false, LocalQuickFix.EMPTY_ARRAY,
-                                                                       ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
-        processor.addProblemElement(refManager.getReference(file.getContainingFile()), descriptor);
-      }
-    }
-  }
-
-  private static void checkMissingTranslations(final BidirectionalMap<PropertiesFile, PropertiesFile> parents,
-                                               final List<PropertiesFile> files,
-                                               final Map<PropertiesFile, Set<String>> keysUpToParent,
-                                               final InspectionManager manager,
-                                               RefManager refManager,
-                                               ProblemDescriptionsProcessor processor) {
-    for (PropertiesFile file : files) {
-      PropertiesFile parent = parents.get(file);
-      if (parent == null) continue;
-      List<PropertiesFile> children = parents.getKeysByValue(file);
-      boolean isLeaf = children == null || children.isEmpty();
-      if (!isLeaf) continue;
-      Set<String> keys = file.getNamesMap().keySet();
-      Set<String> parentKeys = new THashSet<String>(keysUpToParent.get(parent));
-      if (parent.getLocale().getLanguage().equals(file.getLocale().getLanguage())) {
-        // properties can be left untranslated in the dialect files
-        keys = new THashSet<String>(keys);
-        keys.addAll(parent.getNamesMap().keySet());
-        parent = parents.get(parent);
-        if (parent == null) continue;
-        parentKeys = new THashSet<String>(keysUpToParent.get(parent));
-      }
-      parentKeys.removeAll(keys);
-      for (String untranslatedKey : parentKeys) {
-        IProperty untranslatedProperty = null;
-        PropertiesFile untranslatedFile = parent;
-        while (untranslatedFile != null) {
-          untranslatedProperty = untranslatedFile.findPropertyByKey(untranslatedKey);
-          if (untranslatedProperty != null) break;
-          untranslatedFile = parents.get(untranslatedFile);
-        }
-        assert untranslatedProperty != null;
-        String message = InspectionsBundle.message("inconsistent.bundle.untranslated.property.error", untranslatedKey, file.getName());
-        ProblemDescriptor descriptor = manager.createProblemDescriptor(untranslatedProperty.getPsiElement(), message, false, LocalQuickFix.EMPTY_ARRAY,
-                                                                       ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
-        processor.addProblemElement(refManager.getReference(untranslatedFile.getContainingFile()), descriptor);
-      }
-    }
-  }
-}
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nUtil.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nUtil.java
index 45cd174d..0d705dc 100644
--- a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nUtil.java
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/JavaI18nUtil.java
@@ -312,30 +312,46 @@
   }
 
   /**
-   * Returns number of different parameters in i18n message. For example, for string
+   * Returns number of different message format parameters in property value
+   *
    * <i>Class {0} info: Class {0} extends class {1} and implements interface {2}</i>
    * number of parameters is 3.
    *
+   * @param propertyValue
+   * @return number of parameters from single property or 0 for wrong format
+   */
+  public static int getPropertyValuePlaceholdersCount(final @NotNull String propertyValue) {
+    try {
+      return new MessageFormat(propertyValue).getFormatsByArgumentIndex().length;
+    } catch (final IllegalArgumentException e) {
+      return 0;
+    }
+  }
+
+  /**
+   * Returns number of different parameters in i18n message. For example, for string
+   *
+   * <i>Class {0} info: Class {0} extends class {1} and implements interface {2}</i> in one translation of property
+   * <i>Class {0} info: Class {0} extends class {1} </i> in other translation of property
+   *
+   * number of parameters is 3.
+   *
    * @param expression i18n literal
    * @return number of parameters
    */
-  public static int getPropertyValueParamsMaxCount(final PsiLiteralExpression expression) {
+  public static int getPropertyValueParamsMaxCount(final @NotNull PsiLiteralExpression expression) {
     int maxCount = -1;
     for (PsiReference reference : expression.getReferences()) {
       if (reference instanceof PsiPolyVariantReference) {
         for (ResolveResult result : ((PsiPolyVariantReference)reference).multiResolve(false)) {
           if (result.isValidResult() && result.getElement() instanceof IProperty) {
-            String value = ((IProperty)result.getElement()).getValue();
-            MessageFormat format;
             try {
-              format = new MessageFormat(value);
-            }
-            catch (Exception e) {
-              continue; // ignore syntax error
-            }
-            try {
-              int count = format.getFormatsByArgumentIndex().length;
-              maxCount = Math.max(maxCount, count);
+              final IProperty property = (IProperty)result.getElement();
+              final String propertyValue = property.getValue();
+              if (propertyValue == null) {
+                continue;
+              }
+              maxCount = Math.max(maxCount, getPropertyValuePlaceholdersCount(propertyValue));
             }
             catch (IllegalArgumentException ignored) {
             }
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/DuplicatedPropertiesInspectionProvider.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/DuplicatedPropertiesInspectionProvider.java
new file mode 100644
index 0000000..64c9f38
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/DuplicatedPropertiesInspectionProvider.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.reference.RefManager;
+import com.intellij.lang.properties.IProperty;
+import com.intellij.lang.properties.RemovePropertyLocalFix;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.openapi.util.Comparing;
+import com.intellij.util.containers.BidirectionalMap;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public class DuplicatedPropertiesInspectionProvider implements InconsistentResourceBundleInspectionProvider {
+  @NotNull
+  @Override
+  public String getName() {
+    return "REPORT_DUPLICATED_PROPERTIES";
+  }
+
+  @NotNull
+  @Override
+  public String getPresentableName() {
+    return InspectionsBundle.message("inconsistent.bundle.report.duplicate.properties.values");
+  }
+
+  @Override
+  public void check(BidirectionalMap<PropertiesFile, PropertiesFile> parents,
+                    List<PropertiesFile> files,
+                    Map<PropertiesFile, Set<String>> keysUpToParent,
+                    Map<PropertiesFile, Map<String, String>> propertiesFilesNamesMaps,
+                    InspectionManager manager,
+                    RefManager refManager,
+                    ProblemDescriptionsProcessor processor) {
+    for (PropertiesFile file : files) {
+      PropertiesFile parent = parents.get(file);
+      if (parent == null) continue;
+      Set<String> parentKeys = keysUpToParent.get(parent);
+      Set<String> overriddenKeys = new THashSet<String>(propertiesFilesNamesMaps.get(file).keySet());
+      overriddenKeys.retainAll(parentKeys);
+      for (String overriddenKey : overriddenKeys) {
+        IProperty property = file.findPropertyByKey(overriddenKey);
+        assert property != null;
+        while (parent != null) {
+          IProperty parentProperty = parent.findPropertyByKey(overriddenKey);
+          if (parentProperty != null && Comparing.strEqual(property.getValue(), parentProperty.getValue())) {
+            String message = InspectionsBundle.message("inconsistent.bundle.property.inherited.with.the.same.value", parent.getName());
+            ProblemDescriptor descriptor = manager.createProblemDescriptor(property.getPsiElement(), message,
+                                                                           RemovePropertyLocalFix.INSTANCE,
+                                                                           ProblemHighlightType.GENERIC_ERROR_OR_WARNING, false);
+            processor.addProblemElement(refManager.getReference(file.getContainingFile()), descriptor);
+          }
+          parent = parents.get(parent);
+        }
+      }
+    }
+  }
+}
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentPropertiesEndsInspectionProvider.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentPropertiesEndsInspectionProvider.java
new file mode 100644
index 0000000..ff1e8b6
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentPropertiesEndsInspectionProvider.java
@@ -0,0 +1,104 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.reference.RefManager;
+import com.intellij.lang.properties.IProperty;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.psi.PsiElement;
+import com.intellij.util.containers.BidirectionalMap;
+import com.intellij.util.containers.ContainerUtil;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public class InconsistentPropertiesEndsInspectionProvider implements InconsistentResourceBundleInspectionProvider {
+  private static final Set<Character> PROPERTY_VALUE_END_CHECK_SYMBOLS = ContainerUtil.newTroveSet('!', '?', '.', ':', ';');
+
+  @NotNull
+  @Override
+  public String getName() {
+    return "REPORT_INCONSISTENT_PROPERTIES_ENDS";
+  }
+
+  @NotNull
+  @Override
+  public String getPresentableName() {
+    return InspectionsBundle.message("inconsistent.bundle.report.inconsistent.properties.ends");
+  }
+
+  @Override
+  public void check(BidirectionalMap<PropertiesFile, PropertiesFile> parents,
+                    List<PropertiesFile> files,
+                    Map<PropertiesFile, Set<String>> keysUpToParent,
+                    Map<PropertiesFile, Map<String, String>> propertiesFilesNamesMaps,
+                    InspectionManager manager,
+                    RefManager refManager,
+                    ProblemDescriptionsProcessor processor) {
+    for (PropertiesFile file : files) {
+      final Set<String> filePropertyKeys = new THashSet<String>(propertiesFilesNamesMaps.get(file).keySet());
+      PropertiesFile parent = parents.get(file);
+      while (parent != null) {
+        final Collection<String> commonKeys = ContainerUtil.intersection(propertiesFilesNamesMaps.get(parent).keySet(), filePropertyKeys);
+        for (final String commonKey : commonKeys) {
+          final IProperty property = file.findPropertyByKey(commonKey);
+          assert property != null;
+          final String propertyValue = property.getValue();
+          if (propertyValue == null) {
+            continue;
+          }
+          final char lastChar = propertyValue.charAt(propertyValue.length() - 1);
+          if (!PROPERTY_VALUE_END_CHECK_SYMBOLS.contains(lastChar)) {
+            continue;
+          }
+          final String parentPropertyValue = propertiesFilesNamesMaps.get(parent).get(commonKey);
+          if (parentPropertyValue == null) {
+            continue;
+          }
+          final char parentLastChar = parentPropertyValue.charAt(parentPropertyValue.length() - 1);
+          if (lastChar != parentLastChar) {
+            final String message;
+            if (PROPERTY_VALUE_END_CHECK_SYMBOLS.contains(parentLastChar)) {
+              message = InspectionsBundle
+                .message("inconsistent.bundle.property.inconsistent.end.parent.end.from.check.symbols", lastChar, parentLastChar,
+                         parent.getName());
+            } else {
+              message = InspectionsBundle.message("inconsistent.bundle.property.inconsistent.end", lastChar);
+            }
+            final PsiElement propertyPsiElement = property.getPsiElement();
+            processor.addProblemElement(refManager.getReference(file.getContainingFile()),
+                                        manager.createProblemDescriptor(propertyPsiElement,
+                                                                        message,
+                                                                        true,
+                                                                        LocalQuickFix.EMPTY_ARRAY,
+                                                                        ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
+            );
+          }
+        }
+        filePropertyKeys.removeAll(commonKeys);
+        parent = parents.get(parent);
+      }
+    }
+  }
+}
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentResourceBundleInspection.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentResourceBundleInspection.java
new file mode 100644
index 0000000..48f4b05
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentResourceBundleInspection.java
@@ -0,0 +1,206 @@
+/*
+ * Copyright 2000-2009 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeHighlighting.HighlightDisplayLevel;
+import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
+import com.intellij.codeInspection.ui.OptionAccessor;
+import com.intellij.lang.properties.*;
+import com.intellij.lang.properties.ResourceBundle;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.openapi.util.*;
+import com.intellij.psi.PsiFile;
+import com.intellij.util.containers.BidirectionalMap;
+import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.containers.FactoryMap;
+import gnu.trove.THashMap;
+import gnu.trove.THashSet;
+import org.jdom.Element;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.annotations.TestOnly;
+
+import javax.swing.*;
+import java.util.*;
+
+/**
+ * @author max
+ */
+public class InconsistentResourceBundleInspection extends GlobalSimpleInspectionTool {
+  private static final Key<Set<ResourceBundle>> VISITED_BUNDLES_KEY = Key.create("VISITED_BUNDLES_KEY");
+
+  private final InconsistentResourceBundleInspectionProvider[] myInspectionProviders;
+  private final Map<String, Boolean> mySettings = new LinkedHashMap<String, Boolean>();
+
+  public InconsistentResourceBundleInspection() {
+    myInspectionProviders = new InconsistentResourceBundleInspectionProvider[] {
+      new PropertiesKeysConsistencyInspectionProvider(),
+      new DuplicatedPropertiesInspectionProvider(),
+      new MissingTranslationsInspectionProvider(),
+      new PropertiesPlaceholdersInspectionProvider(),
+      new InconsistentPropertiesEndsInspectionProvider(),
+    };
+  }
+
+  @Override
+  @NotNull
+  public String getGroupDisplayName() {
+    return PropertiesBundle.message("properties.files.inspection.group.display.name");
+  }
+
+  @Override
+  @NotNull
+  public String getDisplayName() {
+    return InspectionsBundle.message("inconsistent.resource.bundle.display.name");
+  }
+
+  @Override
+  @NotNull
+  public String getShortName() {
+    return "InconsistentResourceBundle";
+  }
+
+  @Override
+  @NotNull
+  public HighlightDisplayLevel getDefaultLevel() {
+    return HighlightDisplayLevel.ERROR;
+  }
+
+  @Override
+  @Nullable
+  public JComponent createOptionsPanel() {
+    final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(new OptionAccessor() {
+      @Override
+      public boolean getOption(String optionName) {
+        return isProviderEnabled(optionName);
+      }
+
+      @Override
+      public void setOption(String optionName, boolean optionValue) {
+        if (optionValue) {
+          mySettings.remove(optionName);
+        }
+        else {
+          mySettings.put(optionName, false);
+        }
+      }
+    });
+    for (final InconsistentResourceBundleInspectionProvider provider : myInspectionProviders) {
+      panel.addCheckbox(provider.getPresentableName(), provider.getName());
+    }
+    return panel;
+  }
+
+  @Override
+  public void writeSettings(final @NotNull Element node) throws WriteExternalException {
+    for (final Map.Entry<String, Boolean> e : mySettings.entrySet()) {
+      JDOMExternalizerUtil.writeField(node, e.getKey(), Boolean.toString(e.getValue()));
+    }
+  }
+
+  @Override
+  public void readSettings(final @NotNull Element node) throws InvalidDataException {
+    mySettings.clear();
+    for (final Object o : node.getChildren()) {
+      if (o instanceof Element) {
+        final Element e = (Element) o;
+        final String name = e.getAttributeValue("name");
+        final boolean value = Boolean.parseBoolean(e.getAttributeValue("value"));
+        mySettings.put(name, value);
+      }
+    }
+  }
+
+  @Override
+  public void inspectionStarted(@NotNull InspectionManager manager,
+                                @NotNull GlobalInspectionContext globalContext,
+                                @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
+    globalContext.putUserData(VISITED_BUNDLES_KEY, new THashSet<ResourceBundle>());
+  }
+
+  @Override
+  public void checkFile(@NotNull PsiFile file,
+                        @NotNull InspectionManager manager,
+                        @NotNull ProblemsHolder problemsHolder,
+                        @NotNull GlobalInspectionContext globalContext,
+                        @NotNull ProblemDescriptionsProcessor problemDescriptionsProcessor) {
+    Set<ResourceBundle> visitedBundles = globalContext.getUserData(VISITED_BUNDLES_KEY);
+    if (!(file instanceof PropertiesFile)) return;
+    final PropertiesFile propertiesFile = (PropertiesFile)file;
+    ResourceBundle resourceBundle = propertiesFile.getResourceBundle();
+    assert visitedBundles != null;
+    if (!visitedBundles.add(resourceBundle)) return;
+    List<PropertiesFile> files = resourceBundle.getPropertiesFiles(manager.getProject());
+    if (files.size() < 2) return;
+    BidirectionalMap<PropertiesFile, PropertiesFile> parents = new BidirectionalMap<PropertiesFile, PropertiesFile>();
+    for (PropertiesFile f : files) {
+      PropertiesFile parent = PropertiesUtil.getParent(f, files);
+      if (parent != null) {
+        parents.put(f, parent);
+      }
+    }
+    final FactoryMap<PropertiesFile, Map<String,String>> propertiesFilesNamesMaps = new FactoryMap<PropertiesFile, Map<String, String>>() {
+      @Nullable
+      @Override
+      protected Map<String, String> create(PropertiesFile key) {
+        return key.getNamesMap();
+      }
+    };
+    Map<PropertiesFile, Set<String>> keysUpToParent = new THashMap<PropertiesFile, Set<String>>();
+    for (PropertiesFile f : files) {
+      Set<String> keys = new THashSet<String>(propertiesFilesNamesMaps.get(f).keySet());
+      PropertiesFile parent = parents.get(f);
+      while (parent != null) {
+        keys.addAll(propertiesFilesNamesMaps.get(parent).keySet());
+        parent = parents.get(parent);
+      }
+      keysUpToParent.put(f, keys);
+    }
+    for (final InconsistentResourceBundleInspectionProvider provider : myInspectionProviders) {
+      if (isProviderEnabled(provider.getName())) {
+        provider.check(parents, files, keysUpToParent, propertiesFilesNamesMaps, manager, globalContext.getRefManager(),
+                       problemDescriptionsProcessor);
+      }
+    }
+  }
+
+  private boolean isProviderEnabled(final String providerName) {
+    return ContainerUtil.getOrElse(mySettings, providerName, true);
+  }
+
+  @TestOnly
+  public void enableProviders(final Class<? extends InconsistentResourceBundleInspectionProvider>... providerClasses) {
+    Set<Class<? extends InconsistentResourceBundleInspectionProvider>> providersToEnable = ContainerUtil.newHashSet(providerClasses);
+    for (InconsistentResourceBundleInspectionProvider inspectionProvider : myInspectionProviders) {
+      if (providersToEnable.contains(inspectionProvider.getClass())) {
+        mySettings.put(inspectionProvider.getName(), true);
+      }
+    }
+  }
+
+  @TestOnly
+  public void disableAllProviders() {
+    for (InconsistentResourceBundleInspectionProvider inspectionProvider : myInspectionProviders) {
+      mySettings.put(inspectionProvider.getName(), false);
+    }
+  }
+
+  @TestOnly
+  public void clearSettings() {
+    mySettings.clear();
+  }
+}
\ No newline at end of file
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentResourceBundleInspectionProvider.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentResourceBundleInspectionProvider.java
new file mode 100644
index 0000000..0389c71
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/InconsistentResourceBundleInspectionProvider.java
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeInspection.InspectionManager;
+import com.intellij.codeInspection.ProblemDescriptionsProcessor;
+import com.intellij.codeInspection.reference.RefManager;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.util.containers.BidirectionalMap;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public interface InconsistentResourceBundleInspectionProvider {
+  @NotNull
+  String getName();
+
+  @NotNull
+  String getPresentableName();
+
+  void check(BidirectionalMap<PropertiesFile, PropertiesFile> parents,
+             List<PropertiesFile> files,
+             Map<PropertiesFile, Set<String>> keysUpToParent,
+             Map<PropertiesFile, Map<String, String>> propertiesFilesNamesMaps,
+             InspectionManager manager,
+             RefManager refManager,
+             ProblemDescriptionsProcessor processor);
+}
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/MissingTranslationsInspectionProvider.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/MissingTranslationsInspectionProvider.java
new file mode 100644
index 0000000..297f447
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/MissingTranslationsInspectionProvider.java
@@ -0,0 +1,87 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.reference.RefManager;
+import com.intellij.lang.properties.IProperty;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.util.containers.BidirectionalMap;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public class MissingTranslationsInspectionProvider implements InconsistentResourceBundleInspectionProvider {
+  @NotNull
+  @Override
+  public String getName() {
+    return "REPORT_MISSING_TRANSLATIONS";
+  }
+
+  @NotNull
+  @Override
+  public String getPresentableName() {
+    return InspectionsBundle.message("inconsistent.bundle.report.missing.translations");
+  }
+
+  @Override
+  public void check(BidirectionalMap<PropertiesFile, PropertiesFile> parents,
+                    List<PropertiesFile> files,
+                    Map<PropertiesFile, Set<String>> keysUpToParent,
+                    Map<PropertiesFile, Map<String, String>> propertiesFilesNamesMaps,
+                    InspectionManager manager,
+                    RefManager refManager,
+                    ProblemDescriptionsProcessor processor) {
+    for (PropertiesFile file : files) {
+      PropertiesFile parent = parents.get(file);
+      if (parent == null) continue;
+      List<PropertiesFile> children = parents.getKeysByValue(file);
+      boolean isLeaf = children == null || children.isEmpty();
+      if (!isLeaf) continue;
+      Set<String> keys = propertiesFilesNamesMaps.get(file).keySet();
+      Set<String> parentKeys = new THashSet<String>(keysUpToParent.get(parent));
+      if (parent.getLocale().getLanguage().equals(file.getLocale().getLanguage())) {
+        // properties can be left untranslated in the dialect files
+        keys = new THashSet<String>(keys);
+        keys.addAll(propertiesFilesNamesMaps.get(parent).keySet());
+        parent = parents.get(parent);
+        if (parent == null) continue;
+        parentKeys = new THashSet<String>(keysUpToParent.get(parent));
+      }
+      parentKeys.removeAll(keys);
+      for (String untranslatedKey : parentKeys) {
+        IProperty untranslatedProperty = null;
+        PropertiesFile untranslatedFile = parent;
+        while (untranslatedFile != null) {
+          untranslatedProperty = untranslatedFile.findPropertyByKey(untranslatedKey);
+          if (untranslatedProperty != null) break;
+          untranslatedFile = parents.get(untranslatedFile);
+        }
+        assert untranslatedProperty != null;
+        String message = InspectionsBundle.message("inconsistent.bundle.untranslated.property.error", untranslatedKey, file.getName());
+        ProblemDescriptor descriptor = manager.createProblemDescriptor(untranslatedProperty.getPsiElement(), message, false, LocalQuickFix.EMPTY_ARRAY,
+                                                                       ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
+        processor.addProblemElement(refManager.getReference(untranslatedFile.getContainingFile()), descriptor);
+      }
+    }
+  }
+}
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/PropertiesKeysConsistencyInspectionProvider.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/PropertiesKeysConsistencyInspectionProvider.java
new file mode 100644
index 0000000..c6d47b1
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/PropertiesKeysConsistencyInspectionProvider.java
@@ -0,0 +1,79 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.reference.RefManager;
+import com.intellij.lang.properties.IProperty;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.util.containers.BidirectionalMap;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public class PropertiesKeysConsistencyInspectionProvider implements InconsistentResourceBundleInspectionProvider {
+  @NotNull
+  @Override
+  public String getName() {
+    return "REPORT_INCONSISTENT_PROPERTIES";
+  }
+
+  @NotNull
+  @Override
+  public String getPresentableName() {
+    return InspectionsBundle.message("inconsistent.bundle.report.inconsistent.properties");
+  }
+
+  @Override
+  public void check(BidirectionalMap<PropertiesFile, PropertiesFile> parents,
+                    List<PropertiesFile> files,
+                    Map<PropertiesFile, Set<String>> keysUpToParent,
+                    Map<PropertiesFile, Map<String, String>> propertiesFilesNamesMaps,
+                    InspectionManager manager,
+                    RefManager refManager,
+                    ProblemDescriptionsProcessor processor) {
+    for (PropertiesFile file : files) {
+      PropertiesFile parent = parents.get(file);
+      Set<String> parentKeys = keysUpToParent.get(parent);
+      if (parent == null) {
+        parentKeys = new THashSet<String>();
+        for (PropertiesFile otherTopLevelFile : files) {
+          if (otherTopLevelFile != file && parents.get(otherTopLevelFile) == null) {
+            parent = otherTopLevelFile;
+            parentKeys.addAll(propertiesFilesNamesMaps.get(otherTopLevelFile).keySet());
+          }
+        }
+        if (parent == null) continue;
+      }
+      Set<String> keys = new THashSet<String>(propertiesFilesNamesMaps.get(file).keySet());
+      keys.removeAll(parentKeys);
+      for (String inconsistentKey : keys) {
+        IProperty property = file.findPropertyByKey(inconsistentKey);
+        assert property != null;
+        String message = InspectionsBundle.message("inconsistent.bundle.property.error", inconsistentKey, parent.getName());
+        ProblemDescriptor descriptor = manager.createProblemDescriptor(property.getPsiElement(), message, false, LocalQuickFix.EMPTY_ARRAY,
+                                                                       ProblemHighlightType.GENERIC_ERROR_OR_WARNING);
+        processor.addProblemElement(refManager.getReference(file.getContainingFile()), descriptor);
+      }
+    }
+  }
+}
diff --git a/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/PropertiesPlaceholdersInspectionProvider.java b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/PropertiesPlaceholdersInspectionProvider.java
new file mode 100644
index 0000000..bfbae39
--- /dev/null
+++ b/plugins/java-i18n/src/com/intellij/codeInspection/i18n/inconsistentResourceBundle/PropertiesPlaceholdersInspectionProvider.java
@@ -0,0 +1,92 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n.inconsistentResourceBundle;
+
+import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.i18n.JavaI18nUtil;
+import com.intellij.codeInspection.reference.RefManager;
+import com.intellij.lang.properties.IProperty;
+import com.intellij.lang.properties.psi.PropertiesFile;
+import com.intellij.psi.PsiElement;
+import com.intellij.util.containers.BidirectionalMap;
+import com.intellij.util.containers.ContainerUtil;
+import gnu.trove.THashSet;
+import org.jetbrains.annotations.NotNull;
+
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public class PropertiesPlaceholdersInspectionProvider implements InconsistentResourceBundleInspectionProvider {
+  @NotNull
+  @Override
+  public String getName() {
+    return "REPORT_INCONSISTENT_PROPERTIES_PLACEHOLDERS";
+  }
+
+  @NotNull
+  @Override
+  public String getPresentableName() {
+    return InspectionsBundle.message("inconsistent.bundle.report.inconsistent.properties.placeholders");
+  }
+
+  @Override
+  public void check(BidirectionalMap<PropertiesFile, PropertiesFile> parents,
+                    List<PropertiesFile> files,
+                    Map<PropertiesFile, Set<String>> keysUpToParent,
+                    Map<PropertiesFile, Map<String, String>> propertiesFilesNamesMaps,
+                    InspectionManager manager,
+                    RefManager refManager,
+                    ProblemDescriptionsProcessor processor) {
+    for (PropertiesFile file : files) {
+      final Set<String> filePropertyKeys = new THashSet<String>(propertiesFilesNamesMaps.get(file).keySet());
+      PropertiesFile parent = parents.get(file);
+      while (parent != null) {
+        final Collection<String> commonKeys = ContainerUtil.intersection(propertiesFilesNamesMaps.get(parent).keySet(), filePropertyKeys);
+        for (final String commonKey : commonKeys) {
+          final IProperty property = file.findPropertyByKey(commonKey);
+          assert property != null;
+          final String propertyValue = property.getValue();
+          if (propertyValue == null) {
+            continue;
+          }
+          final String parentPropertyValue = propertiesFilesNamesMaps.get(parent).get(commonKey);
+          if (parentPropertyValue == null) {
+            continue;
+          }
+          final int occurrences = JavaI18nUtil.getPropertyValuePlaceholdersCount(propertyValue);
+          final int parentOccurrences = JavaI18nUtil.getPropertyValuePlaceholdersCount(parentPropertyValue);
+          if (occurrences != parentOccurrences) {
+            final String problemDescriptorString =
+              InspectionsBundle.message("inconsistent.bundle.property.inconsistent.placeholders", parentOccurrences, parent.getName());
+            final PsiElement propertyPsiElement = property.getPsiElement();
+            processor.addProblemElement(refManager.getReference(file.getContainingFile()),
+                                        manager.createProblemDescriptor(propertyPsiElement, problemDescriptorString, true,
+                                                                        LocalQuickFix.EMPTY_ARRAY,
+                                                                        ProblemHighlightType.GENERIC_ERROR_OR_WARNING)
+            );
+          }
+        }
+        filePropertyKeys.removeAll(commonKeys);
+        parent = parents.get(parent);
+      }
+    }
+  }
+}
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/expected.xml b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/expected.xml
new file mode 100644
index 0000000..cdb0fe5
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/expected.xml
@@ -0,0 +1,23 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<problems>
+  <problem>
+    <file>prop_en.properties</file>
+    <line>2</line>
+    <description>Inconsistent count of placeholders: found 0 in 'prop.properties'</description>
+  </problem>
+  <problem>
+    <file>prop_en_CA.properties</file>
+    <line>1</line>
+    <description>Inconsistent count of placeholders: found 2 in 'prop_en.properties'</description>
+  </problem>
+  <problem>
+    <file>prop_en_CA.properties</file>
+    <line>2</line>
+    <description>Inconsistent count of placeholders: found 1 in 'prop_en.properties'</description>
+  </problem>
+  <problem>
+    <file>prop_en_CA.properties</file>
+    <line>3</line>
+    <description>Inconsistent count of placeholders: found 0 in 'prop.properties'</description>
+  </problem>
+</problems>
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop.properties
new file mode 100644
index 0000000..8241c14
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop.properties
@@ -0,0 +1,5 @@
+key=value{0}{1}
+key1=value1
+key2=value2
+key3=value3
+key4=value4
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop_en.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop_en.properties
new file mode 100644
index 0000000..5cc6ef0
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop_en.properties
@@ -0,0 +1,4 @@
+key=value{0} en {1}
+key1=value1 {0}
+key2=value2
+key3=value3
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop_en_CA.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop_en_CA.properties
new file mode 100644
index 0000000..a4f9361
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentPlaceholders/src/prop_en_CA.properties
@@ -0,0 +1,3 @@
+key=value en CA {0}
+key1=value1
+key4=value{0}
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/expected.xml b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/expected.xml
new file mode 100644
index 0000000..15bef11
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/expected.xml
@@ -0,0 +1,13 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<problems>
+  <problem>
+    <file>prop_en_CA.properties</file>
+    <line>2</line>
+    <description>Inconsistent property value end ':' but found ';' in 'prop_en.properties'</description>
+  </problem>
+  <problem>
+    <file>prop_en_CA.properties</file>
+    <line>4</line>
+    <description>Inconsistent property value end ';' but found ':' in 'prop.properties'</description>
+  </problem>
+</problems>
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop.properties
new file mode 100644
index 0000000..23a0fe28
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop.properties
@@ -0,0 +1,4 @@
+key1=value
+key2=value;
+key3=value.
+key4=value:
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop_en.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop_en.properties
new file mode 100644
index 0000000..f761395
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop_en.properties
@@ -0,0 +1,3 @@
+key1=value123
+key2=value123;
+key3=value123.
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop_en_CA.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop_en_CA.properties
new file mode 100644
index 0000000..52e3815
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/InconsistentValuesEnds/src/prop_en_CA.properties
@@ -0,0 +1,4 @@
+key1=value
+key2=value:
+key3=value.
+key4=value;
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/expected.xml b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/expected.xml
new file mode 100644
index 0000000..3b7f28f
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/expected.xml
@@ -0,0 +1,40 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+  ~ Copyright 2000-2014 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.
+  -->
+<problems>
+  <problem>
+    <file>Bu.properties</file>
+    <line>1</line>
+    <description>Untranslated property 'a'. Should be overridden in the 'Bu_fr_SSS.properties'.</description>
+  </problem>
+
+  <problem>
+    <file>Bu_fr_SSS.properties</file>
+    <line>1</line>
+    <description>Inconsistent property 'c'. Must be defined in the parent file 'Bu_fr.properties'.</description>
+  </problem>
+
+  <problem>
+    <file>Bu_fr.properties</file>
+    <line>1</line>
+    <description>Inconsistent property 'b'. Must be defined in the parent file 'Bu.properties'.</description>
+  </problem>
+  <problem>
+    <file>Bu_fr_SSS.properties</file>
+    <line>2</line>
+    <description>Property inherited from the 'Bu.properties' file with the same value</description>
+  </problem>
+</problems>
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu.properties
new file mode 100644
index 0000000..ccbe550
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu.properties
@@ -0,0 +1,2 @@
+a=1
+zzz=zzz
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu_fr.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu_fr.properties
new file mode 100644
index 0000000..e82df74
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu_fr.properties
@@ -0,0 +1 @@
+b=2
diff --git a/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu_fr_SSS.properties b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu_fr_SSS.properties
new file mode 100644
index 0000000..1c6b89c
--- /dev/null
+++ b/plugins/java-i18n/testData/inspections/inconsistentResourceBundle/Simple/src/Bu_fr_SSS.properties
@@ -0,0 +1,2 @@
+c=3
+zzz=zzz
\ No newline at end of file
diff --git a/plugins/java-i18n/testData/inspection/ClassName.java b/plugins/java-i18n/testData/inspections/spellchecker/ClassName.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/ClassName.java
rename to plugins/java-i18n/testData/inspections/spellchecker/ClassName.java
diff --git a/plugins/java-i18n/testData/inspection/CorrectJava.java b/plugins/java-i18n/testData/inspections/spellchecker/CorrectJava.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/CorrectJava.java
rename to plugins/java-i18n/testData/inspections/spellchecker/CorrectJava.java
diff --git a/plugins/java-i18n/testData/inspection/DocComment.java b/plugins/java-i18n/testData/inspections/spellchecker/DocComment.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/DocComment.java
rename to plugins/java-i18n/testData/inspections/spellchecker/DocComment.java
diff --git a/plugins/java-i18n/testData/inspection/FieldName.java b/plugins/java-i18n/testData/inspections/spellchecker/FieldName.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/FieldName.java
rename to plugins/java-i18n/testData/inspections/spellchecker/FieldName.java
diff --git a/plugins/java-i18n/testData/inspection/Japanese.java b/plugins/java-i18n/testData/inspections/spellchecker/Japanese.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/Japanese.java
rename to plugins/java-i18n/testData/inspections/spellchecker/Japanese.java
diff --git a/plugins/java-i18n/testData/inspection/LocalVariableName.java b/plugins/java-i18n/testData/inspections/spellchecker/LocalVariableName.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/LocalVariableName.java
rename to plugins/java-i18n/testData/inspections/spellchecker/LocalVariableName.java
diff --git a/plugins/java-i18n/testData/inspection/MethodName.java b/plugins/java-i18n/testData/inspections/spellchecker/MethodName.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/MethodName.java
rename to plugins/java-i18n/testData/inspections/spellchecker/MethodName.java
diff --git a/plugins/java-i18n/testData/inspection/StringLiteral.java b/plugins/java-i18n/testData/inspections/spellchecker/StringLiteral.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/StringLiteral.java
rename to plugins/java-i18n/testData/inspections/spellchecker/StringLiteral.java
diff --git a/plugins/java-i18n/testData/inspection/StringLiteralEscaping.java b/plugins/java-i18n/testData/inspections/spellchecker/StringLiteralEscaping.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/StringLiteralEscaping.java
rename to plugins/java-i18n/testData/inspections/spellchecker/StringLiteralEscaping.java
diff --git a/plugins/java-i18n/testData/inspection/Suppressions.java b/plugins/java-i18n/testData/inspections/spellchecker/Suppressions.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/Suppressions.java
rename to plugins/java-i18n/testData/inspections/spellchecker/Suppressions.java
diff --git a/plugins/java-i18n/testData/inspection/TypoInJava.java b/plugins/java-i18n/testData/inspections/spellchecker/TypoInJava.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/TypoInJava.java
rename to plugins/java-i18n/testData/inspections/spellchecker/TypoInJava.java
diff --git a/plugins/java-i18n/testData/inspection/VarArg.java b/plugins/java-i18n/testData/inspections/spellchecker/VarArg.java
similarity index 100%
rename from plugins/java-i18n/testData/inspection/VarArg.java
rename to plugins/java-i18n/testData/inspections/spellchecker/VarArg.java
diff --git a/plugins/java-i18n/testSrc/com/intellij/codeInspection/i18n/InconsistentResourceBundleInspectionTest.java b/plugins/java-i18n/testSrc/com/intellij/codeInspection/i18n/InconsistentResourceBundleInspectionTest.java
new file mode 100644
index 0000000..06135af
--- /dev/null
+++ b/plugins/java-i18n/testSrc/com/intellij/codeInspection/i18n/InconsistentResourceBundleInspectionTest.java
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2000-2014 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.codeInspection.i18n;
+
+import com.intellij.codeInspection.ex.GlobalInspectionToolWrapper;
+import com.intellij.codeInspection.i18n.inconsistentResourceBundle.*;
+import com.intellij.openapi.application.PluginPathManager;
+import com.intellij.testFramework.fixtures.JavaCodeInsightFixtureTestCase;
+
+/**
+ * @author Dmitry Batkovich
+ */
+@SuppressWarnings("unchecked")
+public class InconsistentResourceBundleInspectionTest extends JavaCodeInsightFixtureTestCase {
+  private final InconsistentResourceBundleInspection myInspection = new InconsistentResourceBundleInspection();
+
+  @Override
+  protected String getTestDataPath() {
+    return PluginPathManager.getPluginHomePath("java-i18n") + "/testData/inspections/inconsistentResourceBundle";
+  }
+
+  @Override
+  protected void setUp() throws Exception {
+    super.setUp();
+    myInspection.disableAllProviders();
+  }
+
+  @Override
+  protected void tearDown() throws Exception {
+    myInspection.clearSettings();
+    super.tearDown();
+  }
+
+  public void testInconsistentPlaceholders() {
+    myInspection.enableProviders(PropertiesPlaceholdersInspectionProvider.class);
+    doTest();
+  }
+
+  public void testInconsistentValuesEnds() {
+    myInspection.enableProviders(InconsistentPropertiesEndsInspectionProvider.class);
+    doTest();
+  }
+
+  public void testSimple() {
+    myInspection.enableProviders(PropertiesKeysConsistencyInspectionProvider.class,
+                                 MissingTranslationsInspectionProvider.class,
+                                 DuplicatedPropertiesInspectionProvider.class);
+    doTest();
+  }
+
+  private void doTest() {
+    myFixture.testInspection(getTestName(false), new GlobalInspectionToolWrapper(myInspection));
+  }
+}
diff --git a/plugins/java-i18n/testSrc/com/intellij/spellchecker/inspection/JavaSpellcheckerInspectionTest.java b/plugins/java-i18n/testSrc/com/intellij/spellchecker/inspection/JavaSpellcheckerInspectionTest.java
index 0a247e3..a3af106 100644
--- a/plugins/java-i18n/testSrc/com/intellij/spellchecker/inspection/JavaSpellcheckerInspectionTest.java
+++ b/plugins/java-i18n/testSrc/com/intellij/spellchecker/inspection/JavaSpellcheckerInspectionTest.java
@@ -21,7 +21,7 @@
 public class JavaSpellcheckerInspectionTest extends LightCodeInsightFixtureTestCase {
   @Override
   protected String getBasePath() {
-    return PluginPathManager.getPluginHomePathRelative("java-i18n") + "/testData/inspection";
+    return PluginPathManager.getPluginHomePathRelative("java-i18n") + "/testData/inspections/spellchecker";
   }
 
   public void testCorrectJava() { doTest(); }
diff --git a/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestRunnerUtil.java b/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestRunnerUtil.java
index 565f621..4862015 100644
--- a/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestRunnerUtil.java
+++ b/plugins/junit_rt/src/com/intellij/junit4/JUnit4TestRunnerUtil.java
@@ -123,12 +123,13 @@
           final Class clazz = loadTestClass(suiteClassName.substring(0, index));
           final String methodName = suiteClassName.substring(index + 1);
           final RunWith clazzAnnotation = (RunWith)clazz.getAnnotation(RunWith.class);
+          final Description testMethodDescription = Description.createTestDescription(clazz, methodName);
           if (clazzAnnotation == null) { //do not override external runners
             try {
               final Method method = clazz.getMethod(methodName, null);
               if (method != null && notForked && (method.getAnnotation(Ignore.class) != null || clazz.getAnnotation(Ignore.class) != null)) { //override ignored case only
                 final Request classRequest = createIgnoreIgnoredClassRequest(clazz, true);
-                final Filter ignoredTestFilter = Filter.matchMethodDescription(Description.createTestDescription(clazz, methodName));
+                final Filter ignoredTestFilter = Filter.matchMethodDescription(testMethodDescription);
                 return classRequest.filterWith(new Filter() {
                   public boolean shouldRun(Description description) {
                     return ignoredTestFilter.shouldRun(description);
@@ -151,13 +152,20 @@
           }
           try {
             if (clazz.getMethod("suite", new Class[0]) != null && !methodName.equals("suite")) {
-              return Request.classWithoutSuiteMethod(clazz).filterWith(Description.createTestDescription(clazz, methodName));
+              return Request.classWithoutSuiteMethod(clazz).filterWith(testMethodDescription);
             }
           }
           catch (Throwable e) {
             //ignore
           }
-          final Filter methodFilter = Filter.matchMethodDescription(Description.createTestDescription(clazz, methodName));
+
+          final Filter methodFilter;
+          try {
+            methodFilter = Filter.matchMethodDescription(testMethodDescription);
+          }
+          catch (NoSuchMethodError e) {
+            return Request.method(clazz, methodName);
+          }
           return Request.aClass(clazz).filterWith(new Filter() {
             public boolean shouldRun(Description description) {
               if (description.isTest() && description.getDisplayName().startsWith("warning(junit.framework.TestSuite$")) {
diff --git a/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java b/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java
index 03cd1ca..abc281f 100644
--- a/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java
+++ b/plugins/properties/properties-psi-api/src/com/intellij/lang/properties/PropertiesUtil.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2009 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.openapi.project.Project;
 import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.util.NullableComputable;
+import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiDirectory;
@@ -27,14 +28,17 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.Arrays;
-import java.util.List;
-import java.util.Locale;
+import java.util.*;
+import java.util.regex.MatchResult;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * @author cdr
  */
 public class PropertiesUtil {
+  private final static Pattern LOCALE_PATTERN = Pattern.compile("(_[^\\._]{2}(_[^\\._]+){0,2})\\.[^_]+$");
+  private final static Locale DEFAULT_LOCALE = new Locale("", "", "");
 
 
   public static boolean isPropertyComplete(final Project project, ResourceBundle resourceBundle, String propertyName) {
@@ -47,23 +51,24 @@
 
   @NotNull
   public static String getBaseName(@NotNull VirtualFile virtualFile) {
-    String name = virtualFile.getNameWithoutExtension();
-
-    List<String> parts = StringUtil.split(name, "_");
-    if (parts.size() == 1) return parts.get(0);
-    if (parts.size() == 0) return "";
-
-    String baseName = parts.get(0);
-    for (int i = 1; i< parts.size(); i++) {
-      String part = parts.get(i);
-      if (part.length() == 2) {
-        break;
+    String name = virtualFile.getName();
+    final Matcher matcher = LOCALE_PATTERN.matcher(name);
+    final String baseNameWithExtension;
+    if (matcher.find()) {
+      final MatchResult matchResult = matcher.toMatchResult();
+      final String[] splitted = matchResult.group(1).split("_");
+      if (splitted.length > 1) {
+        baseNameWithExtension = name.substring(0, matchResult.start(1)) + name.substring(matchResult.end(1));
       }
-      baseName += "_";
-      baseName += part;
+      else {
+        baseNameWithExtension = name;
+      }
+    }
+    else {
+      baseNameWithExtension = name;
     }
 
-    return baseName;
+    return FileUtil.getNameWithoutExtension(baseNameWithExtension);
   }
 
   /**
@@ -108,24 +113,20 @@
   }
 
   @NotNull
-  public static Locale getLocale(VirtualFile propertiesFile) {
-    String name = propertiesFile.getNameWithoutExtension();
-    String tail = StringUtil.trimStart(name, getBaseName(propertiesFile));
-    tail = StringUtil.trimStart(tail, "_");
-    String[] parts = tail.split("_");
-    String language = parts.length == 0 ? "" : parts[0];
-    String country = "";
-    String variant = "";
-    if (parts.length >= 2 && parts[1].length() == 2) {
-      country = parts[1];
-      for (int i = 2; i < parts.length; i++) {
-        String part = parts[i];
-        if (variant.length() != 0) variant += "_";
-        variant += part;
+  public static Locale getLocale(final VirtualFile propertiesFile) {
+    String name = propertiesFile.getName();
+    final Matcher matcher = LOCALE_PATTERN.matcher(name);
+    if (matcher.find()) {
+      String rawLocale = matcher.group(1);
+      String[] splittedRawLocale = rawLocale.split("_");
+      if (splittedRawLocale.length > 1 && splittedRawLocale[1].length() == 2) {
+        final String language = splittedRawLocale[1];
+        final String country = splittedRawLocale.length > 2 ? splittedRawLocale[2] : "";
+        final String variant = splittedRawLocale.length > 3 ? splittedRawLocale[3] : "";
+        return new Locale(language, country, variant);
       }
     }
-
-    return new Locale(language,country,variant);
+    return DEFAULT_LOCALE;
   }
 
   @NotNull
diff --git a/plugins/properties/properties-psi-impl/properties-psi-impl.iml b/plugins/properties/properties-psi-impl/properties-psi-impl.iml
index 0722993..1eeaef3 100644
--- a/plugins/properties/properties-psi-impl/properties-psi-impl.iml
+++ b/plugins/properties/properties-psi-impl/properties-psi-impl.iml
@@ -14,6 +14,7 @@
     <orderEntry type="module" module-name="xml-psi-api" />
     <orderEntry type="module" module-name="xml-psi-impl" />
     <orderEntry type="module" module-name="indexing-impl" />
+    <orderEntry type="module" module-name="lang-impl" />
   </component>
 </module>
 
diff --git a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleImpl.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleImpl.java
index 1cd4562..1ac96a9 100644
--- a/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleImpl.java
+++ b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/ResourceBundleImpl.java
@@ -50,7 +50,7 @@
     List<PropertiesFile> result = new SmartList<PropertiesFile>();
     PsiManager psiManager = PsiManager.getInstance(project);
     for (VirtualFile file : children) {
-      if (!file.isValid()) continue;
+      if (!file.isValid() || file.getExtension() == null) continue;
       if (Comparing.strEqual(PropertiesUtil.getBaseName(file), myBaseName)) {
         PropertiesFile propertiesFile = PropertiesImplUtil.getPropertiesFile(psiManager.findFile(file));
         if (propertiesFile != null) {
diff --git a/plugins/properties/src/com/intellij/lang/properties/psi/impl/PropertiesASTFactory.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertiesASTFactory.java
similarity index 100%
rename from plugins/properties/src/com/intellij/lang/properties/psi/impl/PropertiesASTFactory.java
rename to plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertiesASTFactory.java
diff --git a/plugins/properties/src/com/intellij/lang/properties/psi/impl/PropertyValueImpl.java b/plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertyValueImpl.java
similarity index 100%
rename from plugins/properties/src/com/intellij/lang/properties/psi/impl/PropertyValueImpl.java
rename to plugins/properties/properties-psi-impl/src/com/intellij/lang/properties/psi/impl/PropertyValueImpl.java
diff --git a/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesUtilTest.java b/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesUtilTest.java
new file mode 100644
index 0000000..5ebf25d
--- /dev/null
+++ b/plugins/properties/testSrc/com/intellij/lang/properties/PropertiesUtilTest.java
@@ -0,0 +1,75 @@
+/*
+ * Copyright 2000-2014 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.lang.properties;
+
+import com.intellij.openapi.vfs.newvfs.impl.StubVirtualFile;
+import junit.framework.TestCase;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author Dmitry Batkovich
+ */
+public class PropertiesUtilTest extends TestCase {
+
+  public void testBaseNameWithoutLocale() {
+    assertBaseNameEquals("property-file.properties", "property-file");
+  }
+
+  public void testBaseNameWithLocale() {
+    assertBaseNameEquals("property-file_en._fr.asd_ru.properties", "property-file_en._fr.asd");
+  }
+
+  public void testBaseNameWithoutLocaleWithAdditionalExtension() {
+    assertBaseNameEquals("property-file.utf8.properties", "property-file.utf8");
+  }
+
+  public void testBaseNameWithLocaleWithAdditionalExtension() {
+    assertBaseNameEquals("property-file_fr.file_en.utf8.properties", "property-file_fr.file.utf8");
+  }
+
+  public void testBaseNameWithCountryAndVariant() {
+    assertBaseNameEquals("property-file_fr.file_en_GB_UNIX.utf8.properties", "property-file_fr.file.utf8");
+  }
+
+  public void testBaseNameWithCountry() {
+    assertBaseNameEquals("property-file_fr.file_en_GB.utf8.properties", "property-file_fr.file.utf8");
+  }
+
+  public void testBaseName() {
+    assertBaseNameEquals("Base_Properties.utf8.properties", "Base_Properties.utf8");
+  }
+
+  public void test1() {
+    assertBaseNameEquals("Base_Page_fr.utf8.properties", "Base_Page.utf8");
+  }
+  public void test2() {
+    assertBaseNameEquals("Base_Page_en.utf8.properties", "Base_Page.utf8");
+  }
+  public void test3() {
+    assertBaseNameEquals("Base_Page.utf8.properties", "Base_Page.utf8");
+  }
+
+  private static void assertBaseNameEquals(final String propertyFileName, final String expectedBaseName) {
+    final String actualBaseName = PropertiesUtil.getBaseName(new StubVirtualFile() {
+      @NotNull
+      @Override
+      public String getName() {
+        return propertyFileName;
+      }
+    });
+    assertEquals(expectedBaseName, actualBaseName);
+  }
+}
diff --git a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/JiraRepository.java b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/JiraRepository.java
index 35a957c..582400c 100644
--- a/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/JiraRepository.java
+++ b/plugins/tasks/tasks-core/jira/src/com/intellij/tasks/jira/JiraRepository.java
@@ -40,6 +40,7 @@
   public static final String REST_API_PATH = "/rest/api/latest";
 
   private static final boolean LEGACY_API_ONLY = Boolean.getBoolean("tasks.jira.legacy.api.only");
+  private static final boolean BASIC_AUTH_ONLY = Boolean.getBoolean("tasks.jira.basic.auth.only");
   private static final boolean REDISCOVER_API = Boolean.getBoolean("tasks.jira.rediscover.api");
 
   public static final Pattern JIRA_ID_PATTERN = Pattern.compile("\\p{javaUpperCase}+-\\d+");
@@ -56,13 +57,13 @@
    */
   @SuppressWarnings({"UnusedDeclaration"})
   public JiraRepository() {
-    myUseHttpAuthentication = true;
+    setUseHttpAuthentication(true);
   }
 
   public JiraRepository(JiraRepositoryType type) {
     super(type);
     // Use Basic authentication at the beginning of new session and disable then if needed
-    myUseHttpAuthentication = true;
+    setUseHttpAuthentication(true);
   }
 
   private JiraRepository(JiraRepository other) {
@@ -189,19 +190,25 @@
     HttpClient client = getHttpClient();
     // Fix for https://jetbrains.zendesk.com/agent/#/tickets/24566
     // See https://confluence.atlassian.com/display/ONDEMANDKB/Getting+randomly+logged+out+of+OnDemand for details
-    boolean cookieAuthenticated = false;
-    for (Cookie cookie : client.getState().getCookies()) {
-      if (cookie.getName().equals("JSESSIONID") && !cookie.isExpired()) {
-        cookieAuthenticated = true;
-        break;
+    if (BASIC_AUTH_ONLY) {
+      // to override persisted settings
+      setUseHttpAuthentication(true);
+    }
+    else {
+      boolean cookieAuthenticated = false;
+      for (Cookie cookie : client.getState().getCookies()) {
+        if (cookie.getName().equals("JSESSIONID") && !cookie.isExpired()) {
+          cookieAuthenticated = true;
+          break;
+        }
       }
+      // disable subsequent basic authorization attempts if user already was authenticated
+      boolean enableBasicAuthentication = !(isRestApiSupported() && cookieAuthenticated);
+      if (enableBasicAuthentication != isUseHttpAuthentication()) {
+        LOG.info("Basic authentication for subsequent requests was " + (enableBasicAuthentication ? "enabled" : "disabled"));
+      }
+      setUseHttpAuthentication(enableBasicAuthentication);
     }
-    // disable subsequent basic authorization attempts if user already was authenticated
-    boolean enableBasicAuthentication = !(isRestApiSupported() && cookieAuthenticated);
-    if (enableBasicAuthentication != isUseHttpAuthentication()) {
-      LOG.info("Basic authentication for subsequent requests was " + (enableBasicAuthentication ? "enabled" : "disabled"));
-    }
-    setUseHttpAuthentication(enableBasicAuthentication);
 
     int statusCode = client.executeMethod(method);
     LOG.debug("Status code: " + statusCode);
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/TaskBundle.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/TaskBundle.java
index 385e004..f805006 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/TaskBundle.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/TaskBundle.java
@@ -2,6 +2,7 @@
 
 import com.intellij.CommonBundle;
 import com.intellij.reference.SoftReference;
+import org.apache.commons.httpclient.HttpStatus;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.PropertyKey;
@@ -28,6 +29,17 @@
     return CommonBundle.message(getBundle(), key, params);
   }
 
+  @NotNull
+  public static String messageForStatusCode(int statusCode) {
+    if (statusCode == HttpStatus.SC_UNAUTHORIZED) {
+      return message("failure.login");
+    }
+    else if (statusCode == HttpStatus.SC_FORBIDDEN) {
+      return message("failure.permissions");
+    }
+    return message("failure.http.error", statusCode, HttpStatus.getStatusText(statusCode));
+  }
+
   private static ResourceBundle getBundle() {
     ResourceBundle bundle = SoftReference.dereference(ourBundle);
     if (bundle == null) {
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java
index 7927647..cc66448 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/gitlab/GitlabRepository.java
@@ -175,7 +175,7 @@
   public GitlabIssue fetchIssue(int id) throws Exception {
     ensureProjectsDiscovered();
     HttpGet request = new HttpGet(getRestApiUrl("issues", id));
-    ResponseHandler<GitlabIssue> handler = new GsonSingleObjectDeserializer<GitlabIssue>(GSON, GitlabIssue.class);
+    ResponseHandler<GitlabIssue> handler = new GsonSingleObjectDeserializer<GitlabIssue>(GSON, GitlabIssue.class, true);
     return getHttpClient().execute(request, handler);
   }
 
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/RequestFailedException.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/RequestFailedException.java
new file mode 100644
index 0000000..893c4b8
--- /dev/null
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/RequestFailedException.java
@@ -0,0 +1,36 @@
+package com.intellij.tasks.impl;
+
+import com.intellij.tasks.TaskBundle;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author Mikhail Golubev
+ */
+public class RequestFailedException extends RuntimeException {
+  @NotNull
+  public static RequestFailedException forStatusCode(int code) {
+    return new RequestFailedException(TaskBundle.messageForStatusCode(code));
+  }
+
+  @NotNull
+  public static RequestFailedException forStatusCode(int code, @NotNull String message) {
+    return new RequestFailedException(TaskBundle.message("failure.http.error", code, message));
+  }
+
+  @NotNull
+  public static RequestFailedException forServerMessage(@NotNull String message) {
+    return new RequestFailedException(TaskBundle.message("failure.server.message", message));
+  }
+
+  public RequestFailedException(String message) {
+    super(message);
+  }
+
+  public RequestFailedException(String message, Throwable cause) {
+    super(message, cause);
+  }
+
+  public RequestFailedException(Throwable cause) {
+    super(cause);
+  }
+}
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java
index 788c0db..2f065a9 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/TaskManagerImpl.java
@@ -791,7 +791,8 @@
       catch (Exception e) {
         String reason = "";
         // Fix to IDEA-111810
-        if (e.getClass() == Exception.class) {
+        //noinspection InstanceofCatchParameter
+        if (e.getClass() == Exception.class || e instanceof RequestFailedException) {
           // probably contains some message meaningful to end-user
           reason = e.getMessage();
         }
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java
index 82ac206..441dabe 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/impl/httpclient/ResponseUtil.java
@@ -7,9 +7,11 @@
 import com.intellij.openapi.util.io.StreamUtil;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.CharsetToolkit;
+import com.intellij.tasks.impl.RequestFailedException;
 import com.intellij.tasks.impl.TaskUtil;
 import org.apache.commons.httpclient.HeaderElement;
 import org.apache.commons.httpclient.HttpMethod;
+import org.apache.commons.httpclient.HttpStatus;
 import org.apache.commons.httpclient.NameValuePair;
 import org.apache.http.Header;
 import org.apache.http.HttpResponse;
@@ -92,17 +94,27 @@
   public static final class GsonSingleObjectDeserializer<T> implements ResponseHandler<T> {
     private final Gson myGson;
     private final Class<T> myClass;
-    public GsonSingleObjectDeserializer(Gson gson, Class<T> cls) {
+    private final boolean myIgnoreNotFound;
+
+    public GsonSingleObjectDeserializer(@NotNull Gson gson, @NotNull Class<T> cls) {
+      this(gson, cls, false);
+    }
+
+    public GsonSingleObjectDeserializer(@NotNull Gson gson, @NotNull Class<T> cls, boolean ignoreNotFound) {
       myGson = gson;
       myClass = cls;
+      myIgnoreNotFound = ignoreNotFound;
     }
 
     @Override
     public T handleResponse(HttpResponse response) throws IOException {
       int statusCode = response.getStatusLine().getStatusCode();
       LOG.info("Status code: " + statusCode);
-      if (statusCode >= 400 && statusCode < 500) {
-        return null;
+      if (!isSuccessful(statusCode)) {
+        if (statusCode == HttpStatus.SC_NOT_FOUND && myIgnoreNotFound) {
+          return null;
+        }
+        throw RequestFailedException.forStatusCode(statusCode);
       }
       try {
         if (LOG.isDebugEnabled()) {
@@ -122,16 +134,26 @@
   public static final class GsonMultipleObjectsDeserializer<T> implements ResponseHandler<List<T>> {
     private final Gson myGson;
     private final TypeToken<List<T>> myTypeToken;
-    public GsonMultipleObjectsDeserializer(Gson gson, TypeToken<List<T>> token) {
+    private final boolean myIgnoreNotFound;
+
+    public GsonMultipleObjectsDeserializer(Gson gson, TypeToken<List<T>> typeToken) {
+      this(gson, typeToken, false);
+    }
+
+    public GsonMultipleObjectsDeserializer(@NotNull Gson gson, @NotNull TypeToken<List<T>> token, boolean ignoreNotFound) {
       myGson = gson;
       myTypeToken = token;
+      myIgnoreNotFound = ignoreNotFound;
     }
 
     @Override
     public List<T> handleResponse(HttpResponse response) throws IOException {
       int statusCode = response.getStatusLine().getStatusCode();
-      if (statusCode >= 400 && statusCode < 500) {
-        return Collections.emptyList();
+      if (!isSuccessful(statusCode)) {
+        if (statusCode == HttpStatus.SC_NOT_FOUND && myIgnoreNotFound) {
+          return Collections.emptyList();
+        }
+        throw RequestFailedException.forStatusCode(statusCode);
       }
       LOG.info("Status code: " + statusCode);
       try {
@@ -148,4 +170,16 @@
       }
     }
   }
+
+  public static boolean isSuccessful(int statusCode) {
+    return statusCode / 100 == 2;
+  }
+
+  public static boolean isClientError(int statusCode) {
+    return statusCode / 100 == 4;
+  }
+
+  public static boolean isServerError(int statusCode) {
+    return statusCode / 100 == 5;
+  }
 }
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java
index e06bb48..5dadcdf 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/redmine/RedmineRepository.java
@@ -5,7 +5,7 @@
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.tasks.Task;
-import com.intellij.tasks.TaskBundle;
+import com.intellij.tasks.impl.RequestFailedException;
 import com.intellij.tasks.impl.gson.GsonUtil;
 import com.intellij.tasks.impl.httpclient.NewBaseRepositoryImpl;
 import com.intellij.tasks.redmine.model.RedmineIssue;
@@ -102,17 +102,21 @@
 
   @Override
   public void testConnection() throws Exception {
-    // Strangely, but Redmine doesn't return 401 or 403 error if client sent wrong credentials and instead
+    // Strangely, Redmine doesn't return 401 or 403 error codes, if client sent wrong credentials, and instead
     // merely returns empty array of issues with status code of 200. This means that we should attempt to fetch
-    // something more specific than issues to test connection and configuration.
-    HttpResponse response = getHttpClient().execute(new HttpGet(getRestApiUrl("users", "current.json")));
+    // something more specific than issues to test proper configuration, e.g. current user information at
+    // /users/current.json. Unfortunately this endpoint may be unavailable on some old servers (see IDEA-122845)
+    // and in this case we have to come back to requesting issues in this case to test anything at all.
+    HttpClient client = getHttpClient();
+    HttpResponse response = client.execute(new HttpGet(getRestApiUrl("users", "current.json")));
     //TaskUtil.prettyFormatResponseToLog(LOG, response);
     int code = response.getStatusLine().getStatusCode();
+    if (code == HttpStatus.SC_NOT_FOUND) {
+      getIssues("", 0, 1, true);
+      return;
+    }
     if (code != HttpStatus.SC_OK) {
-      if (code == HttpStatus.SC_UNAUTHORIZED) {
-        throw new Exception(TaskBundle.message("failure.login"));
-      }
-      throw new Exception(TaskBundle.message("failure.http.error", code, response.getStatusLine().getReasonPhrase()));
+      throw RequestFailedException.forStatusCode(code);
     }
   }
 
@@ -148,7 +152,8 @@
     }
     HttpClient client = getHttpClient();
     HttpGet method = new HttpGet(builder.toString());
-    return client.execute(method, new GsonSingleObjectDeserializer<IssuesWrapper>(GSON, IssuesWrapper.class)).getIssues();
+    IssuesWrapper wrapper = client.execute(method, new GsonSingleObjectDeserializer<IssuesWrapper>(GSON, IssuesWrapper.class));
+    return wrapper == null ? Collections.<RedmineIssue>emptyList() : wrapper.getIssues();
   }
 
   public List<RedmineProject> fetchProjects() throws Exception {
@@ -168,7 +173,7 @@
   public Task findTask(@NotNull String id) throws Exception {
     ensureProjectsDiscovered();
     HttpGet method = new HttpGet(getRestApiUrl("issues", id + ".json"));
-    IssueWrapper wrapper = getHttpClient().execute(method, new GsonSingleObjectDeserializer<IssueWrapper>(GSON, IssueWrapper.class));
+    IssueWrapper wrapper = getHttpClient().execute(method, new GsonSingleObjectDeserializer<IssueWrapper>(GSON, IssueWrapper.class, true));
     if (wrapper == null) {
       return null;
     }
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java b/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java
index 6361ac2..2d0f3a9 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/actions/CommonEditActionsProvider.java
@@ -268,7 +268,9 @@
         }
       }
     }
-    catch (Throwable ignored) { }
+    catch (Throwable ignored) {
+      // ignored
+    }
 
     return null;
   }
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/actions/DesignerActionPanel.java b/plugins/ui-designer-core/src/com/intellij/designer/actions/DesignerActionPanel.java
index 526c2b6..626dfb8 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/actions/DesignerActionPanel.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/actions/DesignerActionPanel.java
@@ -15,17 +15,21 @@
  */
 package com.intellij.designer.actions;
 
+import com.intellij.designer.DesignerToolWindowManager;
 import com.intellij.designer.designSurface.ComponentSelectionListener;
 import com.intellij.designer.designSurface.DesignerEditorPanel;
 import com.intellij.designer.designSurface.EditableArea;
 import com.intellij.designer.model.RadComponent;
 import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.wm.IdeFocusManager;
 import com.intellij.ui.IdeBorderFactory;
 import com.intellij.ui.SideBorder;
+import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
+import java.awt.*;
 import java.awt.event.KeyEvent;
 import java.util.List;
 
@@ -105,7 +109,8 @@
                                                                   KeyEvent.KEY_PRESSED, 0, 0,
                                                                   KeyEvent.VK_ESCAPE,
                                                                   (char)KeyEvent.VK_ESCAPE),
-                                                     myDesigner.getSurfaceArea());
+                                                     myDesigner.getSurfaceArea()
+        );
       }
     };
     selectParent.registerCustomShortcutSet(KeyEvent.VK_ESCAPE, 0, null);
@@ -236,7 +241,11 @@
         PlatformDataKeys.CUT_PROVIDER.is(dataId) ||
         PlatformDataKeys.COPY_PROVIDER.is(dataId) ||
         PlatformDataKeys.PASTE_PROVIDER.is(dataId)) {
-      return myCommonEditActionsProvider;
+      JTable table = DesignerToolWindowManager.getInstance(myDesigner).getPropertyTable();
+      Component focusOwner = IdeFocusManager.getInstance(myDesigner.getProject()).getFocusOwner();
+      if (!UIUtil.isAncestor(table, focusOwner)) {
+        return myCommonEditActionsProvider;
+      }
     }
     return null;
   }
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTracker.java b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTracker.java
index a8b35b1..da15902 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTracker.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/designSurface/tools/SelectionTracker.java
@@ -72,6 +72,14 @@
   @Override
   protected void handleButtonUp(int button) {
     if (myState == STATE_DRAG) {
+      // Control clicking on a Mac is used to simulate right clicks: do not treat this as
+      // a selection reset (since it makes it impossible to pull up the context menu with
+      // a multi-selection: the right click action causes the selection to be replaced
+      // with the single item under the mouse)
+      if (SystemInfo.isMac && myInputEvent != null && myInputEvent.isControlDown()) {
+        return;
+      }
+
       performSelection();
       myState = STATE_NONE;
     }
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/PropertyTablePanel.java b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/PropertyTablePanel.java
index 6a98c01..a44a3439 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/PropertyTablePanel.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/PropertyTablePanel.java
@@ -57,7 +57,12 @@
   private final JLabel myTitleLabel;
 
   public PropertyTablePanel(final Project project) {
-    myPropertyTable = new RadPropertyTable(project);
+    myPropertyTable = new RadPropertyTable(project) {
+      @Override
+      protected void updateEditActions() {
+        updateActions();
+      }
+    };
 
     setLayout(new GridBagLayout());
 
@@ -67,7 +72,8 @@
     myTitleLabel.setFont(UIUtil.getLabelFont(UIUtil.FontSize.SMALL));
     add(myTitleLabel,
         new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.HORIZONTAL,
-                               new Insets(2, 5, 2, 10), 0, 0));
+                               new Insets(2, 5, 2, 10), 0, 0)
+    );
 
     ActionManager actionManager = ActionManager.getInstance();
     DefaultActionGroup actionGroup = new DefaultActionGroup();
@@ -87,12 +93,14 @@
     myTabPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
     add(myTabPanel,
         new GridBagConstraints(gridX++, 0, 1, 1, 1, 0, GridBagConstraints.LINE_START, GridBagConstraints.NONE,
-                               new Insets(2, 0, 2, 0), 0, 0));
+                               new Insets(2, 0, 2, 0), 0, 0)
+    );
 
     myActionPanel = new JPanel(new FlowLayout(FlowLayout.CENTER, 5, 0));
     add(myActionPanel,
         new GridBagConstraints(gridX++, 0, 1, 1, 0, 0, GridBagConstraints.CENTER, GridBagConstraints.NONE,
-                               new Insets(2, 0, 2, 2), 0, 0));
+                               new Insets(2, 0, 2, 2), 0, 0)
+    );
 
     myActions = actionGroup.getChildren(null);
     for (AnAction action : myActions) {
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 0fe7d64..3ce8a72 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
@@ -21,12 +21,16 @@
 import com.intellij.designer.designSurface.DesignerEditorPanel;
 import com.intellij.designer.designSurface.EditableArea;
 import com.intellij.designer.model.*;
+import com.intellij.ide.CopyProvider;
 import com.intellij.lang.annotation.HighlightSeverity;
+import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.actionSystem.DataProvider;
 import com.intellij.openapi.actionSystem.PlatformDataKeys;
 import com.intellij.openapi.editor.colors.TextAttributesKey;
+import com.intellij.openapi.ide.CopyPasteManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.util.ThrowableRunnable;
+import com.intellij.util.ui.TextTransferable;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -37,10 +41,13 @@
 import javax.swing.event.TableModelEvent;
 import javax.swing.event.TableModelListener;
 import java.awt.*;
+import java.awt.datatransfer.Transferable;
 import java.util.Collections;
 import java.util.List;
 
 public class RadPropertyTable extends PropertyTable implements DataProvider, ComponentSelectionListener {
+  private final MyCopyProvider myCopyProvider = new MyCopyProvider();
+
   private final Project myProject;
 
   private EditableArea myArea;
@@ -91,8 +98,13 @@
 
   @Override
   public Object getData(@NonNls String dataId) {
-    if (PlatformDataKeys.FILE_EDITOR.is(dataId) && myDesigner != null) {
-      return myDesigner.getEditor();
+    if (myDesigner != null) {
+      if (PlatformDataKeys.FILE_EDITOR.is(dataId)) {
+        return myDesigner.getEditor();
+      }
+      if (PlatformDataKeys.COPY_PROVIDER.is(dataId) && !isEditing()) {
+        return myCopyProvider;
+      }
     }
     return null;
   }
@@ -185,4 +197,38 @@
   protected PropertyContext getPropertyContext() {
     return myDesigner;
   }
-}
+
+  private class MyCopyProvider implements CopyProvider {
+
+    @Override
+    public void performCopy(@NotNull DataContext dataContext) {
+      try {
+        Property property = getSelectionProperty();
+        Object value = getValue(property);
+        Transferable transferable;
+
+        if (value == null) {
+          transferable = new TextTransferable("");
+        }
+        else {
+          transferable = property.doCopy(myContainers.get(0), value);
+        }
+
+        CopyPasteManager.getInstance().setContents(transferable);
+      }
+      catch (Throwable e) {
+        myDesigner.showError("Copy property error", e);
+      }
+    }
+
+    @Override
+    public boolean isCopyEnabled(@NotNull DataContext dataContext) {
+      return getSelectionProperty() != null;
+    }
+
+    @Override
+    public boolean isCopyVisible(@NotNull DataContext dataContext) {
+      return true;
+    }
+  }
+}
\ No newline at end of file
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/RestoreDefault.java b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/RestoreDefault.java
index fa4527a..0d44f09 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/RestoreDefault.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/RestoreDefault.java
@@ -52,7 +52,7 @@
   private static void setEnabled(RadPropertyTable table, Presentation presentation) {
     try {
       Property property = table.getSelectionProperty();
-      presentation.setEnabled(property != null && !table.isDefault(property));
+      presentation.setEnabled(property != null && !table.isEditing() && !table.isDefault(property));
     }
     catch (Exception e) {
       presentation.setEnabled(false);
diff --git a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java
index 53dfcb9..459d18a 100644
--- a/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java
+++ b/plugins/ui-designer-core/src/com/intellij/designer/propertyTable/actions/ShowJavadoc.java
@@ -66,6 +66,7 @@
   private static void setEnabled(RadPropertyTable table, AnActionEvent e, Presentation presentation) {
     Property property = table.getSelectionProperty();
     presentation.setEnabled(property != null &&
+                            !table.isEditing() &&
                             (property.getJavadocElement() != null || !StringUtil.isEmpty(property.getJavadocText())) &&
                             (e == null || e.getProject() != null));
   }
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java b/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java
index 21e72aa..4d01bae 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/make/FormSourceCodeGenerator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2013 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -776,8 +776,9 @@
     if (!borderNone || borderTitle != null) {
       startMethodCall(variable, "setBorder");
 
-
-      startStaticMethodCall(BorderFactory.class, "createTitledBorder");
+      if (borderTitle != null) {
+        startStaticMethodCall(BorderFactory.class, "createTitledBorder");
+      }
 
       if (!borderNone) {
         startStaticMethodCall(BorderFactory.class, borderFactoryMethodName);
@@ -801,26 +802,26 @@
         push((String) null);
       }
 
-      push(borderTitle);
-
-      if (isCustomBorder(container)) {
-        push(container.getBorderTitleJustification(), ourTitleJustificationMap);
-        push(container.getBorderTitlePosition(), ourTitlePositionMap);
-        if (container.getBorderTitleFont() != null || container.getBorderTitleColor() != null) {
-          if (container.getBorderTitleFont() == null) {
-            push((String) null);
-          }
-          else {
-            pushFont(variable, container.getBorderTitleFont(), "getFont");
-          }
-          if (container.getBorderTitleColor() != null) {
-            pushColor(container.getBorderTitleColor());
+      if (borderTitle != null) {
+        push(borderTitle);
+        if (isCustomBorder(container)) {
+          push(container.getBorderTitleJustification(), ourTitleJustificationMap);
+          push(container.getBorderTitlePosition(), ourTitlePositionMap);
+          if (container.getBorderTitleFont() != null || container.getBorderTitleColor() != null) {
+            if (container.getBorderTitleFont() == null) {
+              push((String)null);
+            }
+            else {
+              pushFont(variable, container.getBorderTitleFont(), "getFont");
+            }
+            if (container.getBorderTitleColor() != null) {
+              pushColor(container.getBorderTitleColor());
+            }
           }
         }
+        endMethod(); // createTitledBorder
       }
 
-      endMethod(); // createTitledBorder
-
       endMethod(); // setBorder
     }
   }
diff --git a/plugins/ui-designer/testData/TestBorderWithoutTitle.form b/plugins/ui-designer/testData/TestBorderWithoutTitle.form
new file mode 100644
index 0000000..f71d55c
--- /dev/null
+++ b/plugins/ui-designer/testData/TestBorderWithoutTitle.form
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="BindingTest">
+  <grid id="a78aa" binding="myRootComponent" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+    <margin top="0" left="0" bottom="0" right="0"/>
+    <constraints>
+      <xy x="167" y="123" width="36" height="52"/>
+    </constraints>
+    <properties/>
+    <border type="empty"/>
+    <children/>
+  </grid>
+</form>
diff --git a/plugins/ui-designer/testData/TestNoneBorderWithTitle.form b/plugins/ui-designer/testData/TestNoneBorderWithTitle.form
new file mode 100644
index 0000000..8f13946
--- /dev/null
+++ b/plugins/ui-designer/testData/TestNoneBorderWithTitle.form
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="BindingTest">
+  <grid id="a78aa" binding="myRootComponent" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+    <margin top="0" left="0" bottom="0" right="0"/>
+    <constraints>
+      <xy x="167" y="123" width="36" height="52"/>
+    </constraints>
+    <properties/>
+    <border type="none" title="BorderTitle"/>
+    <children/>
+  </grid>
+</form>
diff --git a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle b/plugins/ui-designer/testData/sourceCodeGenerator/borders/BindingTest.java
similarity index 64%
copy from plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
copy to plugins/ui-designer/testData/sourceCodeGenerator/borders/BindingTest.java
index 91140f2..181687d 100644
--- a/plugins/gradle/tooling-extension/src/org/jetbrains/plugins/gradle/tooling/internal/buildSrcInit.gradle
+++ b/plugins/ui-designer/testData/sourceCodeGenerator/borders/BindingTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2014 JetBrains s.r.o.
+ * Copyright 2000-2009 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.
@@ -13,13 +13,15 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
+import javax.swing.*;
 
-allprojects { project ->
-  if(project.name == 'buildSrc') {
-    apply plugin: 'groovy'
-    dependencies {
-      compile gradleApi()
-      compile localGroovy()
-    }
+public class BindingTest {
+  public JComponent myRootComponent;
+  public static JComponent myStaticField;
+  public final JComponent myFinalField = null;
+  public int myIntField;
+  public String myStringField;
+
+  public BindingTest() { 
   }
-}
\ No newline at end of file
+}
diff --git a/plugins/ui-designer/testData/sourceCodeGenerator/borders/BindingTest.java.after b/plugins/ui-designer/testData/sourceCodeGenerator/borders/BindingTest.java.after
new file mode 100644
index 0000000..6f38fcf
--- /dev/null
+++ b/plugins/ui-designer/testData/sourceCodeGenerator/borders/BindingTest.java.after
@@ -0,0 +1,67 @@
+/*
+ * Copyright 2000-2009 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.
+ */
+import javax.swing.*;
+
+public class BindingTest {
+    public JComponent myRootComponent;
+    public static JComponent myStaticField;
+    public final JComponent myFinalField = null;
+    public int myIntField;
+    public String myStringField;
+
+    public BindingTest() {
+    }
+
+    {
+// GUI initializer generated by IntelliJ IDEA GUI Designer
+// >>> IMPORTANT!! <<<
+// DO NOT EDIT OR ADD ANY CODE HERE!
+        $$$setupUI$$$();
+    }
+
+    /**
+     * Method generated by IntelliJ IDEA GUI Designer
+     * >>> IMPORTANT!! <<<
+     * DO NOT edit this method OR call it in your code!
+     *
+     * @noinspection ALL
+     */
+    private void $$$setupUI$$$() {
+        myRootComponent = new JPanel();
+        myRootComponent.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(4, 1, new java.awt.Insets(0, 0, 0, 0), -1, -1));
+        final JPanel panel1 = new JPanel();
+        panel1.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new java.awt.Insets(0, 0, 0, 0), -1, -1));
+        myRootComponent.add(panel1, new com.intellij.uiDesigner.core.GridConstraints(0, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
+        panel1.setBorder(javax.swing.BorderFactory.createEmptyBorder());
+        final com.intellij.uiDesigner.core.Spacer spacer1 = new com.intellij.uiDesigner.core.Spacer();
+        myRootComponent.add(spacer1, new com.intellij.uiDesigner.core.GridConstraints(3, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_VERTICAL, 1, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_WANT_GROW, null, null, null, 0, false));
+        final JPanel panel2 = new JPanel();
+        panel2.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new java.awt.Insets(0, 0, 0, 0), -1, -1));
+        myRootComponent.add(panel2, new com.intellij.uiDesigner.core.GridConstraints(1, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
+        panel2.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createEmptyBorder(), "BorderTitle"));
+        final JPanel panel3 = new JPanel();
+        panel3.setLayout(new com.intellij.uiDesigner.core.GridLayoutManager(1, 1, new java.awt.Insets(0, 0, 0, 0), -1, -1));
+        myRootComponent.add(panel3, new com.intellij.uiDesigner.core.GridConstraints(2, 0, 1, 1, com.intellij.uiDesigner.core.GridConstraints.ANCHOR_CENTER, com.intellij.uiDesigner.core.GridConstraints.FILL_BOTH, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_SHRINK | com.intellij.uiDesigner.core.GridConstraints.SIZEPOLICY_CAN_GROW, null, null, null, 0, false));
+        panel3.setBorder(javax.swing.BorderFactory.createTitledBorder("BorderTitle"));
+    }
+
+    /**
+     * @noinspection ALL
+     */
+    public JComponent $$$getRootComponent$$$() {
+        return myRootComponent;
+    }
+}
diff --git a/plugins/ui-designer/testData/sourceCodeGenerator/borders/Test.form b/plugins/ui-designer/testData/sourceCodeGenerator/borders/Test.form
new file mode 100644
index 0000000..f6fdd48
--- /dev/null
+++ b/plugins/ui-designer/testData/sourceCodeGenerator/borders/Test.form
@@ -0,0 +1,45 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="BindingTest">
+  <grid id="91062" binding="myRootComponent" layout-manager="GridLayoutManager" row-count="4" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+    <margin top="0" left="0" bottom="0" right="0"/>
+    <constraints>
+      <xy x="131" y="90" width="40" height="158"/>
+    </constraints>
+    <properties/>
+    <border type="none"/>
+    <children>
+      <grid id="f7d8a" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+        <margin top="0" left="0" bottom="0" right="0"/>
+        <constraints>
+          <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+        </constraints>
+        <properties/>
+        <border type="empty"/>
+        <children/>
+      </grid>
+      <vspacer id="e260d">
+        <constraints>
+          <grid row="3" column="0" row-span="1" col-span="1" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
+        </constraints>
+      </vspacer>
+      <grid id="45af7" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+        <margin top="0" left="0" bottom="0" right="0"/>
+        <constraints>
+          <grid row="1" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+        </constraints>
+        <properties/>
+        <border type="empty" title="BorderTitle"/>
+        <children/>
+      </grid>
+      <grid id="a14db" layout-manager="GridLayoutManager" row-count="1" column-count="1" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+        <margin top="0" left="0" bottom="0" right="0"/>
+        <constraints>
+          <grid row="2" column="0" row-span="1" col-span="1" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
+        </constraints>
+        <properties/>
+        <border type="none" title="BorderTitle"/>
+        <children/>
+      </grid>
+    </children>
+  </grid>
+</form>
diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java
index a45dfeb..093547b 100644
--- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java
+++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/core/AsmCodeGeneratorTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2014 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.
@@ -37,6 +37,8 @@
 import org.jetbrains.asm4.ClassWriter;
 
 import javax.swing.*;
+import javax.swing.border.Border;
+import javax.swing.border.EmptyBorder;
 import javax.swing.border.EtchedBorder;
 import javax.swing.border.TitledBorder;
 import java.awt.*;
@@ -331,6 +333,19 @@
     assertEquals("BorderTitle", border.getTitle());
     assertTrue(border.getBorder().toString(), border.getBorder() instanceof EtchedBorder);
   }
+  
+  public void testBorderWithoutTitle() throws Exception {
+    JPanel panel = (JPanel) getInstrumentedRootComponent("TestBorderWithoutTitle.form", "BindingTest");
+    Border border = panel.getBorder();
+    assertTrue(border.toString(), border instanceof EmptyBorder);
+  }
+  
+  public void testNoneBorderWithTitle() throws Exception {
+    JPanel panel = (JPanel) getInstrumentedRootComponent("TestNoneBorderWithTitle.form", "BindingTest");
+    assertTrue(panel.getBorder() instanceof TitledBorder);
+    TitledBorder border = (TitledBorder) panel.getBorder();
+    assertEquals("BorderTitle", border.getTitle());
+  }
 
   public void testMnemonic() throws Exception {
     JPanel panel = (JPanel) getInstrumentedRootComponent("TestMnemonics.form", "BindingTest");
diff --git a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java
index 0d212f6..f9bb8e02 100644
--- a/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java
+++ b/plugins/ui-designer/testSrc/com/intellij/uiDesigner/make/FormSourceCodeGeneratorTest.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2014 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,10 +16,8 @@
 
 package com.intellij.uiDesigner.make;
 
-import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.PluginPathManager;
 import com.intellij.openapi.command.CommandProcessor;
-import com.intellij.openapi.projectRoots.impl.JavaSdkImpl;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -58,6 +56,10 @@
   public void testSimple() throws IOException {
     doTest();
   }
+  
+  public void testBorders() throws IOException {
+    doTest();
+  }
 
   public void testCustomCreateComponent() throws IOException {
     doTest();
diff --git a/python/helpers/pycharm/pycharm_run_utils.py b/python/helpers/pycharm/pycharm_run_utils.py
index d905d05..78aada5 100644
--- a/python/helpers/pycharm/pycharm_run_utils.py
+++ b/python/helpers/pycharm/pycharm_run_utils.py
@@ -1,7 +1,9 @@
 __author__ = 'ktisha'
-import os, sys
+import os
+import sys
 import imp
 
+
 PYTHON_VERSION_MAJOR = sys.version_info[0]
 PYTHON_VERSION_MINOR = sys.version_info[1]
 
@@ -26,6 +28,8 @@
   sys.path.append(pycharm_path)
 
 def import_system_module(name):
+  if sys.platform == "cli":    # hack for the ironpython
+      return __import__(name)
   f, filename, desc = imp.find_module(name)
   return imp.load_module('pycharm_' + name, f, filename, desc)
 
diff --git a/python/helpers/pycharm/utrunner.py b/python/helpers/pycharm/utrunner.py
index b2e333b..1f11206 100644
--- a/python/helpers/pycharm/utrunner.py
+++ b/python/helpers/pycharm/utrunner.py
@@ -104,7 +104,7 @@
       a_splitted = a[0].split(";")
       if len(a_splitted) != 1:
         # means we have pattern to match against
-        if a_splitted[0].endswith("/"):
+        if a_splitted[0].endswith(os.path.sep):
           debug("/ from folder " + a_splitted[0] + ". Use pattern: " + a_splitted[1])
           modules = loadModulesFromFolderRec(a_splitted[0], a_splitted[1])
       else:
diff --git a/python/psi-api/src/com/jetbrains/python/FunctionParameter.java b/python/psi-api/src/com/jetbrains/python/FunctionParameter.java
new file mode 100644
index 0000000..bceba9e
--- /dev/null
+++ b/python/psi-api/src/com/jetbrains/python/FunctionParameter.java
@@ -0,0 +1,21 @@
+package com.jetbrains.python;
+
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * This class (possibly enum) represents function parameter
+ *
+ * @author Ilya.Kazakevich
+ */
+public interface FunctionParameter {
+  /**
+   * @return parameter position
+   */
+  int getPosition();
+
+  /**
+   * @return parameter name (if known)
+   */
+  @Nullable
+  String getName();
+}
diff --git a/python/psi-api/src/com/jetbrains/python/psi/PyArgumentList.java b/python/psi-api/src/com/jetbrains/python/psi/PyArgumentList.java
index f89f25f..0a1a9c3 100644
--- a/python/psi-api/src/com/jetbrains/python/psi/PyArgumentList.java
+++ b/python/psi-api/src/com/jetbrains/python/psi/PyArgumentList.java
@@ -16,6 +16,7 @@
 package com.jetbrains.python.psi;
 
 import com.intellij.lang.ASTNode;
+import com.jetbrains.python.FunctionParameter;
 import com.jetbrains.python.psi.resolve.PyResolveContext;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -78,4 +79,13 @@
 
   @Nullable
   ASTNode getClosingParen();
+
+  /**
+   * Searches parameter value and returns it if exists.
+   *
+   * @param parameter param to search
+   * @return function parameter value expression or null if does not exist
+   */
+  @Nullable
+  PyExpression getValueExpressionForParam(@NotNull FunctionParameter parameter);
 }
diff --git a/python/resources/inspectionDescriptions/DjangoIncompatibleInspection.html b/python/resources/inspectionDescriptions/DjangoIncompatibleInspection.html
deleted file mode 100644
index e2f7fc0..0000000
--- a/python/resources/inspectionDescriptions/DjangoIncompatibleInspection.html
+++ /dev/null
@@ -1,8 +0,0 @@
-<html>
-<body>
-<span style="font-family: verdana,serif;">
-Django inspection that checks template code for django version compatibility.
-  Notable example is <code>url</code> tag whose first parameter should be in quotes since Django 1.5
-</span>
-</body>
-</html>
\ No newline at end of file
diff --git a/python/resources/pycharm_core_logo.png b/python/resources/pycharm_core_logo.png
index 4fc68fa..aa19d19 100644
--- a/python/resources/pycharm_core_logo.png
+++ b/python/resources/pycharm_core_logo.png
Binary files differ
diff --git a/python/resources/[email protected] b/python/resources/[email protected]
index 9dfe7d3..97912f54 100644
--- a/python/resources/[email protected]
+++ b/python/resources/[email protected]
Binary files differ
diff --git a/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java b/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java
index 964d5b1..b439a54 100644
--- a/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java
+++ b/python/src/com/jetbrains/python/documentation/PyStructuredDocstringFormatter.java
@@ -15,6 +15,7 @@
  */
 package com.jetbrains.python.documentation;
 
+import com.google.common.collect.Lists;
 import com.intellij.execution.process.ProcessOutput;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.module.Module;
@@ -50,7 +51,11 @@
   @Nullable
   public static List<String> formatDocstring(@NotNull final PsiElement element, @NotNull final String docstring) {
     Module module = ModuleUtilCore.findModuleForPsiElement(element);
-    if (module == null) module = ModuleManager.getInstance(element.getProject()).getModules()[0];
+    if (module == null) {
+      final Module[] modules = ModuleManager.getInstance(element.getProject()).getModules();
+      if (modules.length == 0) return Lists.newArrayList();
+      module = modules[0];
+    }
 
     final PyDocumentationSettings documentationSettings = PyDocumentationSettings.getInstance(module);
     final List<String> result = new ArrayList<String>();
diff --git a/python/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java b/python/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java
index e766bc0..bc46d71 100644
--- a/python/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java
+++ b/python/src/com/jetbrains/python/inspections/PyProtectedMemberInspection.java
@@ -81,7 +81,10 @@
     public void visitPyImportElement(PyImportElement node) {
       final PyStatement statement = node.getContainingImportStatement();
       if (!(statement instanceof PyFromImportStatement)) return;
-      checkReference(node.getImportReferenceExpression(), ((PyFromImportStatement)statement).getImportSource());
+      final PyReferenceExpression importReferenceExpression = node.getImportReferenceExpression();
+      final PyReferenceExpression importSource = ((PyFromImportStatement)statement).getImportSource();
+      if (importReferenceExpression != null && importSource != null)
+        checkReference(importReferenceExpression, importSource);
     }
 
     @Override
@@ -91,7 +94,7 @@
       checkReference(node, qualifier);
     }
 
-    private void checkReference(PyReferenceExpression node, PyExpression qualifier) {
+    private void checkReference(@NotNull final PyReferenceExpression node, @NotNull final PyExpression qualifier) {
       if (myTypeEvalContext.getType(qualifier) instanceof PyNamedTupleType) return;
       final String name = node.getName();
       final List<LocalQuickFix> quickFixes = new ArrayList<LocalQuickFix>();
diff --git a/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java b/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java
index 86add67..3e31733a 100644
--- a/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java
+++ b/python/src/com/jetbrains/python/packaging/PyPackageManagerImpl.java
@@ -879,7 +879,7 @@
   }
 
   private static String quoteIfNeeded(String arg) {
-    return arg.replace(" ", "\\ ").replace("<", "\\<").replace(">", "\\>");
+    return arg.replace("<", "\\<").replace(">", "\\>"); //TODO: move this logic to ParametersListUtil.encode
   }
 
   @NotNull
diff --git a/python/src/com/jetbrains/python/psi/PyUtil.java b/python/src/com/jetbrains/python/psi/PyUtil.java
index 7ea85fb..49a024bc 100644
--- a/python/src/com/jetbrains/python/psi/PyUtil.java
+++ b/python/src/com/jetbrains/python/psi/PyUtil.java
@@ -81,6 +81,7 @@
 import java.io.File;
 import java.io.FileFilter;
 import java.io.IOException;
+import java.lang.reflect.Array;
 import java.util.*;
 import java.util.List;
 
@@ -88,6 +89,9 @@
 import static com.jetbrains.python.psi.PyFunction.Modifier.STATICMETHOD;
 
 public class PyUtil {
+
+  private static final Object[] EMPTY_OBJECTS = new Object[0];
+
   private PyUtil() {
   }
 
diff --git a/python/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java b/python/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java
index 2e6120a..d0c83cc 100644
--- a/python/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java
+++ b/python/src/com/jetbrains/python/psi/impl/PyArgumentListImpl.java
@@ -27,6 +27,7 @@
 import com.jetbrains.python.PyElementTypes;
 import com.jetbrains.python.PyTokenTypes;
 import com.jetbrains.python.PythonDialectsTokenSetProvider;
+import com.jetbrains.python.FunctionParameter;
 import com.jetbrains.python.psi.*;
 import com.jetbrains.python.psi.resolve.PyResolveContext;
 import org.jetbrains.annotations.NotNull;
@@ -203,7 +204,6 @@
       catch (IncorrectOperationException e1) {
         throw new IllegalStateException(e1);
       }
-
     }
     else {
       getNode().addChild(arg.getNode(), par);
@@ -214,7 +214,7 @@
   public ASTNode getClosingParen() {
     ASTNode node = getNode();
     final ASTNode[] children = node.getChildren(TokenSet.create(PyTokenTypes.RPAR));
-    return children.length == 0 ? null : children[children.length-1];
+    return children.length == 0 ? null : children[children.length - 1];
   }
 
   private void addArgumentNode(PyExpression arg, ASTNode beforeThis, boolean commaFirst) {
@@ -256,14 +256,12 @@
         // 1: Nothing, just add
         addArgumentNode(argument, node, true);
         break;
-
       }
       else if (PythonDialectsTokenSetProvider.INSTANCE.getExpressionTokens().contains(type)) {
         // 2: After some argument followed by comma: after comma, add element, add comma
         // 3: After some argument not followed by comma: add comma, add element
         addArgumentNode(argument, node, true);
         break;
-
       }
       else if (type == PyTokenTypes.COMMA) {
         ASTNode next = PyUtil.getNextNonWhitespace(node);
@@ -333,4 +331,23 @@
       return (PsiTreeUtil.getParentOfType(input, PyKeywordArgument.class) == null) && !(input instanceof PyKeywordArgument);
     }
   }
+
+  @Nullable
+  @Override
+  public PyExpression getValueExpressionForParam(@NotNull final FunctionParameter parameter) {
+    final String parameterName = parameter.getName();
+    if (parameterName != null) {
+      final PyKeywordArgument kwarg = getKeywordArgument(parameterName);
+      if (kwarg != null) {
+        return kwarg.getValueExpression();
+      }
+    }
+
+    final PyExpression[] arguments = getArguments();
+    if (arguments.length > parameter.getPosition()) {
+      return arguments[parameter.getPosition()];
+    }
+
+    return null;
+  }
 }
diff --git a/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java b/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java
index 63705b4..c04d1c8 100644
--- a/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java
+++ b/python/src/com/jetbrains/python/psi/impl/PyFromImportStatementImpl.java
@@ -235,11 +235,10 @@
   @NotNull
   @Override
   public List<String> getFullyQualifiedObjectNames() {
-    final PyReferenceExpression source = getImportSource();
-    String prefix = "";
-    if (source != null) {
-      prefix = source.getText() + ".";
-    }
+    final QualifiedName source = getImportSourceQName();
+
+    final String prefix = (source != null) ? (source.join(".") + '.') : "";
+
     final List<String> unqualifiedNames = PyImportStatementImpl.getImportElementNames(getImportElements());
 
     final List<String> result = new ArrayList<String>(unqualifiedNames.size());
diff --git a/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java b/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java
index 9236e4e..0a9d63a 100644
--- a/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java
+++ b/python/src/com/jetbrains/python/sdk/CreateVirtualEnvDialog.java
@@ -272,16 +272,18 @@
         FileChooser.chooseFiles(descriptor, myProject, suggestedDir, new FileChooser.FileChooserConsumer() {
           @Override
           public void consume(List<VirtualFile> selectedFiles) {
-            final String path = selectedFiles.get(0).getPath();
+            String path = selectedFiles.get(0).getPath();
             if (sdkType.isValidSdkHome(path)) {
+              path = FileUtil.toSystemDependentName(path);
               Sdk newSdk = null;
               for (Sdk sdk : allSdks) {
                 if (path.equals(sdk.getHomePath())) {
                   newSdk = sdk;
                 }
               }
-              if (newSdk == null)
+              if (newSdk == null) {
                 newSdk = new PyDetectedSdk(path);
+              }
               consumer.consume(newSdk);
             }
           }
@@ -366,6 +368,7 @@
   private void updateSdkList(final List<Sdk> allSdks, @Nullable Sdk initialSelection) {
     mySdkCombo.setRenderer(new PySdkListCellRenderer());
     mySdkCombo.setModel(new CollectionComboBoxModel(allSdks, initialSelection));
+    checkValid();
   }
 
   @Override
diff --git a/python/src/com/jetbrains/python/sdk/PythonSdkDetailsStep.java b/python/src/com/jetbrains/python/sdk/PythonSdkDetailsStep.java
index 354549d..7a6b2db 100644
--- a/python/src/com/jetbrains/python/sdk/PythonSdkDetailsStep.java
+++ b/python/src/com/jetbrains/python/sdk/PythonSdkDetailsStep.java
@@ -30,9 +30,12 @@
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.ui.popup.*;
 import com.intellij.openapi.ui.popup.util.BaseListPopupStep;
+import com.intellij.openapi.util.Disposer;
 import com.intellij.util.NullableConsumer;
+import com.intellij.util.ui.EmptyIcon;
 import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
 import com.jetbrains.python.sdk.flavors.PythonSdkFlavor;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
@@ -62,13 +65,17 @@
 
     final ListPopupStep sdkHomesStep = new PythonSdkDetailsStep(project, moreDialog, ownerComponent, existingSdks, callback);
     final ListPopup popup = JBPopupFactory.getInstance().createListPopup(sdkHomesStep);
+    Dimension size = new JLabel(VIRTUALENV, EmptyIcon.ICON_16, SwingConstants.LEFT).getMinimumSize();
+    final int height = size.height * 5 + 5;
+    popup.setSize(new Dimension(size.width, height));
+    popup.setMinimumSize(new Dimension(size.width, height));
     popup.showInScreenCoordinates(ownerComponent, popupPoint);
   }
 
-  public PythonSdkDetailsStep(Project project,
-                              DialogWrapper moreDialog, Component ownerComponent,
-                              Sdk[] existingSdks,
-                              NullableConsumer<Sdk> callback) {
+  public PythonSdkDetailsStep(@Nullable final Project project,
+                              @Nullable final DialogWrapper moreDialog, @NotNull final Component ownerComponent,
+                              @NotNull final Sdk[] existingSdks,
+                              @NotNull final NullableConsumer<Sdk> callback) {
     super(null, getAvailableOptions(moreDialog != null));
     myProject = project;
     myMore = moreDialog;
@@ -187,6 +194,12 @@
   }
 
   @Override
+  public void canceled() {
+    if (getFinalRunnable() == null)
+      Disposer.dispose(myMore.getDisposable());
+  }
+
+  @Override
   public PopupStep onChosen(final String selectedValue, boolean finalChoice) {
     return doFinalStep(new Runnable() {
       public void run() {
diff --git a/python/src/com/jetbrains/python/testing/nosetest/PythonNoseTestConfigurationProducer.java b/python/src/com/jetbrains/python/testing/nosetest/PythonNoseTestConfigurationProducer.java
index b7dc704..ddbd906 100644
--- a/python/src/com/jetbrains/python/testing/nosetest/PythonNoseTestConfigurationProducer.java
+++ b/python/src/com/jetbrains/python/testing/nosetest/PythonNoseTestConfigurationProducer.java
@@ -41,8 +41,7 @@
       module = modules[0];
     }
     final Sdk sdk = PythonSdkType.findPythonSdk(module);
-    return (TestRunnerService.getInstance(module).getProjectConfiguration().equals(
-      PythonTestConfigurationsModel.PYTHONS_NOSETEST_NAME) && sdk != null);
+    return (PythonTestConfigurationsModel.PYTHONS_NOSETEST_NAME.equals(TestRunnerService.getInstance(module).getProjectConfiguration()) && sdk != null);
   }
 
   @Override
diff --git a/python/testData/inspections/RedundantParenthesesBoolean.py b/python/testData/inspections/RedundantParenthesesBoolean.py
index c43341a..2eb3a31 100644
--- a/python/testData/inspections/RedundantParenthesesBoolean.py
+++ b/python/testData/inspections/RedundantParenthesesBoolean.py
@@ -1,5 +1,6 @@
 settings = ('foreground',)
 old_value = None
+new_value = None
 
-if ('foreground' in settings) and <weak_warning descr="Remove redundant parentheses"><caret>((old_value is None) or (old_value > 5))</weak_warning>:
+if ('foreground' in settings) and <weak_warning descr="Remove redundant parentheses"><caret>((old_value) or (new_value))</weak_warning>:
   pass
diff --git a/python/testData/inspections/RedundantParenthesesBoolean_after.py b/python/testData/inspections/RedundantParenthesesBoolean_after.py
index 6c71cf3..f65c17a 100644
--- a/python/testData/inspections/RedundantParenthesesBoolean_after.py
+++ b/python/testData/inspections/RedundantParenthesesBoolean_after.py
@@ -1,5 +1,6 @@
 settings = ('foreground',)
 old_value = None
+new_value = None
 
-if ('foreground' in settings) and (old_value is None or old_value > 5):
+if ('foreground' in settings) and (old_value or new_value):
   pass
diff --git a/resources-en/src/inspectionDescriptions/InconsistentResourceBundle.html b/resources-en/src/inspectionDescriptions/InconsistentResourceBundle.html
index d8d5003..edd04cd 100644
--- a/resources-en/src/inspectionDescriptions/InconsistentResourceBundle.html
+++ b/resources-en/src/inspectionDescriptions/InconsistentResourceBundle.html
@@ -22,8 +22,8 @@
       option controls invalid resource bundle structure inspection.<br>
       It reports properties contained in inherited properties file that are missing in parent (or in sibling if there is no parent).<br>
       E.g. having this resource bundle:<br>
-      <b>messages_fr.properties</b>: <font color="#000080"><b>abc=xxx</b></font><br>
       <b>messages.properties</b>: empty<br>
+      <b>messages_fr.properties</b>: <font color="#000080"><b>abc=xxx</b></font><br>
 
       Property <font color="#000080"><b>abc</b></font> translation here is not available for any language except French,
       and, thus, will be reported as missing in the (default) properties file <b>messages.properties</b>.
@@ -36,11 +36,50 @@
     </ul>
   option checks for properties which are copy-pasted into several properties files verbatim.<br>
   E.g. in this resource bundle:<br>
-  <b>messages_fr.properties</b>: <font color="#000080"><b>abc=xxx</b></font><br>
   <b>messages.properties</b>: <font color="#000080"><b>abc=xxx</b></font><br>
+  <b>messages_fr.properties</b>: <font color="#000080"><b>abc=xxx</b></font><br>
 
   Property <font color="#000080"><b>abc</b></font> will be reported as unnecessarily inherited in the file <b>messages_fr.properties</b>.
   <br>
+
+<ul>
+    <li>
+
+      <b>Report properties overridden with different placeholders</b>
+    </li>
+    </ul>
+  option checks for properties which are overridden for placeholders consistency.<br>
+  E.g. in this resource bundle:<br>
+  <b>messages.properties</b>:<br>
+    <font color="#000080"><b>qwe={0}xxx{1}</b></font><br>
+    <font color="#000080"><b>abc={0}yyy{1}</b></font><br>
+  <b>messages_fr.properties</b>:<br>
+    <font color="#000080"><b>qwe={0}xxx{0}xxx{1}</b></font><br>
+    <font color="#000080"><b>abc={0}yyy</b></font><br>
+
+
+  Property <font color="#000080"><b>abc</b></font> will be reported as property contains message format placeholders
+  with value not corresponding to <b>messages.properties</b>.
+  <br>
+
+<ul>
+    <li>
+
+      <b>Report properties overridden with different values endings</b>
+    </li>
+    </ul>
+  option checks for properties which are overridden for endings consistency.<br>
+  E.g. in this resource bundle:<br>
+  <b>messages.properties</b>:<br>
+    <font color="#000080"><b>abc=xxxzzz</b></font><br>
+  <b>messages_fr.properties</b>:<br>
+    <font color="#000080"><b>abc=xxx;</b></font><br>
+
+
+  Property <font color="#000080"><b>abc</b></font> will be reported as property contains special signs
+  (<b>'!'</b>, <b>'?'</b>, <b>'.'</b>, <b>':'</b> or <b>';'</b>) at the end of value but
+  value in <b>messages.properties</b> doesn't.
+  <br>
 </font>
 
 </body>
diff --git a/resources-en/src/inspectionDescriptions/WrongPackageStatement.html b/resources-en/src/inspectionDescriptions/WrongPackageStatement.html
index 01fb18e..78ff052 100644
--- a/resources-en/src/inspectionDescriptions/WrongPackageStatement.html
+++ b/resources-en/src/inspectionDescriptions/WrongPackageStatement.html
@@ -1,5 +1,6 @@
 <html>
 <body>
-<font face="verdana" size="-1">Detects package statements that do not correspond to the project directory structure.</font>
+<font face="verdana" size="-1">Detects <b>package</b> statements that do not correspond to the project directory structure
+  and reports classes without <b>package</b> statements.</font>
 </body>
 </html>
\ No newline at end of file
diff --git a/resources/src/META-INF/PostfixTemplates.xml b/resources/src/META-INF/PostfixTemplates.xml
index af5d57e..2fe4cd38 100644
--- a/resources/src/META-INF/PostfixTemplates.xml
+++ b/resources/src/META-INF/PostfixTemplates.xml
@@ -1,40 +1,23 @@
 <idea-plugin version="2">
   <extensionPoints>
-    <extensionPoint name="postfixTemplate" interface="com.intellij.codeInsight.template.postfix.templates.PostfixTemplate"/>
+    <extensionPoint name="codeInsight.template.postfixTemplateProvider"
+                    beanClass="com.intellij.lang.LanguageExtensionPoint">
+      <with attribute="implementationClass" implements="com.intellij.codeInsight.template.postfix.templates.PostfixTemplateProvider"/>
+    </extensionPoint>
   </extensionPoints>
 
+
   <extensions defaultExtensionNs="com.intellij">
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ElseStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.IntroduceVariablePostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.NotNullCheckPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.IsNullCheckPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.NotExpressionPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ForeachPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.WhileStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.CastExpressionPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.IfStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ForAscendingPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ForDescendingPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.IntroduceFieldPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ParenthesizedExpressionPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ReturnStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.SwitchStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.ThrowExceptionPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.AssertStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.SynchronizedStatementPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.InstanceofExpressionPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.SoutPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.FormatPostfixTemplate"/>
-    <postfixTemplate implementation="com.intellij.codeInsight.template.postfix.templates.TryStatementPostfixTemplate"/>
+    <codeInsight.template.postfixTemplateProvider language="JAVA" implementationClass="com.intellij.codeInsight.template.postfix.templates.JavaPostfixTemplateProvider"/>
   </extensions>
 
   <extensions defaultExtensionNs="com.intellij">
     <applicationService id="postfixCompletionSettings" serviceImplementation="com.intellij.codeInsight.template.postfix.settings.PostfixTemplatesSettings"/>
     <customLiveTemplate implementation="com.intellij.codeInsight.template.postfix.templates.PostfixLiveTemplate"/>
-    
+
     <completion.contributor language="JAVA" implementationClass="com.intellij.codeInsight.template.postfix.completion.PostfixTemplateCompletionContributor"/>
     <lookup.actionProvider implementation="com.intellij.codeInsight.template.postfix.completion.PostfixTemplateLookupActionProvider"/>
-    
+
     <editorOptionsProvider id="editing.postfixCompletion" instance="com.intellij.codeInsight.template.postfix.settings.PostfixTemplatesConfigurable"/>
   </extensions>
 </idea-plugin>
\ No newline at end of file
diff --git a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
index c0ef08b..5b519a6 100644
--- a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
+++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
@@ -28,8 +28,9 @@
 import com.intellij.codeInsight.template.emmet.tokens.TemplateToken;
 import com.intellij.codeInsight.template.emmet.tokens.TextToken;
 import com.intellij.codeInsight.template.emmet.tokens.ZenCodingToken;
-import com.intellij.codeInsight.template.impl.LiveTemplateCompletionContributor;
 import com.intellij.codeInsight.template.impl.TemplateImpl;
+import com.intellij.codeInsight.template.impl.TemplateManagerImpl;
+import com.intellij.codeInsight.template.impl.TemplateSettings;
 import com.intellij.codeInsight.template.impl.TemplateState;
 import com.intellij.diagnostic.AttachmentFactory;
 import com.intellij.ide.IdeEventQueue;
@@ -43,6 +44,7 @@
 import com.intellij.openapi.ui.popup.JBPopupListener;
 import com.intellij.openapi.ui.popup.LightweightWindowEvent;
 import com.intellij.openapi.ui.popup.util.PopupUtil;
+import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.TextRange;
@@ -188,7 +190,12 @@
     }
     if (surroundedText == null && node instanceof TemplateNode) {
       if (key.equals(((TemplateNode)node).getTemplateToken().getKey()) && callback.findApplicableTemplates(key).size() > 1) {
-        callback.startTemplate();
+        TemplateManagerImpl templateManager = (TemplateManagerImpl)callback.getTemplateManager();
+        Map<TemplateImpl, String> template2Argument = templateManager.findMatchingTemplates(callback.getFile(), callback.getEditor(), null, TemplateSettings.getInstance());
+        Runnable runnable = templateManager.startNonCustomTemplates(template2Argument, callback.getEditor(), null);
+        if (runnable != null) {
+          runnable.run();
+        }
         return;
       }
     }
@@ -472,21 +479,29 @@
       final Ref<TemplateImpl> generatedTemplate = new Ref<TemplateImpl>();
       final CustomTemplateCallback callback = new CustomTemplateCallback(editor, file, false) {
         @Override
-        public void deleteTemplateKey(String key) {
+        public void deleteTemplateKey(@NotNull String key) {
         }
 
         @Override
-        public void startTemplate(Template template, Map<String, String> predefinedValues, TemplateEditingListener listener) {
+        public void startTemplate(@NotNull Template template, Map<String, String> predefinedValues, TemplateEditingListener listener) {
           if (template instanceof TemplateImpl && !((TemplateImpl)template).isDeactivated()) {
             generatedTemplate.set((TemplateImpl)template);
           }
         }
       };
 
-      String templatePrefix = computeTemplateKeyWithoutContextChecking(callback);
+      final String templatePrefix = computeTemplateKeyWithoutContextChecking(callback);
 
       if (templatePrefix != null) {
-        if (LiveTemplateCompletionContributor.findApplicableTemplate(file, offset, templatePrefix) == null) {
+        List<TemplateImpl> regularTemplates = TemplateManagerImpl.listApplicableTemplates(file, offset, false);
+        boolean regularTemplateWithSamePrefixExists = !ContainerUtil.filter(regularTemplates, new Condition<TemplateImpl>() {
+          @Override
+          public boolean value(TemplateImpl template) {
+            return templatePrefix.equals(template.getKey());
+          }
+        }).isEmpty();
+        
+        if (!regularTemplateWithSamePrefixExists) {
           // exclude perfect matches with existing templates because LiveTemplateCompletionContributor handles it
           final Collection<SingleLineEmmetFilter> extraFilters = ContainerUtil.newLinkedList(new SingleLineEmmetFilter());
           expand(templatePrefix, callback, null, generator, extraFilters, false);
diff --git a/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java b/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java
index a5295ed..aefcd3f 100644
--- a/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java
+++ b/xml/relaxng/src/org/intellij/plugins/relaxNG/references/FileReferenceUtil.java
@@ -112,18 +112,6 @@
       return result;
     }
 
-    @Override
-    protected ResolveResult[] innerResolve() {
-      final ResolveResult[] results = super.innerResolve();
-      return ContainerUtil.findAll(results, new Condition<ResolveResult>() {
-        @Override
-        public boolean value(ResolveResult resolveResult) {
-          final PsiElement e = resolveResult.getElement();
-          return match(e, myCond);
-        }
-      }).toArray(ResolveResult.EMPTY_ARRAY);
-    }
-
     @NotNull
     @Override
     public Object[] getVariants() {
diff --git a/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.flex b/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.flex
index f79beb6..a6e87b1 100644
--- a/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.flex
+++ b/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.flex
@@ -10,14 +10,6 @@
 %unicode
 
 %{
-  private IElementType elTokenType = XmlTokenType.XML_DATA_CHARACTERS;
-  private IElementType elTokenType2 = XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;
-
-  public void setElTypes(IElementType _elTokenType,IElementType _elTokenType2) {
-    elTokenType = _elTokenType;
-    elTokenType2 = _elTokenType2;
-  }
-
   public _HtmlLexer() {
     this((java.io.Reader)null);
   }
@@ -60,7 +52,7 @@
 DOCTYPE= "<!" (D|d)(O|o)(C|c)(T|t)(Y|y)(P|p)(E|e)
 HTML= (H|h)(T|t)(M|m)(L|l)
 PUBLIC= (P|p)(U|u)(B|b)(L|l)(I|i)(C|c)
-EL_EMBEDDMENT="${" [^\}]* "}"
+EL_EMBEDDMENT="${" [^<\}]* "}"
 
 END_COMMENT="--"[ \n\r\t\f]*">"
 
@@ -115,10 +107,6 @@
   return XmlTokenType.XML_DATA_CHARACTERS;
 }
 
-<YYINITIAL> {EL_EMBEDDMENT} {
-  return elTokenType;
-}
-
 <START_TAG_NAME, END_TAG_NAME> {TAG_NAME} { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_NAME; }
 <END_TAG_NAME2> {TAG_NAME_FWT} { return XmlTokenType.XML_NAME; }
 <START_TAG_NAME2> {TAG_NAME_FWT} { yybegin(TAG_CHARACTERS); return XmlTokenType.XML_NAME; }
@@ -133,9 +121,6 @@
 
 <ATTRIBUTE_VALUE_START> ">" { yybegin(YYINITIAL); return XmlTokenType.XML_TAG_END; }
 <ATTRIBUTE_VALUE_START> "/>" { yybegin(YYINITIAL); return XmlTokenType.XML_EMPTY_ELEMENT_END; }
- <ATTRIBUTE_VALUE_START> {EL_EMBEDDMENT} {
-  return elTokenType2;
-}
 
 <ATTRIBUTE_VALUE_START> [^ \n\r\t\f'\"\>]([^ \n\r\t\f\>]|(\/[^\>]))* { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; }
 <ATTRIBUTE_VALUE_START> "\"" { yybegin(ATTRIBUTE_VALUE_DQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER; }
@@ -144,14 +129,12 @@
 <ATTRIBUTE_VALUE_DQ> {
   "\"" { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER; }
   \\\$ { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; }
-  "${" [^\}\"]* "}" { return elTokenType2; }
   [^] { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;}
 }
 
 <ATTRIBUTE_VALUE_SQ> {
   "'" { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER; }
   \\\$ { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN; }
-  "${" [^\}\']* "}" { return elTokenType2; }
   [^] { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;}
 }
 
diff --git a/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.java b/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.java
index 7f4397a..0765925 100644
--- a/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.java
+++ b/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.java
@@ -1,4 +1,4 @@
-/* The following code was generated by JFlex 1.4.3 on 4/7/14 1:40 PM */
+/* The following code was generated by JFlex 1.4.3 on 4/17/14 5:51 PM */
 
 /* It's an automatically generated code. Do not modify it. */
 package com.intellij.lexer;
@@ -11,7 +11,7 @@
 /**
  * This class is a scanner generated by 
  * <a href="http://www.jflex.de/">JFlex</a> 1.4.3
- * on 4/7/14 1:40 PM from the specification file
+ * on 4/17/14 5:51 PM from the specification file
  * <tt>/Users/denofevil/Code/IDEA/tools/lexer/../../community/xml/xml-psi-impl/src/com/intellij/lexer/_HtmlLexer.flex</tt>
  */
 public class _HtmlLexer implements FlexLexer {
@@ -51,14 +51,14 @@
    */
   private static final String ZZ_CMAP_PACKED = 
     "\11\0\2\3\1\0\2\3\22\0\1\3\1\14\1\11\1\7\1\41"+
-    "\1\0\1\46\1\12\1\45\1\45\3\0\1\6\1\5\1\50\12\2"+
-    "\1\4\1\54\1\13\1\10\1\44\1\47\1\0\1\63\1\36\1\20"+
-    "\1\15\1\26\1\63\1\1\1\27\1\40\2\1\1\32\1\30\1\1"+
-    "\1\16\1\24\3\1\1\21\1\34\3\1\1\23\1\1\1\51\1\53"+
-    "\1\52\1\0\1\4\1\0\1\56\1\37\1\20\1\15\1\26\1\63"+
-    "\1\55\1\27\1\40\2\1\1\33\1\31\1\61\1\17\1\25\1\60"+
-    "\1\1\1\57\1\22\1\35\2\1\1\62\1\23\1\1\1\42\1\45"+
-    "\1\43\54\0\1\1\12\0\1\1\4\0\1\1\5\0\27\1\1\0"+
+    "\1\0\1\44\1\12\1\43\1\43\3\0\1\6\1\5\1\46\12\2"+
+    "\1\4\1\52\1\13\1\10\1\42\1\45\1\0\1\61\1\36\1\20"+
+    "\1\15\1\26\1\61\1\1\1\27\1\40\2\1\1\32\1\30\1\1"+
+    "\1\16\1\24\3\1\1\21\1\34\3\1\1\23\1\1\1\47\1\51"+
+    "\1\50\1\0\1\4\1\0\1\54\1\37\1\20\1\15\1\26\1\61"+
+    "\1\53\1\27\1\40\2\1\1\33\1\31\1\57\1\17\1\25\1\56"+
+    "\1\1\1\55\1\22\1\35\2\1\1\60\1\23\1\1\1\0\1\43"+
+    "\1\0\54\0\1\1\12\0\1\1\4\0\1\1\5\0\27\1\1\0"+
     "\37\1\1\0\u013f\1\31\0\162\1\4\0\14\1\16\0\5\1\11\0"+
     "\1\1\213\0\1\1\13\0\1\1\1\0\3\1\1\0\1\1\1\0"+
     "\24\1\1\0\54\1\1\0\46\1\1\0\5\1\4\0\202\1\10\0"+
@@ -125,19 +125,18 @@
   private static final int [] ZZ_ACTION = zzUnpackAction();
 
   private static final String ZZ_ACTION_PACKED_0 =
-    "\1\1\10\0\1\2\5\0\1\1\1\3\5\1\1\4"+
+    "\1\1\10\0\1\2\5\0\1\1\1\3\4\1\1\4"+
     "\1\5\4\4\1\6\1\4\3\7\1\10\1\7\1\11"+
     "\1\12\1\13\1\14\2\12\1\15\1\16\1\17\1\12"+
-    "\1\20\1\21\1\22\2\20\1\23\1\24\4\23\1\2"+
+    "\1\20\1\21\1\22\1\20\1\23\1\24\2\23\1\2"+
     "\1\25\1\4\1\26\1\15\3\27\1\30\1\7\3\30"+
-    "\1\31\1\32\1\33\1\0\1\34\1\35\15\0\1\35"+
-    "\1\36\2\20\3\0\1\37\2\0\1\40\1\41\1\42"+
-    "\1\43\11\0\1\44\1\45\1\0\1\46\1\20\1\46"+
-    "\1\47\1\0\1\50\3\0\1\15\3\0\1\51\2\0"+
-    "\1\52";
+    "\1\31\1\32\1\33\1\0\1\34\1\35\14\0\1\35"+
+    "\1\36\1\20\1\0\1\37\2\0\1\40\1\41\1\42"+
+    "\11\0\1\43\1\44\1\45\1\0\1\46\3\0\1\15"+
+    "\3\0\1\47\2\0\1\50";
 
   private static int [] zzUnpackAction() {
-    int [] result = new int[131];
+    int [] result = new int[118];
     int offset = 0;
     offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result);
     return result;
@@ -162,26 +161,24 @@
   private static final int [] ZZ_ROWMAP = zzUnpackRowMap();
 
   private static final String ZZ_ROWMAP_PACKED_0 =
-    "\0\0\0\64\0\150\0\234\0\320\0\u0104\0\u0138\0\u016c"+
-    "\0\u01a0\0\u01d4\0\u0208\0\u023c\0\u0270\0\u02a4\0\u02d8\0\u030c"+
-    "\0\u0340\0\u0374\0\u03a8\0\u03dc\0\u0410\0\u0444\0\u0374\0\u0478"+
-    "\0\u04ac\0\u04e0\0\u0514\0\u0548\0\u0374\0\u0410\0\u0374\0\u057c"+
-    "\0\u05b0\0\u0374\0\u0410\0\u0374\0\u0374\0\u05e4\0\u0374\0\u0410"+
-    "\0\u0618\0\u064c\0\u0374\0\u0374\0\u0680\0\u06b4\0\u0374\0\u0374"+
-    "\0\u06e8\0\u071c\0\u0374\0\u0374\0\u0750\0\u0410\0\u0784\0\u07b8"+
-    "\0\u07ec\0\u0374\0\u0820\0\u0854\0\u0888\0\u0374\0\u0410\0\u0680"+
-    "\0\u0374\0\u08bc\0\u057c\0\u0410\0\u08f0\0\u0374\0\u0924\0\u0958"+
-    "\0\u098c\0\u0374\0\u09c0\0\u09f4\0\u0a28\0\u0a5c\0\u0a90\0\u0ac4"+
-    "\0\u0af8\0\u0b2c\0\u04ac\0\u04e0\0\u0b60\0\u0b94\0\u0bc8\0\u0bfc"+
-    "\0\u0374\0\u0374\0\u0c30\0\u0c64\0\u0c98\0\u0ccc\0\u0d00\0\u0374"+
-    "\0\u0d34\0\u0d68\0\u0d9c\0\u0dd0\0\u0374\0\u0374\0\u0e04\0\u0e38"+
-    "\0\u0e6c\0\u0ea0\0\u0ed4\0\u0f08\0\u0f3c\0\u0f70\0\u0fa4\0\u0374"+
-    "\0\u0374\0\u0fd8\0\u06b4\0\u100c\0\u0374\0\u0374\0\u1040\0\u0374"+
-    "\0\u1074\0\u10a8\0\u10dc\0\u0374\0\u1110\0\u1144\0\u1178\0\u0374"+
-    "\0\u11ac\0\u11e0\0\u0374";
+    "\0\0\0\62\0\144\0\226\0\310\0\372\0\u012c\0\u015e"+
+    "\0\u0190\0\u01c2\0\u01f4\0\u0226\0\u0258\0\u028a\0\u02bc\0\u02ee"+
+    "\0\u0320\0\u0352\0\u0384\0\u03b6\0\u03e8\0\u0352\0\u041a\0\u044c"+
+    "\0\u047e\0\u04b0\0\u04e2\0\u0352\0\u03b6\0\u0352\0\u0514\0\u0546"+
+    "\0\u0352\0\u03b6\0\u0352\0\u0352\0\u0578\0\u0352\0\u03b6\0\u05aa"+
+    "\0\u05dc\0\u0352\0\u0352\0\u060e\0\u0640\0\u0352\0\u0352\0\u0672"+
+    "\0\u0352\0\u0352\0\u03b6\0\u06a4\0\u06d6\0\u0352\0\u0708\0\u073a"+
+    "\0\u076c\0\u0352\0\u03b6\0\u060e\0\u0352\0\u079e\0\u0514\0\u03b6"+
+    "\0\u07d0\0\u0352\0\u0802\0\u0834\0\u0866\0\u0352\0\u0898\0\u08ca"+
+    "\0\u08fc\0\u092e\0\u0960\0\u0992\0\u09c4\0\u044c\0\u047e\0\u09f6"+
+    "\0\u0a28\0\u0a5a\0\u0a8c\0\u0352\0\u0352\0\u0abe\0\u0af0\0\u0352"+
+    "\0\u0b22\0\u0b54\0\u0b86\0\u0bb8\0\u0352\0\u0bea\0\u0c1c\0\u0c4e"+
+    "\0\u0c80\0\u0cb2\0\u0ce4\0\u0d16\0\u0d48\0\u0d7a\0\u0352\0\u0352"+
+    "\0\u0352\0\u0dac\0\u0352\0\u0dde\0\u0e10\0\u0e42\0\u0352\0\u0e74"+
+    "\0\u0ea6\0\u0ed8\0\u0352\0\u0f0a\0\u0f3c\0\u0352";
 
   private static int [] zzUnpackRowMap() {
-    int [] result = new int[131];
+    int [] result = new int[118];
     int offset = 0;
     offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result);
     return result;
@@ -204,85 +201,79 @@
   private static final int [] ZZ_TRANS = zzUnpackTrans();
 
   private static final String ZZ_TRANS_PACKED_0 =
-    "\3\20\1\21\3\20\1\22\3\20\1\23\25\20\1\24"+
-    "\4\20\1\25\4\20\1\26\10\20\3\27\1\30\5\27"+
-    "\1\31\1\32\11\27\2\33\1\27\1\34\14\27\1\35"+
-    "\1\27\1\36\15\27\6\37\1\40\4\37\1\41\30\37"+
-    "\1\42\1\37\1\43\2\37\1\44\12\37\1\45\1\46"+
-    "\1\45\1\30\1\46\6\45\1\47\1\45\24\46\5\45"+
-    "\1\50\6\45\7\46\1\45\1\46\1\45\1\30\1\46"+
-    "\6\45\1\51\1\45\24\46\5\45\1\50\6\45\7\46"+
-    "\1\45\1\52\1\45\1\30\1\52\3\45\1\53\4\45"+
-    "\24\52\3\45\1\54\1\45\1\50\1\45\1\55\4\45"+
-    "\7\52\3\56\1\30\5\56\1\57\1\60\26\56\1\61"+
-    "\2\56\1\54\3\56\1\62\13\56\11\63\1\64\27\63"+
-    "\1\65\4\63\1\66\4\63\1\67\22\63\1\64\26\63"+
-    "\1\70\4\63\1\66\4\63\1\67\10\63\44\71\1\72"+
-    "\2\71\1\73\14\71\7\27\1\74\3\27\1\47\32\27"+
-    "\1\36\15\27\3\45\1\30\3\45\1\75\3\45\1\51"+
-    "\30\45\1\54\1\45\1\50\15\45\3\76\1\30\7\76"+
-    "\1\47\30\76\1\54\1\76\1\77\1\76\1\100\13\76"+
-    "\1\101\1\102\4\101\1\103\6\101\24\102\5\101\1\104"+
-    "\3\101\1\105\2\101\7\102\1\101\1\102\4\101\1\103"+
-    "\6\101\24\102\5\101\1\104\3\101\1\106\2\101\7\102"+
-    "\3\20\1\0\3\20\1\0\3\20\1\0\25\20\1\0"+
-    "\4\20\1\0\4\20\1\26\10\20\3\0\1\21\145\0"+
-    "\1\107\2\0\1\107\2\0\1\110\4\0\1\111\24\107"+
-    "\6\0\1\112\1\113\4\0\7\107\42\0\1\114\22\0"+
-    "\1\115\2\0\1\115\2\0\1\116\5\0\16\115\1\117"+
-    "\5\115\14\0\1\117\1\120\1\115\1\121\1\122\2\115"+
-    "\3\20\1\0\7\20\1\0\32\20\1\0\4\20\1\26"+
-    "\10\20\3\0\1\30\60\0\11\123\1\63\52\123\12\124"+
-    "\1\63\51\124\34\0\2\125\47\0\2\126\47\0\1\127"+
-    "\71\0\1\130\50\0\2\46\1\0\3\46\6\0\24\46"+
-    "\14\0\7\46\50\0\1\131\13\0\3\52\1\0\4\52"+
-    "\4\0\30\52\1\0\3\52\1\0\13\52\44\0\1\132"+
-    "\17\0\3\56\1\0\40\56\1\0\3\56\1\133\16\56"+
-    "\1\0\36\56\1\134\1\56\1\0\3\56\1\133\16\56"+
-    "\1\0\40\56\1\132\3\56\1\133\13\56\42\0\1\135"+
-    "\62\0\1\63\64\0\1\136\21\0\44\71\1\0\2\71"+
-    "\1\137\60\71\1\72\17\71\1\0\2\74\1\0\3\74"+
-    "\6\0\24\74\14\0\7\74\1\0\2\75\1\0\3\75"+
-    "\6\0\24\75\14\0\7\75\1\0\3\102\1\0\1\102"+
-    "\6\0\25\102\4\0\2\102\6\0\7\102\44\0\1\140"+
-    "\20\0\2\107\1\0\3\107\6\0\24\107\14\0\7\107"+
-    "\1\0\2\110\1\0\3\110\6\0\24\110\14\0\7\110"+
-    "\6\0\1\141\6\0\1\142\47\0\1\143\2\0\1\143"+
-    "\2\0\1\144\5\0\24\143\14\0\7\143\43\114\1\145"+
-    "\20\114\1\0\2\115\1\0\3\115\6\0\24\115\13\0"+
-    "\1\146\7\115\2\0\1\147\57\0\1\150\2\0\2\115"+
-    "\1\0\3\115\6\0\5\115\1\151\16\115\13\0\1\146"+
-    "\7\115\1\0\2\115\1\0\3\115\6\0\10\115\1\152"+
-    "\3\115\1\153\7\115\13\0\1\146\7\115\1\0\2\115"+
-    "\1\0\3\115\6\0\20\115\1\154\3\115\13\0\1\146"+
-    "\7\115\1\0\2\115\1\0\3\115\6\0\22\115\1\155"+
-    "\1\115\13\0\1\146\7\115\36\0\2\156\54\0\2\157"+
-    "\35\0\1\127\40\0\1\160\70\0\1\161\12\0\44\56"+
-    "\1\0\3\56\1\133\13\56\3\134\1\162\37\134\1\163"+
-    "\1\162\3\134\1\164\13\134\11\135\1\0\31\135\1\165"+
-    "\20\135\12\136\1\0\30\136\1\165\20\136\44\71\1\0"+
-    "\17\71\6\0\1\166\73\0\2\167\45\0\2\143\1\0"+
-    "\3\143\6\0\24\143\14\0\7\143\1\0\2\144\1\0"+
-    "\3\144\6\0\24\144\14\0\7\144\2\0\1\147\51\0"+
-    "\1\170\11\0\1\171\12\0\1\171\2\0\1\171\5\0"+
-    "\1\171\7\0\2\171\16\0\1\171\4\0\1\171\1\0"+
-    "\2\115\1\0\3\115\6\0\24\115\13\0\1\170\7\115"+
-    "\1\0\2\115\1\0\3\115\6\0\2\115\1\172\21\115"+
-    "\13\0\1\146\7\115\1\0\2\115\1\0\3\115\6\0"+
-    "\10\115\1\151\13\115\13\0\1\146\7\115\1\0\2\115"+
-    "\1\0\3\115\6\0\2\115\1\117\21\115\13\0\1\146"+
-    "\7\115\1\0\2\115\1\0\3\115\6\0\24\115\13\0"+
-    "\1\146\2\115\1\153\4\115\32\0\2\173\62\0\2\174"+
-    "\30\0\43\162\1\165\20\162\43\134\1\163\1\162\3\134"+
-    "\1\164\13\134\20\0\1\175\45\0\1\171\12\0\1\171"+
-    "\2\0\1\171\5\0\1\171\7\0\2\171\14\0\1\170"+
-    "\1\0\1\171\4\0\1\171\1\0\2\115\1\0\3\115"+
-    "\6\0\24\115\13\0\1\146\2\115\1\151\4\115\40\0"+
-    "\1\176\44\0\2\177\61\0\1\200\66\0\1\201\64\0"+
-    "\2\202\64\0\1\203\35\0";
+    "\3\20\1\21\3\20\1\22\3\20\1\23\25\20\1\22"+
+    "\2\20\1\24\4\20\1\25\10\20\3\26\1\27\5\26"+
+    "\1\30\1\31\11\26\2\32\1\26\1\33\12\26\1\34"+
+    "\1\26\1\35\15\26\6\36\1\37\4\36\1\40\26\36"+
+    "\1\41\1\36\1\42\2\36\1\43\12\36\1\44\1\45"+
+    "\1\44\1\27\1\45\6\44\1\46\1\44\24\45\3\44"+
+    "\1\47\6\44\7\45\1\44\1\45\1\44\1\27\1\45"+
+    "\6\44\1\50\1\44\24\45\3\44\1\47\6\44\7\45"+
+    "\1\44\1\51\1\44\1\27\1\51\3\44\1\52\4\44"+
+    "\24\51\1\44\1\53\1\44\1\47\1\44\1\54\4\44"+
+    "\7\51\3\55\1\27\5\55\1\56\1\57\27\55\1\53"+
+    "\3\55\1\60\13\55\11\61\1\62\32\61\1\63\4\61"+
+    "\1\64\22\61\1\62\31\61\1\63\4\61\1\64\10\61"+
+    "\42\65\1\66\2\65\1\67\14\65\7\26\1\70\3\26"+
+    "\1\46\30\26\1\35\15\26\3\44\1\27\3\44\1\71"+
+    "\3\44\1\50\26\44\1\53\1\44\1\47\15\44\3\72"+
+    "\1\27\7\72\1\46\26\72\1\53\1\72\1\73\1\72"+
+    "\1\74\13\72\1\75\1\76\4\75\1\77\6\75\24\76"+
+    "\3\75\1\100\3\75\1\101\2\75\7\76\1\75\1\76"+
+    "\4\75\1\77\6\75\24\76\3\75\1\100\3\75\1\102"+
+    "\2\75\7\76\3\20\1\0\3\20\1\0\3\20\1\0"+
+    "\25\20\1\0\2\20\1\0\4\20\1\25\10\20\3\0"+
+    "\1\21\141\0\1\103\2\0\1\103\2\0\1\104\4\0"+
+    "\1\105\24\103\4\0\1\106\1\107\4\0\7\103\1\0"+
+    "\1\110\2\0\1\110\2\0\1\111\5\0\16\110\1\112"+
+    "\5\110\12\0\1\112\1\113\1\110\1\114\1\115\2\110"+
+    "\3\20\1\0\7\20\1\0\30\20\1\0\4\20\1\25"+
+    "\10\20\3\0\1\27\56\0\11\116\1\61\50\116\12\117"+
+    "\1\61\47\117\34\0\2\120\45\0\2\121\45\0\1\122"+
+    "\67\0\1\123\46\0\2\45\1\0\3\45\6\0\24\45"+
+    "\12\0\7\45\46\0\1\124\13\0\3\51\1\0\4\51"+
+    "\4\0\26\51\1\0\3\51\1\0\13\51\42\0\1\125"+
+    "\17\0\3\55\1\0\36\55\1\0\3\55\1\126\16\55"+
+    "\1\0\36\55\1\125\3\55\1\126\13\55\41\0\1\61"+
+    "\20\0\42\65\1\0\2\65\1\127\56\65\1\66\17\65"+
+    "\1\0\2\70\1\0\3\70\6\0\24\70\12\0\7\70"+
+    "\1\0\2\71\1\0\3\71\6\0\24\71\12\0\7\71"+
+    "\1\0\3\76\1\0\1\76\6\0\25\76\2\0\2\76"+
+    "\6\0\7\76\42\0\1\130\20\0\2\103\1\0\3\103"+
+    "\6\0\24\103\12\0\7\103\1\0\2\104\1\0\3\104"+
+    "\6\0\24\104\12\0\7\104\6\0\1\131\6\0\1\132"+
+    "\45\0\1\133\2\0\1\133\2\0\1\134\5\0\24\133"+
+    "\12\0\7\133\1\0\2\110\1\0\3\110\6\0\24\110"+
+    "\11\0\1\135\7\110\2\0\1\136\55\0\1\137\2\0"+
+    "\2\110\1\0\3\110\6\0\5\110\1\140\16\110\11\0"+
+    "\1\135\7\110\1\0\2\110\1\0\3\110\6\0\10\110"+
+    "\1\141\3\110\1\142\7\110\11\0\1\135\7\110\1\0"+
+    "\2\110\1\0\3\110\6\0\20\110\1\143\3\110\11\0"+
+    "\1\135\7\110\1\0\2\110\1\0\3\110\6\0\22\110"+
+    "\1\144\1\110\11\0\1\135\7\110\36\0\2\145\52\0"+
+    "\2\146\33\0\1\122\36\0\1\147\66\0\1\150\12\0"+
+    "\42\55\1\0\3\55\1\126\13\55\42\65\1\0\17\65"+
+    "\6\0\1\151\71\0\2\152\43\0\2\133\1\0\3\133"+
+    "\6\0\24\133\12\0\7\133\1\0\2\134\1\0\3\134"+
+    "\6\0\24\134\12\0\7\134\2\0\1\136\47\0\1\153"+
+    "\11\0\1\154\12\0\1\154\2\0\1\154\5\0\1\154"+
+    "\7\0\2\154\14\0\1\154\4\0\1\154\1\0\2\110"+
+    "\1\0\3\110\6\0\24\110\11\0\1\153\7\110\1\0"+
+    "\2\110\1\0\3\110\6\0\2\110\1\155\21\110\11\0"+
+    "\1\135\7\110\1\0\2\110\1\0\3\110\6\0\10\110"+
+    "\1\140\13\110\11\0\1\135\7\110\1\0\2\110\1\0"+
+    "\3\110\6\0\2\110\1\112\21\110\11\0\1\135\7\110"+
+    "\1\0\2\110\1\0\3\110\6\0\24\110\11\0\1\135"+
+    "\2\110\1\142\4\110\32\0\2\156\60\0\2\157\46\0"+
+    "\1\160\43\0\1\154\12\0\1\154\2\0\1\154\5\0"+
+    "\1\154\7\0\2\154\12\0\1\153\1\0\1\154\4\0"+
+    "\1\154\1\0\2\110\1\0\3\110\6\0\24\110\11\0"+
+    "\1\135\2\110\1\140\4\110\40\0\1\161\42\0\2\162"+
+    "\57\0\1\163\64\0\1\164\62\0\2\165\62\0\1\166"+
+    "\33\0";
 
   private static int [] zzUnpackTrans() {
-    int [] result = new int[4628];
+    int [] result = new int[3950];
     int offset = 0;
     offset = zzUnpackTrans(ZZ_TRANS_PACKED_0, offset, result);
     return result;
@@ -323,17 +314,16 @@
   private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute();
 
   private static final String ZZ_ATTRIBUTE_PACKED_0 =
-    "\1\1\10\0\1\1\5\0\2\1\1\11\4\1\1\11"+
+    "\1\1\10\0\1\1\5\0\2\1\1\11\3\1\1\11"+
     "\5\1\1\11\1\1\1\11\2\1\1\11\1\1\2\11"+
-    "\1\1\1\11\3\1\2\11\2\1\2\11\2\1\2\11"+
-    "\5\1\1\11\3\1\1\11\2\1\1\11\4\1\1\11"+
-    "\2\1\1\0\1\11\1\1\15\0\2\11\2\1\3\0"+
-    "\1\11\2\0\2\1\2\11\11\0\2\11\1\0\2\1"+
-    "\2\11\1\0\1\11\3\0\1\11\3\0\1\11\2\0"+
-    "\1\11";
+    "\1\1\1\11\3\1\2\11\2\1\2\11\1\1\2\11"+
+    "\3\1\1\11\3\1\1\11\2\1\1\11\4\1\1\11"+
+    "\2\1\1\0\1\11\1\1\14\0\2\11\1\1\1\0"+
+    "\1\11\2\0\2\1\1\11\11\0\3\11\1\0\1\11"+
+    "\3\0\1\11\3\0\1\11\2\0\1\11";
 
   private static int [] zzUnpackAttribute() {
-    int [] result = new int[131];
+    int [] result = new int[118];
     int offset = 0;
     offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result);
     return result;
@@ -392,14 +382,6 @@
   private boolean zzEOFDone;
 
   /* user code: */
-  private IElementType elTokenType = XmlTokenType.XML_DATA_CHARACTERS;
-  private IElementType elTokenType2 = XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;
-
-  public void setElTypes(IElementType _elTokenType,IElementType _elTokenType2) {
-    elTokenType = _elTokenType;
-    elTokenType2 = _elTokenType2;
-  }
-
   public _HtmlLexer() {
     this((java.io.Reader)null);
   }
@@ -654,47 +636,43 @@
         case 19: 
           { return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;
           }
-        case 43: break;
+        case 41: break;
         case 26: 
           { yybegin(START_TAG_NAME); yypushback(yylength());
           }
-        case 44: break;
+        case 42: break;
         case 23: 
           { return XmlTokenType.XML_TAG_CHARACTERS;
           }
-        case 45: break;
+        case 43: break;
         case 14: 
           { yybegin(ATTRIBUTE_VALUE_START); return XmlTokenType.XML_EQ;
           }
-        case 46: break;
-        case 34: 
-          { return elTokenType;
-          }
-        case 47: break;
+        case 44: break;
         case 13: 
           { return XmlTokenType.XML_NAME;
           }
-        case 48: break;
+        case 45: break;
         case 20: 
           { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_END_DELIMITER;
           }
-        case 49: break;
+        case 46: break;
         case 10: 
           { yybegin(YYINITIAL); yypushback(1); break;
           }
-        case 50: break;
-        case 41: 
+        case 47: break;
+        case 39: 
           { return XmlTokenType.XML_DOCTYPE_PUBLIC;
           }
-        case 51: break;
-        case 39: 
+        case 48: break;
+        case 37: 
           { yybegin(COMMENT); return XmlTokenType.XML_COMMENT_START;
           }
-        case 52: break;
+        case 49: break;
         case 3: 
           { return XmlTokenType.XML_REAL_WHITE_SPACE;
           }
-        case 53: break;
+        case 50: break;
         case 8: 
           { // according to HTML spec (http://www.w3.org/html/wg/drafts/html/master/syntax.html#comments)
   // comments should start with <!-- and end with --> thus making <!--> absolutely valid comment
@@ -707,127 +685,123 @@
   }
   return XmlTokenType.XML_COMMENT_CHARACTERS;
           }
-        case 54: break;
+        case 51: break;
         case 32: 
           { yybegin(END_TAG_NAME); yypushback(yylength());
           }
-        case 55: break;
+        case 52: break;
         case 1: 
           { return XmlTokenType.XML_DATA_CHARACTERS;
           }
-        case 56: break;
+        case 53: break;
         case 25: 
           { yybegin(COMMENT); return XmlTokenType.XML_CONDITIONAL_COMMENT_END;
           }
-        case 57: break;
+        case 54: break;
         case 33: 
           { yybegin(END_TAG_NAME2); yypushback(yylength());
           }
-        case 58: break;
+        case 55: break;
         case 4: 
           { return XmlTokenType.XML_BAD_CHARACTER;
           }
-        case 59: break;
+        case 56: break;
         case 15: 
           { yybegin(YYINITIAL); return XmlTokenType.XML_TAG_END;
           }
-        case 60: break;
+        case 57: break;
         case 31: 
           { yybegin(COMMENT); return XmlTokenType.XML_CONDITIONAL_COMMENT_START_END;
           }
-        case 61: break;
+        case 58: break;
         case 29: 
           { return XmlTokenType.XML_END_TAG_START;
           }
-        case 62: break;
-        case 36: 
+        case 59: break;
+        case 35: 
           { yybegin(YYINITIAL); return XmlTokenType.XML_COMMENT_END;
           }
-        case 63: break;
-        case 42: 
+        case 60: break;
+        case 40: 
           { yybegin(DOC_TYPE); return XmlTokenType.XML_DOCTYPE_START;
           }
-        case 64: break;
+        case 61: break;
         case 2: 
           { return XmlTokenType.XML_PI_TARGET;
           }
-        case 65: break;
+        case 62: break;
         case 30: 
           { yybegin(YYINITIAL); return XmlTokenType.XML_EMPTY_ELEMENT_END;
           }
-        case 66: break;
-        case 37: 
+        case 63: break;
+        case 36: 
           { yybegin(C_COMMENT_END); return XmlTokenType.XML_CONDITIONAL_COMMENT_END_START;
           }
-        case 67: break;
+        case 64: break;
         case 28: 
           { yybegin(PROCESSING_INSTRUCTION); return XmlTokenType.XML_PI_START;
           }
-        case 68: break;
+        case 65: break;
         case 9: 
           { yybegin(C_COMMENT_START); return XmlTokenType.XML_CONDITIONAL_COMMENT_START;
           }
-        case 69: break;
+        case 66: break;
         case 22: 
           { yybegin(TAG_CHARACTERS); return XmlTokenType.XML_NAME;
           }
-        case 70: break;
+        case 67: break;
         case 6: 
           { yybegin(YYINITIAL); return XmlTokenType.XML_DOCTYPE_END;
           }
-        case 71: break;
-        case 40: 
+        case 68: break;
+        case 38: 
           { return XmlTokenType.XML_CHAR_ENTITY_REF;
           }
-        case 72: break;
+        case 69: break;
         case 12: 
           { return XmlTokenType.XML_START_TAG_START;
           }
-        case 73: break;
+        case 70: break;
         case 5: 
           { return XmlTokenType.XML_WHITE_SPACE;
           }
-        case 74: break;
-        case 35: 
+        case 71: break;
+        case 34: 
           { return XmlTokenType.XML_ENTITY_REF_TOKEN;
           }
-        case 75: break;
+        case 72: break;
         case 24: 
           { yybegin(COMMENT); return XmlTokenType.XML_COMMENT_CHARACTERS;
           }
-        case 76: break;
-        case 38: 
-          { return elTokenType2;
-          }
-        case 77: break;
+        case 73: break;
         case 21: 
           { yybegin(YYINITIAL); return XmlTokenType.XML_PI_END;
           }
-        case 78: break;
+        case 74: break;
         case 17: 
           { yybegin(ATTRIBUTE_VALUE_DQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER;
           }
-        case 79: break;
+        case 75: break;
         case 18: 
           { yybegin(ATTRIBUTE_VALUE_SQ); return XmlTokenType.XML_ATTRIBUTE_VALUE_START_DELIMITER;
           }
-        case 80: break;
+        case 76: break;
         case 11: 
           { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_NAME;
           }
-        case 81: break;
+        case 77: break;
         case 27: 
           { yybegin(START_TAG_NAME2); yypushback(yylength());
           }
-        case 82: break;
+        case 78: break;
         case 16: 
           { yybegin(TAG_ATTRIBUTES); return XmlTokenType.XML_ATTRIBUTE_VALUE_TOKEN;
           }
-        case 83: break;
+        case 79: break;
         case 7: 
           { return XmlTokenType.XML_COMMENT_CHARACTERS;
           }
-        case 84: break;
+        case 80: break;
         default:
           if (zzInput == YYEOF && zzStartRead == zzCurrentPos) {
             zzAtEOF = true;