Snapshot 020d29497847701e84e383d965abf543b80758e2 from idea/133.370 of git://git.jetbrains.org/idea/community.git

020d294: platform: incompatible KTerm option stripped
589c8be: ui: correct icon for facet editor panel
00b8db5: skip invalid highlighters (EA-37197) - 8K reports! (cherry picked from commit 3688a79) [r=Peter.Gromov]
663de5b: IDEA-114952 Eclipse code style import: would be nice to remember imported file location (URL fix for Windows) (cherry picked from commit 7f1b705)
fd13ff8: IDEA-116071 (Field can be final inspection change) (cherry picked from commit e1eab58)[CR-IC-3389]
ae3b411: IDEA-116508 ("Local variable or parameter can be final" inspection use generates uncompilable code not extracting a really finalizable variable) (cherry picked from commit 49639e8)[CR-IC-3388]
e31eafc: EA-52123 (IAE: InvertBooleanHandler.invoke) (cherry picked from commit 18e2e69)
b318047: 2x more compact mapping storage for 7bit ascii paths [r=Eugene.Zhuravlev] (cherry picked from commit 2f10822)
42fa68e: IDEA-117378 Privilege escalation via JetBrains products by local attacker (cherry picked from commit 81b56c6)
87e3a49: IDEA-118063 Gradle: cosmetic fix 'Add gradle plugin' action: 'Choose plugin' popup has lots of not clickable links (cherry picked from commit ca4f7bc)
1245a78: IDEA-117792 Gradle Run/Debug Configuration: support adding Gradle specific parameters; review - http://crucible.labs.intellij.net/cru/CR-IC-3727
8558b99: 13.0.2 with EAP
997edcb: no smart icons and no parameter info in power save mode (cherry picked from commit 4bb3242)
bdd56c0: [^jeka] tolerate mysterious groovy class file corruption
a346506: IDEA-118397 Resume build not working (cherry picked from commit ea2b802) +review CR-IC
a659297: IDEA-118245 Retain the last used command line in the Execute Maven Goal dialog (cherry picked from commit 26a7d57) +review CR-IC
a604811: IDEA-118102 Maven: artifacts name not properly generated from pom in IDEA 13 (cherry picked from commit e610603) +review CR-IC
a8ffcf9: IDEA-118053 Editor "deprived of mind" when editing settings.xml (cherry picked from commit ed529d5) +review CR-IC
0e9a065: IDEA-78508 [Maven] Good Code Red with empty variables in classifiers (cherry picked from commit 0831af1) +review CR-IC
cbd34cb: IDEA-116921 Run configuration can't resolve test dependency when "Resolve workspace artifacts" ticked on. (cherry picked from commit d06f31a) +review CR-IC
75e374a: Fix for IDEA-116940 @formatter off still generating braces [CR-IC-3478] (cherry picked from commit 3340beb)
1f6f81f: avoid unconditional trace properly (cherry picked from commit 2e72fcc)
5f45643: Compilation fix
a4749db: IDEA-118292 (process idea.properties in declaration order)
679e1c4: IDEA-118111 (OpenJDK 6 check made strict)
950225b: restore classes in nav bar (IDEA-118168)
cfe1124: NPE
0a41d99: method may be static: process default methods (IDEA-118272)
6ff67d9: redundant cast: ensure that temp variable would have unique name (IDEA-118197)
9549258: distinct prover: distinguish types when type parameter has bounds (IDEA-118037)
0dcb258: show param info: highlight overload vararg method
c40975b: method references: smart completion to filter by return type
319017d: disable lambda completion after inserted qualifier
ed361ec: do not register fixes which need editor in batch mode (IDEA-116248)
30cba59: EA-52652 - NPE:  ExceptionUtil.getUnhandledExceptions
c9199b7: redundant type args: process nested calls (IDEA-117945)
fad3ead: IDEA-117989 JUnit: Run/Debug java test output "scroll to stacktrace" not working as expected
c9d58cc: IDEA-117911 Delegate methods duplicate @Override
35afc12: generate javadoc: search for modules under progress
bf0ec72: IDEA-117883 make <--tooltip end--> logic work in Inspections View; provide additional tooltip bounds
056b529: new inference: propagate outer method to constraints, initial (IDEA-117803)
cd65706: IDEA-117827 Invalid "ambiguous method call" error
8251b5d: IDEA-117780 Bad code is green: non-static class T cannot be referenced from a static context
4a1ae2f: restore suppressions (IDEA-117763)
b7003c6: pull up: ignore conflicts coming from access object when it is also moved (IDEA-117671)
282c332: remember different working dirs for rerun (IDEA-116110)
8224a17: scope to check for cheap search (IDEA-117665)
b2affde: refactoring high level listeners (IDEA-115905)
a2ae64e: NPE
f75829b: extend local scope a set of containing files as visitors expect file level (IDEA-117649)
c72c42f: tests notification: separate not started notification from ignored when no 'not started' tests were detected (IDEA-116825)
5a0aebc: suspicious names: highlight only variable name (IDEA-116475)
62ba24a: disable introduce variable from part of literal expression which is not a string
740bbf2: testng: ignore default annotations attributes (IDEA-117575)
52c384c: add explicit arguments: eliminate wildcards (IDEA-106741)
31e57cc: check lambda return values during constant&conditions (IDEA-117420)
c8ff7ea: javafx: allow to configure custom manifest attributes (IDEA-115252)
99b89cc: IDEA-117314 Can not compile Java project with Eclipse dependencies storage format
528f2d5: introduce variable inside lambda: do not step out of lambda block
48cb2be: IDEA-117252 Extract variable bug
8724806: IDEA-113339 "replace with method reference" ignores side effect of expression: ignore any new expressions in qualifiers
6f6d61b: lambda -> method ref: do not convert if resulted ref would be ambiguous (IDEA-116964)
d9a89a1: EA-52426 - NPE: JavaDocInfoGenerator.generateSuperMethodsSection
df01945: IDEA-118264 Rearrange Entries stopped working in Intellij 13
5e7d560: files compiled on first round may require additional recompilation on the next round (second part for IDEA-116914)  constant search on the IDE side rewritten: only direct dependencies are returned for each search round; all transitive dependencies will be additionally handled by make
4792865: handling cases when added class hides imported class with the same short name (IDEA-116914 Incremental compilation of Java project fails)
e99d464: correct check
ea90776: safely skipping some invalid usages
3a16b61: proper synchronization
0c9c72e: IDEA-117249 Optimize make's constant search algorithm, so that read action is not held for long time
f19231c: do not search usages of removed constant fields in injected PSI
d6ef061: Merge branch '133' of git.labs.intellij.net:idea/community into 133
fa65f8e: IDEA-35996 Ant integration: provide more informative message in case ant file execution is stopped due to unknown command line argument
9519530: IDEA-117904 Ant integration: running: with an error (javac) the result is reported as "successful": perform all status calculations after all messages are processed
5a9f9a8: IDEA-111702 Java Rearranger illegal forward reference on fields rearrangement [CR-IC-3034] (cherry picked from commit 7f01bcd)
a2dd3a6: IDEA-115786 Allow the number of Maven threads to be specified (cherry picked from commit 9d05ff2) +review CR-IC
abfd9a5: IDEA-114418 (Grails SDK of an dependency)  -Dgrails.disable.structure.update=true should work for JDK synchronization. (cherry picked from commit 009ca28) +review CR-IU
491ceb6: IDEA-96723 Java Rearranger deletes blank lines in field declarations (cherry picked from commit 15869e7)
85fe89f: IDEA-118159 "Search Everywhere" inconsistent api on ItemPresentation (cherry picked from commit 9729ea9) [r=Konstantin.Bulenkov]
bcf528b: revert platform fix for PY-6095, apply Python specifix fix instead (cherry picked from commit 0dfae8b)
fec8fe7: IDEA-117864
930439c: cosmetics
6c1df41: IDEA-108838 Wrong code when introducing variable in injection (cherry picked from commit f119c2e)
2a40aeb: Merge remote-tracking branch 'origin/133' into 133
d92cdcc: IDEA-117391 (annotation highlighting fixed)
05a20ae: IDEA-117772 (start application loading in EDT)
ef18d70: DevKit: refine DOM stubs + test (cherry picked from commit 84d8e52)
15d7962: IDEA-117583 DevKit: highlight <idea-version> "min"|"max" as deprecated (cherry picked from commit ce277a1)
be71e9a: cleanup, update "since-build" (cherry picked from commit f56ca26)
e9aa79b: IDEA-117573 DevKit: highlight <vendor> "logo" as obsolete (cherry picked from commit d552ee4)
d5d86be: EA-52563 - assert: ChooseModulesDialog$MyTableCellRenderer$.customizeCellRenderer (cherry picked from commit d24d279)
009d144: CodeInsightTestUtil#doIntentionTest(): remove Throwable declaration (cherry picked from commit d7e8e2a)
e543b44: lazy class loading for PtyProcess (r=Eugene.Zhuravlev), 2 (cherry picked from commit 85700e4)
edd9c56: save / load per project key hash codes (cherry picked from commit c847d67) [r=Eugene.Zhuravlev]
eff72da: avoid garbage creation in JDK7 due to calling StringBuilder.toString() that copies buffer now (cherry picked from commit 03f7413) [r=Peter.Gromov]
40c73d4: no need to create strings of PsiFile's Text when we can avoid it or use charsequence (cherry picked from commit d8ec59b) [r=Peter.Gromov]
10c479c: introduced cvs.roots.refresh.uses.vfs property (true by default) and uses its value to refresh cvs roots after update using vfs to avoid performance problems (IDEA-112132) (cherry picked from commit 1958e9a) [r=Peter.Gromov]
8cac2e5: - detect proper encoding for html5's <meta charset="charsetname"> - [performance fix] avoid (light) parsing of html content if there is no charset\s*= pattern inside the string (cherry picked from commit 2f4be38) [r=Alexey.Kudryavtsev]
cee6644: IDEA-78206 Constructing 'mailto' link -> cannot resolve file 'mailto' (cherry picked from commit 3166c04) [r=Konstantin.Ulitin]
98571ff: Cyclic Expand Word leaves word highlighted (IDEA-115727) (cherry picked from commit 29bb231) [r=Peter.Gromov]
31fe1a1: refixing IDEA-57940 : the variants from other editors are suggested AFTER finishing variants from current file (cherry picked from commit e76fe51) [r=Peter.Gromov]
e3975be: avoid allocating sun.nio.cs.US_ASCII$Decoder when converting byte[] to String
1053bdb: don't create TIntArrayList(DEPTH_LIMIT) before we have clear indication that we might have a loop (parentId >= id) (cherry picked from commit 5478fdf) [r=Alexey.Kudryavtsev]
364e80e: avoid unconditional trace (cherry picked from commit 2e72fcc) [r=Alexey.Kudryavtsev]
70980d8: don't call toString() without need to avoid garbage (cherry picked from commit 75c030c) [r=Alexey.Kudryavtsev]
466dc64: Apply again "update stubs per filetype  reverted for 133 branch"
3f66295: Apply again "IDEA-113684 Soft wraps insert additional spaces"
028b3ae: Darcula: combobox as cell renderer/editor fixes
e96975a: fix default size of SourceMapInspector window (cherry picked from commit a64047e)
edfb4da: if IDEA sees text/plain and extension .java, perhaps it should infer that it's actually Java, because not everyone will set up their HTTP servers with language-specific mime types? (Particularly when following a URL to a source file in a sourcemap.) +review (cherry picked from commit 5ea95e3)
6162222: fix ClassCastException: com.intellij.openapi.fileEditor.FileEditorState$1 cannot be cast to com.intellij.openapi.fileEditor.impl.text.TextEditorState (cherry picked from commit 44f0697)
6c8dbc0: update progress on test done (finished, failed, or ignored), not on test started (cherry picked from commit dbcb907)
a4038dd: REGISTERED state added (cherry picked from commit 08677f9)
bf0da3a: fix PersistenceRenameTest blinking: inconsistent @NameValue placement and random methods order in DomGenericInfo
1f08879: PsiBuilder/GPUB: zero-length token parsing support (lexer-based macros)
352056d: EA-52484 - IOOBE: ConsoleHistoryModel.getHistoryPrev
21ab06f: EA-52027 - assert: TextRange.<init>
b452663: IDEA-116383 cannot reconnect Some RuntimeException contains not serializable class 'org.apache.maven.model.building.DefaultModelProblem'. So IDEA throw java.rmi.UnmarshalException  caused by java.io.NotSerializableException. (cherry picked from commit 9f7fb6c) +review CR-IC
a4e9447: Revert "IDEA-113684 Soft wraps insert additional spaces"
231adec: Revert "update stubs per filetype  reverted for 133 branch"
d62a526: use method instead of manual hack
cae16e2: better combobox rendering on aqua: no focus ring around combo button, fixed 1px size difference
7d9b58c: fix TextFieldWithHistory rendering on mac
95d40df: determine tag end by doctype #WEB-2229 fixed
556c3bc: lazy class loading for PtyProcess (r=Eugene.Zhuravlev) (cherry picked from commit 96c8bca)
749d89f: RUBY-14672: better name for gracefulProcessTermination() (reviewed by Dennis Ushakov and Sergey Simonchik ) (cherry picked from commit 908538b)
dd5dd11: RUBY-14672: we need to send SIGINT to Ruby debugger twice (reviewed by Dennis Ushakov and Sergey Simonchik ) (cherry picked from commit 4546732)
3c01a72: Merge remote-tracking branch 'origin/133' into 133
6378e77: [git] IDEA-118265 Fix showing Git Branches menu
b9446e2: close process's input stream after process termination (cherry picked from commit e962648) CR-WS-272
c8fbe68: support Windows soft kills using runnerw.exe in KillableColoredProcessHandler (cherry picked from commit 77e0f1a) CR-IC-3459
988c990: fix showValuePopup — incorrect scrolling (cherry picked from commit 594785c)
1f67166: IDEA-105450 Attribute id in OSGI reference element not allowed: XmlHighlightingTest.testXhtmlSchemaHighlighting fixed (cherry picked from commit 69daed6)
eb3a323: IDEA-105450 Attribute id in OSGI reference element not allowed: get schemaLocation from import tag (cherry picked from commit ec44bbd)
8bb9587: IDEA-105450 Attribute id in OSGI reference element not allowed: namespaces from standard resources should be considered relevant (cherry picked from commit d30684d)
a129c6c: IDEA-84166 Support "CTRL+H" on class in .xml file (cherry picked from commit da3cbf3)
7162d4b: update stubs per filetype  reverted for 133 branch
377bf70: IDEA-113684 Soft wraps insert additional spaces (cherry picked from commit 0e1c820)
643cd5d: use direct call to storage.resize() so that IOException is not masked with RuntimeException (IDEA-118107)
2e7c85f: Plugin for IDEA 133.286 3.0.1 EAP CE
f75f35e: Merge branch '133' of git.labs.intellij.net:idea/community into 133
9186d35: PyCharm 3.1
58936a1: add create method
ecf556d: do nothing if state didn't change
dcfbfb5: IDEA-115859 Presentation mode is broken
1d6443d: Javascript tests fixed, IDEA-113977 Formatter: caret is moved on next line if closing brace has wrong indent  [CR-IC-3034] (cherry picked from commit dd55e70)
b75041b: Merge branch '133' of git.labs.intellij.net:idea/community into 133
2a74e83: Pty lib updated - run in console mode.
390900e: Guava and Pty4J libraries dependencies.
10a39d8: Contains in branches feature implemented for mercurial log.
37a14b0: Added logging.
9355a2b: improved user experience with run configuration producers
78e57f9: Better multiline code handling in console.
fc7702f: Correct test data path.
6bba62d: Detect SQL fragments only in the beginning of string literals
ba5ff19: Fixed LiteralTextEscaper.getOffsetInHost() for partial ranges inside host that contain escapes
df0c579: Added caching of decoded fragments of string literals
f93a871: Fixed detecting file references in Python strings without delimiters
01bf006: Removed unused PyStringLiteralExpression.iterateCharacterRanges()
147ed7a: Switched to new string value iteration in Python file references inside string literals
f8e775c: Use Pair instead of a custom class
0106a10: Switched to new string value iteration in Python spellchecker
69ac8c5: Added PyStringLiteralExpression.getDecodedFragments()
d703ca5: reverted module type from plugin_module to java_module for localization and rest
2cb9a61: fixed tests since we don't propose to make static decorated method
d6ed1d7: fixed PY-10998 Wrong highlight in rst (restructured texts) for headlines
5511e2f: Fix NPE.
9f0c134: Don't break compatibility (PY-11499).
f80fc2e: fixed PY-11500 False positive in method may be static inspection for decorated methods
0bfaaf2: fixed PY-2984 Surround with try/except reformats entire file
0ed12da: args can be immutable (PY-11465).
1bb8318: fixed PY-11435 Can't run script by context menu action if it has method named test
0336898: Fixed detection of the largest string literal for right parts of '%' operator
cb5714e: fixed PY-11452 tcunittest errors with single-character failure message
2503a60: fixed test data
16aa28c: fixed PY-11476 No error given for mismatched accolade and squarebracket
403b937: Allow to run processes with PTY.
4740054: Added comment-based language injector for Python
f56fecc: fixed tests
45a824c: Fixed un-inject language availability for temporary Python injections
ea707eb: Method renamed.
4b349d3: Extracted PyInjectionBase.registerInjection
909a31d: Don't inject any language into percent-based Python formatting even without formatting operator (PY-10771)
b928248: Fixed SQL select IntelliLang pattern (PY-10926)
55239bf: If command executed but is incomplete and more lines are needed prompt shouldn't be changed to ordinary one in this case.
a061c7e: Fix modified console options modified after creation.
52b6eb3: Jython doesn't support 'exec' symbol in interactive console.
1213be2: PyConsole: correctly indent after execution of incomplete multi-line string.
38b4e20: Fixed execution of incomplete multiline code fragments.
5306cfb: First evaluate more then add to queue.
4f18cfe: Simplified.
9688ef7: Attribute renamed.
10a0e30: NotNull annotation.
5e5c546: Fixed IPython and debug console broken by console execution model changes.
e53607e: Fixed write lock assertion.
78ea78d: Execute multi-line code fragments by runsrouce with 'exec' option instead of one line by one (PY-10769).
0dcf990: Cleanup.
9f4dca96: Broken indentetion in console fixed (PY-10776).
3c4550e: Fixed saving of env in console settings. Mappings format saving changed.
699255f: Fixed working directory setting in console settings.
9b98ce9: Fixed saving path mappings in console settings (PY-9855).
14fbafd: Don't ask to reconnect remote interpreter in case of fail as it never helps but causes problems (PY-10590).
f8a096a: Support for temporary and configuration-based IntelliLang injections in Python (PY-10983, PY-10721)
5def9d3: fixed http://youtrack.jetbrains.com/issue/PY-2953
e6a24df: fixed PY-11394 "no tests were found" with django 1.6 DiscoverRunner
1fb4a8a: used consistent name prefix
923f8c0: fixed PY-11415 GAE: Lazy Handler reference is not updated when moving to other module
0a3c840: fixed PY-9967 App Engine: do not resolve to installed to interpreter library
ea42fbf: [log] Fix showing dot in the root table header
decac91: [log] Fix background of the details panel content (cherry picked from commit 2ad2cba)
224a2be: [log] fix name of variable
f79c2e4: [log] IDEA-115675 IDEA-116040 Fix table columns sizing
668c021: [log] IDEA-117500 Don't repaint branches panel on every updateUI
ed4a8ca: [log] IDEA-117500 Optimize grouping of branch references
a98e6c8: [git] Don't modify the unmodifiable collection (cherry picked from commit 007dc0d)
9321b17: [git] IDEA-117500 Don't copy, just wrap in unmodifiable
f3cd826: [git] remove unused method
d7db0fc: [log] Separate loading indicator for "Contained in branches"
ab8606f: [log] Fix "Containing branches" for filtered list & for Mercurial
c190668: [git] Move & rename method to get branches to GitBranchUtil for reuse (cherry picked from commit f78700e)
0ae4458: [git] Simplify method to get branches: use branch names.
423dbc6: IDEA-117936 IDEA13 fails to stop at breakpoint inside advised method
4587a46: IDEA-117613 Gradle: tool window is missing after the update, safe check for newly created project added
18e44f3: IDEA-117613 Gradle: tool window is missing after the update review: http://crucible.labs.intellij.net/cru/CR-IC-3629
b9b4c6c: fixed IDEA-111701 Emacs: pressing Ctrl+k several times should add lines to muti-line buffer (regression for IDEA-18764, broken in IDEA-111275)
a843386: we must not use getKnownFileTypeOrAssociate on navigate (cherry picked from commit 476b30d)
cf363b6: fix actionSystem.fixLostTyping.description (cherry picked from commit caf3ece) CR-IC-3481
4dfe767: IDEA-117548 Bad function parameters highlight (cherry picked from commit d4507c9)
b83ac23: fix assertion (cherry picked from commit 5743c3c)
f7e5eeb: WEB-10231 first navigation to http file doesn't open desired location (cherry picked from commit 384f8f9)
fe39b87: wait smart mode checks for isReadAccessAllowed too, so, we must not call it (cherry picked from commit a5dd92c)
f4c9d17: optimization — check isEmpty (cherry picked from commit 44727c2)
cd8fb58: VmFileEditor — prepare to fix postponed navigation problem in our HTTP file editor. VmFileEditor supports postponed navigation. (cherry picked from commit db4ca37)
c669320: "Run in background" option from now on means "show build messages immediately" rather than "execute with modal dialog"
d83aedd: don't generate large substrings when creating CompletionResultSet [r=Peter.Gromov]
87ad24b: 13.0.1
14361cd: avoid easy garbage java.util.ArrayList$Itr: 1,720,417,512 (1%) bytes in 71,684,063 (2%) objects (avg size 24 bytes) 	java.util.ArrayList.iterator: 1,720,392,864 (99%) bytes in 71,683,036 (99%) objects 		com.intellij.openapi.projectRoots.impl.ProjectJdkTableImpl.findJdk: 938,831,640 (54%) bytes in 39,117,985 (54%) objects 		com.intellij.openapi.editor.impl.ComplementaryFontsRegistry.getFontAbleToDisplay: 218,420,520 (12%) bytes in 9,100,855 (12%) objects (cherry picked from commit 9207b87) [r=Peter.Gromov]
41efe97: look for xml properties in files with xml file type only (cherry picked from commit b6ae811) [r=Dmitry.Avdeev]
ea2590e: WEB-10191 Weird field in the Configure NodeJS Modules Sources (cherry picked from commit 0f61ced) http://crucible.labs.intellij.net/cru/CR-IC-3556
a2b39c2: Gradle: fix dependencies scope merge IDEA-117556 Gradle custom provided configuration added with compile scope IDEA-117601 Gradle integration ignores scopes.TEST.plus in build.gradle (cherry picked from commit f80d692) Safe hotfix, the code works in a separate process (in gradle daemon, not in IDE process)
ce53010: External system: build files modification triggers threads continuously if "auto-import" feature enabled review- http://crucible.labs.intellij.net/cru/CR-IC-3533
4d9ae0c: Gradle: fix dependency scope merge to respect artifact classifier option related bug - IDEA-117627 Transitive dependencies missing from imported Gradle project Safe hotfix, the code works in a separate process (in gradle daemon, mot in IDE process)
d9c3f83: IDEA-117669 gradle multi-module project executing subtask uses wrong gradle version review - http://crucible.labs.intellij.net/cru/CR-IC-3564
87819e2: Gradle: IDEA-116880 Intellij 13 doesn't auto-save files before Gradle task (cherry picked from commit e5c53c6)
5b87b39: Gradle: fix MultipleRepositoryUrlsInspection to operate on gradle-relevant files only (cherry picked from commit 95fbdc9)
1c2f07c: IDEA-117432 Do not fail while resolving client factory for upgrade if "other factory" is configured incorrectly (cherry picked from commit 0694e5d)
d11b435: IDEA-117432 Do not fail while resolving client factory for checkout if "other factory" is configured incorrectly (cherry picked from commit 6242d70)
db15422: Branch information checks moved to appropriated separated methods. (cherry picked from commit 9492982)
6f85df3: Method name simplified (cherry picked from commit 0924c2b)
16e2328: IDEA-115906 Throwable ; IDEA-117401 IAE fixed
eedd7fe: HEAD branch filter in new log fixed (cherry picked from commit 7793e6f)
a787eb2: VcsRootDetector and NotifierError tests fixed (there were .git in T ot tmp dir above, so appropriate checker found its root,then error)
ddc643d: remove outdated and buggy (in case of library code) property java.debugger.xBreakpoint.onlyIfHasFacets (cherry picked from commit 5b7f60f)
ab9cce8: CR-IC-3511 CFR-63806 (cherry picked from commit e800ade)
d3e739f: introduce newUrl (cherry picked from commit bb94f47)
5009fbf: VisualizeScriptSourcemap action (cherry picked from commit 2694a1f)
2051c1e: cleanup (cherry picked from commit 30d4cdf)
586ef62: Merge remote-tracking branch 'origin/133' into 133
3a93fee: rollback IDEA-117378. It will be available in 13.0.2
d72ed2a: IDEA-117227 load imports from stubs [^Peter]
5568b0d: Groovy: injection in command expression [^Peter]
b0ef47e: IDEA-117389 Groovy: Introduce constant from string part [^Peter]
7076f89: IDEA-117227 stubs for Groovy imports [^Peter]
605a0a9: IDEA-117390 'IntelliJIdeaRulezzz' in Code Completion [^peter]
ac4417e: fix testdata
8607b4d: IDEA-116547 optimization in reassigned vars check [^peter]
1e7c610: WEB-10019 Don't show emmet preview after simply dot (cherry picked from commit 127560f)
4b36aad: WEB-9986 CSS: fuzzy search shows turned off abbreviations (cherry picked from commit 56e0385)
4b4958e: WEB-10017 New "Surround with emmet" popup breaks usability (cherry picked from commit 8bdc013)
0bd5b71: automatically starts rebuild if java builder caches are corrupted (IDEA-117024) [rev by Jeka]
f536c49: Merge remote-tracking branch 'origin/133' into 133
81b56c6: IDEA-117378 Privilege escalation via JetBrains products by local attacker
633cd5e: a temporary workaround for HiDPI on Windows/Linux
b7a8a38: Local VCS tests quick fix (ignore temp. FS)
eecd3d1: make history almost unlimited
72de836: no delay after tab or escape
96b5a46: re-create components on every call (laf change fix)
9aa347b: Extracted Python path walking and fixed broken symlink check (PY-10534)
66b3393: differentiate between Sun and Oracle VMs
6b27a51: fixed silent installation mode.
0e4a0fc: IDEA-117378 Privilege escalation via JetBrains products by local attacker IDEA-113862 Confusing Run as dialog
a7300cd: [^maxim] FrequentEventDetector: log outside of synchronized (IDEA-117426)
9d0b588: [^nik] GroovyHotSwapper: use FileTypeIndex
3228a63: [^nik] cache GroovyHotSwapper.containsGroovyClasses (IDEA-116851)
57ff2da: IDEA-103199 Undo: UTF problem (after-review improvements) (cherry picked from commit 0a0aecf)
75ed596: IDEA-103199 Undo: UTF problem (cherry picked from commit ea49ecf)
0a705a8: correct definition of "oracle vm" for java 6
7464e2f: can not clear JarFileHandler caches (e.g. on JDK 7) -> no logging (cherry picked from commit 5012a9b) [r=Alexey.Kudryavtsev]
299f014: IDEA-117498 Caret locks up after using ctrl+tab to switch editors [r=Peter.Gromov] (cherry picked from commit 38f2f05)
99b71dc: IDEA-117494 133.193: Importing grails modules not labeled as grails enabled +review CR-IU (cherry picked from commit 588cd01) reviewer: Peter Gromov
48ce506: do not auto-switch current suspend context if a new thread with suspenPolicy=thread hits a breakpoint (IDEA-116160)
64dc9f5: CR-IC-3489 restore old API
f1dcd4c: Merge remote-tracking branch 'origin/133' into 133
4b41e83: [log] IDEA-117365 Expect "empty" git tag; protect against errors
725c360: [log] Register disposable right away, not after initialization (cherry picked from commit 1e48680)
265d0df: EA-51913 - assert: DomNamespaceKeyIndex.hasStubElementsWithNamespaceKey (cherry picked from commit 6763822) CR-IC-3472
42ecb1a: CR-IC-3471 (cherry picked from commit b213f10)
89ee113: finalize consts (cherry picked from commit 73b245e)
d033d07: gwt, ability to debug — one idea module to many gwt modules (cherry picked from commit 8086f92)
056f905: NullFileEditorState +review (cherry picked from commit 561c8d1)
ca7af60: overrides (cherry picked from commit aaa236a)
4f2af9c: CR-IU-366 (cherry picked from commit 40ae21d)
c8c0d46: Problem — we use short gwt module name (Hello) instead of output name (hello, rename-to specified in Hello.gwt.xml). 1) if rename-to specified, url will be http://localhost:9876/sourcemaps/{rename-to} rename-to=“hello” => http://localhost:9876/sourcemaps/hello 2) if rename-to is not specified, url will be http://localhost:9876/sourcemaps/{qualified name} com.google.gwt.sample.hello.Hello => http://localhost:9876/sourcemaps/com.google.gwt.sample.hello.Hello
40f41b5: IDEA-116260 ISE: RPC handler object "AddOnlineUser" not found at com.intellij.ide.XmlRpcServerImpl.process (cherry picked from commit 5aa9b8e)
3265387: enable all lafs by passing a special registry key
bf2b0c6: Rename "Java" -> "JVMOptions" so MacOS doesn't require java 1.6 download from Apple.
c825894: [log] Make fields volatile
3cc0a09: [git] IDEA-116690 Fix "Select in Git Log" from File History
8b85de3: fixing IDEA-117328 java.lang.NoSuchMethodError: com.sun.tools.javac.util.Paths.clearPathExistanceCache()
7e1850e: Merge remote-tracking branch 'origin/133' into 133
f2aed4c: IDEA-117347 Search Everywhere popup is too wide
3675b82: merging ConcurrentMapFactory and ContainerUtil
98ef79b: fix Url equality (scheme) (cherry picked from commit e668634)
290e4a4: fix NPE — url could be in any form, so, parsed can be null (cherry picked from commit ec22c2e)
f90eaba: allow V8 map on IBM JDK 1.7
845ffae: do not disable "ext.dirs" location, because IBM jdk stores some of its essential jars there
5278615: EA-52516 - IAE: HighlightUsagesHandlerBase.addOccurrence
cae4139: EA-52505 - NPE: MethodCandidateInfo.getPertinentApplicabilityLevel
9b6b81e: default concurrency level upper limit
91cefef: encapsulation of factory's implementation details
1081168: IDEA-117298 Darcula&IntelliJ on Windows: Inspection description is too small in Settings
7799dc3: IDEA-117095 Goto File: checkbox 'include non-project files' is remembered between invocations [r=Anna.Kozlova] (cherry picked from commit 7cf6caa)
8eecc0f: all code in "util" module to create CHM implementation via dedicated factory (see IDEA-116404 Java code compilation does not work with IBM JDK)
81ae633: [Filechooser sheets] IDEA-102449 Mac OS + JDK 1.7: dialog sheets go to background if focus is moved from IDEA and then back
ea058b0: fix NPEs
8fbca43: Remove broken dependency on 'markdownj' from tasks-core module
5c1098b: IDEA-117258 IntelliJ theme: selected tabs in Debugger and in Run <application server> views get black color
5e02eb3: IDEA-116558 Update state transition requests for JIRA REST API 2
c2f531a: "read access" assertion and NPE fixes
ea4f96b: fix "read access" assertion
787438f: IDEA-117265 java.lang.ClassCastException: com.intellij.psi.impl.source.tree.java.PsiParenthesizedExpressionImpl cannot be cast to com.intellij.psi.PsiCallExpression
99ae1f5: NPE on invalid expressions
ffc7fa5: IDEA-115953 Editor: Line Spacing < 1.0 no longer works (reviewed by Roman Shevchenko)
886b675: External system: add support for different naming of external entities within IDEA models. E.g. external lib name: 'somelib' -> IDEA lib name: 'Gradle: somelib'. external module name: 'some/module' -> IDEA module name: 'some_module'. (cherry picked from commit bb941b0)
0634d95: enable abbreviations (cherry picked from commit 0ecc836)
1dc77a9: more searchable options
31750db: fix history and symbols 'More' action
bc4db67: Merge remote-tracking branch 'origin/133' into 133
84f584a4: add new actions
5a49390: change action place to Main Menu
4a50f96: don't use smart search for files (don't use space as a separator)
93dd505: ready to nulls (EA-52470 - IAE: TypeCompatibilityConstraint.<init>)
174531a: EA-52436 - IAE: PsiElementFactoryImpl.createType
e58f16d: IDEA-115412 Diff window is minimized  after the appearance (cherry picked from commit b2307d0)
8146462: IDEA-117059 (error reporting in updater fixed)
be1c105: NPE in mouse handler
a460658: IDEA-111388 Built-in server not "available external" — it is unclear that port number must be also changed (cherry picked from commit 6ccdae5)
dfdaaae: continue WEB-9968 Dart: ClassCastException when debugging web application in Dartium (cherry picked from commit c19e163)
ee28c75: newHttpUrl — authority must be NotNull (cherry picked from commit a708a6e)
01efd39: NetUtils.tryToFindAvailableSocketPort (cherry picked from commit fa39c70)
ca466c8: introduce Urls.newUri, prepare to fix WEB-9968 Dart: ClassCastException when debugging web application in Dartium (cherry picked from commit 4ecac7f)
e6b739a: IDEA-117059 (same temp. directory for updater)
2679834: introduced idea.register.bundled.fonts registry to be able to switch off bundled fonts registration in order to avoid garbled text in editor (IDEA-93404) [r=Konstantin.Bulenkov] (cherry picked from commit e2cdb6d)
16eb783: fix null project
05de913: report missing optimizedFileManager only once
1b747fe: correct place for optimizedFileManager.jar
4713bfc: Merge branch '133' of git.labs.intellij.net:idea/community into 133
c2c0281: Jediterm updated.
26cf0f4: Mouse selection should always work in Terminal (IDEA-117210).
1f68d01: reconfigure navbar toolbar actions
1ae092c: show separators in navbar toolbar
afcfe95: Setup composite as it is done in EditorImpl.paintComponent.
66f161d: Behave the same as EditorImpl.
013c138: Use Source Code Pro as we don't have problems with unprintable pseudo-graphics as we iterate fonts to find suitable one for unprintable characters.
9796737: special icon for generated test root [rev by Peter]
2398eb9: make adapt_builder_() overridable (initState -> public)
2ef1c62: [git] Quick-fix for IDEA-115581: don't fail, just skip such hashes
1578562: [vcs] IDEA-109608 Apply patch: Fix path detection for new files + test
080813c: update Source Code Pro to version 17
f9c2953: IDEA-117211 empty elements in Search Everywhere
32ebdf3: error reporting in 'Project Structure' dialog: merge UI updates (IDEA-116808, IDEA-110799) [rev by Maxim M.]
2bab20f: added quick-fix to delete all unused libraries (IDEA-99885) [rev by Maxim M.]
f069657: disable GroovyShell because it doesn't work on win {^Peter]
637a5ba: Merge branch '133' of git.labs.intellij.net:idea/community into 133
dd8e18a: moved to core-impl
47f94f0: IDEA-104734 Dracula: Cannot see well active tab in Modules Settings
e2c1637: removed LOG.error for null syntax highlighter (cherry picked from commit 3e4c22c) [r=Peter.Gromov]
d4240b2: check that index for which indexUnsavedDocument is performed can be applied to given file type (EA-47740) [r=Eugene.Zhuravlev] (cherry picked from commit 0057f81)
acede1f: Merge branch '133' of git.labs.intellij.net:idea/community into 133
5ffb206: PsiSearchHelper changes cherry-picked (r:Peter)
1669188: avoid blocking runReadAction in debug logging
ba70dd4: Minor typo fix (IDEA-116432 Incorrect Spelling of Eclipse) (cherry picked from commit 3c553d6)
aadedc9: IDEA-117192 NavBar popup shows in wrong place when navigating to the directory from popup
c3b6615: Merge remote-tracking branch 'origin/133' into 133
a915da31: Merge remote-tracking branch 'origin/133' into 133
9a90c16: IDEA-116866 (path overriding for plugins/log dirs fixed once again)
bc3d847: Merge remote-tracking branch 'origin/133' into 133
6081b4f: removed signing for CE launchers.
21cd0c7: tuned UI for got it button
f986c7c: method refs: do not choose more specific method between methods with different number of params
aa7db43: IDEA-116756 Gradle multi-module project with deep-nested modules - idea places iml file in the wrong directory (cherry picked from commit 8e2ad06)
3bd2a55: plugin advertiser: ensure that older plugins won't be ever suggested
f739564: plugins advertise: download plugin if it was not explicitly disabled (IDEA-117003)
df398a9: plugins advertiser: provide loading plugin version for renderer
751d401: CCE (IDEA-117119)
03b253b: lambda: do not distinguish between ellipsis and arrays for formal lambda params checks (IDEA-117124)
ca191c9: index property optimization [^Peter]
4f7ba3a: class searching optimization [^Peter]
4e7ff49: IDEA-116628 No nulls in type parameters [^Peter]
a30f59b: typo [^Peter]
580cb5e: Merge branch '133' of git.labs.intellij.net:idea/community into 133
9c2489a: Take default shell from env variable.
9b2b7f3: File chooser for shell path (PY-11334).
9758753: Take shell path setting before every process creation.
3dbe4eb: use the same background color
8b8c0df: set lower limit of 1 for max_worker_threads_count (for low-profile cpu)
2a67fed: test for unzipping malformed zip archive (cherry picked from commit cd35a94) CR-WS-267
2c74d46: target error message for a newly created project (cherry picked from commit 8e10c3a) CR-WS-267
41311ea: use ZipFile, because it throws exception for a malformed zip archive (cherry picked from commit 02da50f) CR-WS-267
323523c: make IntelliJ laf by default on Linux
9d74b04: update artwork for version 13
d7ce47d: add history
42733a8: utility class holding two colors for gradient painting
537dd04: better colors? fix balloon and popup borders
787ec72: added signing for community launchers in zip distr.
f577493: use backported V8 CHM only for Oracle or Apple JDK (IDEA-116404 Java code compilation does not work with IBM JDK)
ae19efc: isEap = false, no error reporting
7e1f100: ~update mockJDK-1.7 used classes to be at least from jdk 1.5
c812622: do not create raw outer types during diamond inference
d0bc4ad: Merge branch '133' of git.labs.intellij.net:idea/community into 133
b6fe06f: FinderRecursivePanel: do not perform getListItems() in EDT on update (cherry picked from commit a128fa5) CR-IC-3413
e189085: IDEA-116866 (path overriding for plugins/log dirs fixed)
c50b1f1: Cleanup (punctuation)
cf75962: External System: support for multiple tasks execution added (cherry picked from commit a6f9141)
60418e9: IDEA-100294 Cannot edit a file - text jumps all over the screen (cherry picked from commit 36bacc0) [cdr]
3da28ad: Merge remote-tracking branch 'origin/133' into 133
86b3924: mock 1.8 jdk
ae8c2b0: switching to java.util.ConcurrentHashMap in jps code; eliminate unneeded map queries
f3d2761: EA-52322 (diagnostic)
f0d71c1: copyright: fix for 2 open projects
e797eb4: javadoc: keep whitespaces in {@code} tags (IDEA-109997) (cherry picked from commit d08af6dfed35217f3bb03093e8c549ec3065d258)
aa52879: IDEA-117082 Anonymous class assigned to final field (cherry picked from commit 02cabc4e849835259d9d837f86493c5e4ff7269c)
c040d2f: junit: do not reuse directory configuration from another test root (IDEA-116871) (cherry picked from commit 354fece7efab569fa05b135ab912bee758a6d3f7)
99043c6: junit: do not create directory configuration when selection is not under test root, e.g. module content root (IDEA-116871) (cherry picked from commit effc865ab3bff89d4651054569ef7ac4f86d7b33)
f8ff71b: product name -> full product name (IDEA-117070) (cherry picked from commit 2b4dc107514b4bd13ec4dced1144c81de79a0bb7)
d60166d: plugins advertiser: ensure that all installed plugins would be enabled - check also unknown plugins (IDEA-117068) (cherry picked from commit 99ffd837ba1ec2523ae8c4faa2060c84b5941986)
b3ed3c2: plugins advertiser: do not suggest to update to ultimate on implicitly disabled plugins (IDEA-117040) (cherry picked from commit e5452974f1a45693dd8ddb967525d37cd54f3ba4)
61ebb02: IDEA-116991 "IDE is up to date" message (cherry picked from commit 094ac76636050b6f0796c9802342cb3d431eeab0)
a4dc3a5: lambda: process lambda as parameter for anonymous class (IDEA-116987) (cherry picked from commit bf64625fb2e79f29f924d47fb68ec55d7c46d954)
7be1ec1: IDEA-117071 (language level in decompiled .class files)
5e5d914: relative path - special url, encoding is not required (cherry picked from commit 58704c7)
7f786c5: cleanup (cherry picked from commit 3868464)
208311d: cleanup (cherry picked from commit d58146c)
53f1175: CR-IC-3246 (cherry picked from commit 5d6a0c8)
a186992: CR-IC-3246 (cherry picked from commit 51864f4)
04cd96d: open in browser — choose url, show full url, not only path (decoded form with parameters) (cherry picked from commit b3fff55)
bb59091: WeightBasedComparator — string natural compare (cherry picked from commit 86971b9)
52c78b1: overrides (cherry picked from commit 716766a)
5b53293: Urls.newFromIdea returns not-null (cherry picked from commit f47f98a)
fde95ae: move Url to platform - avoid raw string (cherry picked from commit d4e4a40)
7dabf92: UriUtil.trimLastSlash refine Url nullability (newFromIdea is not yet done) (cherry picked from commit 9b8aac5)
e1bcebb: CR-IC-2986 (cherry picked from commit 34ef731)
6a65720: cleanup (cherry picked from commit e50df4c)
60e168b: CR-IC-2986 MessageBuilder -> MessageDialogBuilder (cherry picked from commit 1999b51)
be3b2ec: some memory tune-ups
cfbafa0: IDEA-117077 Can't remove files from Recent Files
3f42891: EA-52338 - assert: ComponentManagerImpl.getComponent (cherry picked from commit 7c076b6)
58bc683: IDEA-117030 Groovy/Gradle frequent, severe hangs (cherry picked from commit aadeb26)
0ef7db2: IDEA-117073 Recent files and Switcher are not centred in ide window
4a2dde3: file watchers tips should be in WS only
39ee2d2: update complete statement tips
292b280: remove image tag
bffe81e: missed images
b975e7d: Add missing module definition.
3cd9608: Add license for "aether-api-0.9.0.M2.jar" (cherry picked from commit 0df2a18)
d63a566: IDEA-116452 "Resolve workspace artifacts" option doesn't work with Maven 3.1.x (cherry picked from commit 8c35e68)
9103476: Enter in SE should close popup if selection is a setting
4f37f20:  button placed on top, should be in the middle
6c28556: [log] IDEA-116399 Fix filter by branch
7684e66: IDEA-116881 Please time stamp gradle tasks (cherry picked from commit 79c4e6e)
db139a1: IDEA-116891 gradle import creates a lot of extra empty directories (cherry picked from commit 9732da7)
9ed8e39: WEB-9933 What should happen when creating node.js Express App as New Module? (cherry picked from commit a0c7d51) CR-WS-262
2e2fd29: IDEA-116891 gradle import creates a lot of extra empty directories (cherry picked from commit ca7e083)
5902fb8: IDEA-116974 Gradle Plugin doesn't handle 'providedCompile' dependencies in 'war' projects correctly (cherry picked from commit d3f9d06)
0e97c89: Merge remote-tracking branch 'origin/133' into 133
5be1c50: IDEA-115546 Full Screen Mode: main menu persists on screen, when invoked by the keyboard shortcut(reviewed by kb)
4055528: IDEA-111161 Flat tool window design PATCH(reviewed by kb)
17913b8: Lens pixel hunting (reviewed by kb)
38dd8e8: select correct shell runner in title [^Peter]
57befaf: IDEA-116917 check for jansi in classpath [^Peter]
93e3010: IDEA-66494 Switching between search and replace (cherry picked from commit d7dc6ca) [r=Peter.Gromov]
45d852b: IDEA-66494 Switching between search and replace (cherry picked from commit d7dc6ca) [r=Peter.Gromov]
7673aeb: IDEA-116952 IntelliJ LAF issue (set label.disabledForeground to 999999)
56d2cb6: IDEA-116911 Speed search: wrong background in recent files
6ecd960: IDEA-115577 Commit Changes: keyboard shortcut for Commit Message History does not work
27aa855: IDEA-115708 Add workaround by setting global SSLContext (cherry picked from commit fc3f452bbbef193a3ebf6fd28d7e0bffb14a9a5a)
7c3e066: get rid of invoke later [^Peter]
3f10d5b: special icon for 'generated source' roots: added file forgotten by first cherry-pick (cherry picked from commit 35806f22)
6f3780e: grayed text is invisible on Linux
f64ba46: menu is not visible on Linux + IntelliJ theme
e7f0816: [vcs] IDEA-115571 Don't clean change lists's commit message until committed
f0226f9: [log] Make "show details" & "show long edges" actions dumb aware (cherry picked from commit 726ffc1)
8ca08ac: [log] IDEA-116950 Draw just "tag +" instead of "tag + 5 more" (cherry picked from commit 49a033a)
976a8ef: [log] IDEA-116950 Don't display all tags if there are too many of them
4a1db8f: [log] Refactor: move ref painter & drawRefs & calc refs padding to the common parent class (cherry picked from commit 3bb3524)
5dd3597: IDEA-113730 Implemented "cat" command to read content as binary data (not to read as text data and then convert to bytes using some encoding) (cherry picked from commit efd5985)
4201c87: update tips
5c4c6e0: special icon for 'generated source' roots [rev by Peter] (cherry picked from commit 35806f2)
fcc237f: [^nicity] fix outdated javadoc (completion is performed in a read action) (cherry picked from commit d4e5553)
0f918a9: [^nicity] support hippie completion at the file start (EA-52100) (cherry picked from commit 3334c0b)
41b5038: IDEA-102449 Mac OS + JDK 1.7: dialog sheets go to background if focus is moved from IDEA and then back
aff52ee: IDEA-116784 Error Parsing Regex /\s/ in Groovy [^Peter]
8bf0c61: IDEA-95170 closure parameter type [^peter]
8f7c63d: IDEA-116378 only expressions are available in loop conditions [^peter]
d889262: IDEA-116837 Groovy: don't suggest to shorten references in comments [^peter]
f835a08: IDEA-116621 Groovy: Extract Parameter Refactoring: 'Replace this occurrence only' replaces all occurrences in current method [^peter]
6ee4359: [log] fix action's update()
5b8fb93: do not update recent projects on closing in headless mode
3fb3322: Merge remote-tracking branch 'origin/133' into 133
9251d90: SSH console - credentials validation (cherry picked from commit 8b7b23a)
9947162: IDEA-116824 Gradle: Provide an inspection & quickfix for multiple custom maven repo links (cherry picked from commit 810199f)

Change-Id: I47b8e5f8b6b865ec46d5625dd1838900539d7d93
diff --git a/.idea/modules.xml b/.idea/modules.xml
index 7173cae..5d00c5a 100644
--- a/.idea/modules.xml
+++ b/.idea/modules.xml
@@ -109,6 +109,7 @@
       <module fileurl="file://$PROJECT_DIR$/plugins/maven/maven.iml" filepath="$PROJECT_DIR$/plugins/maven/maven.iml" group="plugins/maven" />
       <module fileurl="file://$PROJECT_DIR$/plugins/maven/artifact-resolver-m2/maven-artifact-resolver-m2.iml" filepath="$PROJECT_DIR$/plugins/maven/artifact-resolver-m2/maven-artifact-resolver-m2.iml" group="plugins/maven" />
       <module fileurl="file://$PROJECT_DIR$/plugins/maven/artifact-resolver-m3/maven-artifact-resolver-m3.iml" filepath="$PROJECT_DIR$/plugins/maven/artifact-resolver-m3/maven-artifact-resolver-m3.iml" group="plugins/maven" />
+      <module fileurl="file://$PROJECT_DIR$/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml" filepath="$PROJECT_DIR$/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml" group="plugins/maven" />
       <module fileurl="file://$PROJECT_DIR$/plugins/maven/jps-plugin/maven-jps-plugin.iml" filepath="$PROJECT_DIR$/plugins/maven/jps-plugin/maven-jps-plugin.iml" group="plugins/maven" />
       <module fileurl="file://$PROJECT_DIR$/plugins/maven/maven-server-api/maven-server-api.iml" filepath="$PROJECT_DIR$/plugins/maven/maven-server-api/maven-server-api.iml" group="plugins/maven" />
       <module fileurl="file://$PROJECT_DIR$/plugins/maven/maven2-server-impl/maven2-server-impl.iml" filepath="$PROJECT_DIR$/plugins/maven/maven2-server-impl/maven2-server-impl.iml" group="plugins/maven" />
diff --git a/bin/idea.properties b/bin/idea.properties
index 33bee38..be34798 100644
--- a/bin/idea.properties
+++ b/bin/idea.properties
@@ -1,26 +1,26 @@
-# Use ${idea.home} macro to specify location relative to IDE installation home
-# Also use ${xxx} where xxx is any java property (including defined in previous lines of this file) to refer to its value
-# Note for Windows users: please make sure you're using forward slashes. I.e. c:/idea/system
+# Use ${idea.home} macro to specify location relative to IDE installation home.
+# Use ${xxx} where xxx is any Java property (including defined in previous lines of this file) to refer to its value.
+# Note for Windows users: please make sure you're using forward slashes (e.g. c:/idea/system).
 
 #---------------------------------------------------------------------
-# Uncomment this option if you want to customize path to IDE config folder. Make sure you're using forward slashes
+# Uncomment this option if you want to customize path to IDE config folder. Make sure you're using forward slashes.
 #---------------------------------------------------------------------
 # idea.config.path=${user.home}/.@@settings_dir@@/config
 
 #---------------------------------------------------------------------
-# Uncomment this option if you want to customize path to IDE system folder. Make sure you're using forward slashes
+# Uncomment this option if you want to customize path to IDE system folder. Make sure you're using forward slashes.
 #---------------------------------------------------------------------
 # idea.system.path=${user.home}/.@@settings_dir@@/system
 
 #---------------------------------------------------------------------
-# Uncomment this option if you want to customize path to user installed plugins folder. Make sure you're using forward slashes
+# Uncomment this option if you want to customize path to user installed plugins folder. Make sure you're using forward slashes.
 #---------------------------------------------------------------------
-# idea.plugins.path=${user.home}/.@@settings_dir@@/config/plugins
+# idea.plugins.path=${idea.config.path}/plugins
 
 #---------------------------------------------------------------------
 # Uncomment this option if you want to customize path to IDE logs folder. Make sure you're using forward slashes.
 #---------------------------------------------------------------------
-# idea.log.path=${user.home}/.@@settings_dir@@/system/log
+# idea.log.path=${idea.system.path}/log
 
 #---------------------------------------------------------------------
 # Maximum file size (kilobytes) IDE should provide code assistance for.
@@ -91,7 +91,7 @@
 sun.java2d.pmoffscreen=false
 
 #---------------------------------------------------------------------
-# Workaround to avoid long hangs while accessing clipboard under Mac OS X. 
+# Workaround to avoid long hangs while accessing clipboard under Mac OS X.
 #---------------------------------------------------------------------
 #ide.mac.useNativeClipboard=True
 
diff --git a/build/conf/mac/Contents/Info.plist b/build/conf/mac/Contents/Info.plist
index 987f33d..ce773a4 100644
--- a/build/conf/mac/Contents/Info.plist
+++ b/build/conf/mac/Contents/Info.plist
@@ -62,7 +62,7 @@
     <key>LSRequiresNativeExecution</key>
     <string>YES</string>
     @@url_schemes@@
-    <key>Java</key>
+    <key>JVMOptions</key>
     <dict>
       <key>ClassPath</key>
       <string>@@class_path@@</string>
diff --git a/build/conf/mac/Contents/MacOS/idea b/build/conf/mac/Contents/MacOS/idea
index 6cee6be..1089d07 100755
--- a/build/conf/mac/Contents/MacOS/idea
+++ b/build/conf/mac/Contents/MacOS/idea
Binary files differ
diff --git a/build/conf/nsis/idea.nsi b/build/conf/nsis/idea.nsi
index 3191b48..4b80457 100644
--- a/build/conf/nsis/idea.nsi
+++ b/build/conf/nsis/idea.nsi
@@ -749,7 +749,7 @@
   ${If} $0 == "1"  
     ;ExecCmd::exec 'icacls "$INSTDIR" /grant %username%:F /T >"$INSTDIR"\installation_log.txt 2>"$INSTDIR"\installation_error.txt'
     AccessControl::GrantOnFile \
-      "$INSTDIR" "(S-1-5-32-545)" "GenericRead + GenericExecute + GenericWrite + Delete"
+      "$INSTDIR" "(S-1-5-32-545)" "GenericRead + GenericExecute"
   ${EndIf}
 SectionEnd
 
diff --git a/build/scripts/layouts.gant b/build/scripts/layouts.gant
index 79a4506..63b1027 100644
--- a/build/scripts/layouts.gant
+++ b/build/scripts/layouts.gant
@@ -301,6 +301,13 @@
         }
       }
 
+      jar("artifact-resolver-m31.jar") {
+        module("maven-artifact-resolver-m31")
+        module("maven-artifact-resolver-m2") {
+          include(name: 'org/jetbrains/idea/maven/artifactResolver/common/*')
+        }
+      }
+
       dir("maven3") {
         fileset(dir: "$home/plugins/maven/maven3-server-impl/lib") {include(name: "*.jar")}
         fileset(dir: "$home/plugins/maven/maven3-server-impl/lib/maven3/lib") {include(name: "*.jar")}
@@ -718,12 +725,14 @@
       include(name: "nanoxml-*.jar")
       include(name: "protobuf-*.jar")
       include(name: "cli-parser-*.jar")
-      include(name: "optimizedFileManager.jar")
       include(name: "log4j.jar")
       include(name: "jgoodies-forms.jar")
       include(name: "ecj*.jar")
       include(name: "jsr166e.jar")
     }
+    fileset(dir: "$home/jps/lib") {
+      include(name: "optimizedFileManager.jar")
+    }
     dir("test") {
       jar("jps-build-test.jar") {
         moduleTests("jps-builders")
diff --git a/build/scripts/libLicenses.gant b/build/scripts/libLicenses.gant
index 01a28df..bfe2f29 100644
--- a/build/scripts/libLicenses.gant
+++ b/build/scripts/libLicenses.gant
@@ -207,6 +207,7 @@
 libraryLicense(name: "Maven", version: "2.2.1", license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
 libraryLicense(name: "plexus-util", version: "2.0.6", license: "Apache 2.0", url: "http://maven.apache.org/", libraryNames:['plexus-utils-2.0.6.jar'], licenseUrl: "http://apache.org/licenses/LICENSE-2.0")
 libraryLicense(name: "aether-api", version: "1.11", libraryNames: ["aether-api-1.11.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
+libraryLicense(name: "aether-api-0.9.0.M2.jar", version: "0.9.0.M2", libraryNames: ["aether-api-0.9.0.M2.jar"], license: "Eclipse Public License v1.0", url: "http://nexus.sonatype.org/", licenseUrl: "http://www.eclipse.org/org/documents/epl-v10.html")
 libraryLicense(name: "maven-2.2.1-uber", version: "2.2.1", libraryNames: ["maven-2.2.1-uber.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
 libraryLicense(name: "maven-artifact", version: "3.0.3", libraryNames: ["maven-artifact-3.0.3.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
 libraryLicense(name: "maven-core", version: "3.0.3", libraryNames: ["maven-core-3.0.3.jar"], license: "Apache 2.0", url: "http://maven.apache.org/", licenseUrl: "http://maven.apache.org/license.html")
diff --git a/colorSchemes/src/colorSchemes/Darcula.xml b/colorSchemes/src/colorSchemes/Darcula.xml
index 724db8f..2e96e56 100644
--- a/colorSchemes/src/colorSchemes/Darcula.xml
+++ b/colorSchemes/src/colorSchemes/Darcula.xml
@@ -16,7 +16,7 @@
     <option name="ANNOTATIONS_COLOR" value="8b999f" />
     <option name="CARET_COLOR" value="bbbbbb" />
     <option name="CARET_ROW_COLOR" value="323232" />
-    <option name="CONSOLE_BACKGROUND_KEY" value="333333" />
+    <option name="CONSOLE_BACKGROUND_KEY" value="2B2B2B" />
     <option name="FILESTATUS_ADDED" value="629755" />
     <option name="FILESTATUS_DELETED" value="6c6c6c" />
     <option name="FILESTATUS_IDEA_FILESTATUS_DELETED_FROM_FILE_SYSTEM" value="6c6c6c" />
diff --git a/community-resources/src/idea/IdeaApplicationInfo.xml b/community-resources/src/idea/IdeaApplicationInfo.xml
index 084236c..9e07e0c 100644
--- a/community-resources/src/idea/IdeaApplicationInfo.xml
+++ b/community-resources/src/idea/IdeaApplicationInfo.xml
@@ -1,10 +1,10 @@
 <component>
-  <version codename="Community Edition" major="13" minor="0" eap="true"/>
+  <version codename="Community Edition" major="13" minor="0.2" eap="true"/>
   <company name="JetBrains s.r.o." url="http://www.jetbrains.com/?fromIDE"/>
   <build number="__BUILD_NUMBER__" date="__BUILD_DATE__"/>
   <install-over minbuild="129.1" maxbuild="132.9999" version="12.1"/>
-  <logo url="/idea_community_logo.png" textcolor="ffffff" progressColor="ffaa16" progressY="230" progressTailIcon="/community_progress_tail.png"/>
-  <about url="/idea_community_about.png" foreground="f5f5f5" linkColor="9dc0ff" logoX="300" logoY="265" logoW="75" logoH="30"/>
+  <logo url="/idea_community_logo.png" textcolor="444444" progressColor="ffaa16" progressY="222" progressTailIcon="/community_progress_tail.png"/>
+  <about url="/idea_community_about.png" foreground="444444" linkColor="000099" logoX="300" logoY="265" logoW="75" logoH="30"/>
   <icon size32="/icon_CE.png" size16="/icon_CEsmall.png" size32opaque="/icon_CEwhite.png" size12="/toolwindows/toolWindowProject.png" size128="/icon_CE_128.png" ico="idea_CE.ico"/>
   <package code="__PACKAGE_CODE__"/>
   <names product="IDEA" fullname="IntelliJ IDEA" script="idea"/>
diff --git a/community-resources/src/idea_community_about.png b/community-resources/src/idea_community_about.png
index 3f363f2..5bed0ec 100644
--- a/community-resources/src/idea_community_about.png
+++ b/community-resources/src/idea_community_about.png
Binary files differ
diff --git a/community-resources/src/[email protected] b/community-resources/src/[email protected]
index 619c7c5..428aaa5 100644
--- a/community-resources/src/[email protected]
+++ b/community-resources/src/[email protected]
Binary files differ
diff --git a/community-resources/src/idea_community_logo.png b/community-resources/src/idea_community_logo.png
index f95add3..87543ff 100644
--- a/community-resources/src/idea_community_logo.png
+++ b/community-resources/src/idea_community_logo.png
Binary files differ
diff --git a/community-resources/src/[email protected] b/community-resources/src/[email protected]
index 50ea4ee..57603be 100644
--- a/community-resources/src/[email protected]
+++ b/community-resources/src/[email protected]
Binary files differ
diff --git a/images/src/org/intellij/images/editor/impl/ImageFileEditorProvider.java b/images/src/org/intellij/images/editor/impl/ImageFileEditorProvider.java
index da0f8f1..56fe8d3 100644
--- a/images/src/org/intellij/images/editor/impl/ImageFileEditorProvider.java
+++ b/images/src/org/intellij/images/editor/impl/ImageFileEditorProvider.java
@@ -15,7 +15,10 @@
  */
 package org.intellij.images.editor.impl;
 
-import com.intellij.openapi.fileEditor.*;
+import com.intellij.openapi.fileEditor.FileEditor;
+import com.intellij.openapi.fileEditor.FileEditorPolicy;
+import com.intellij.openapi.fileEditor.FileEditorProvider;
+import com.intellij.openapi.fileEditor.FileEditorState;
 import com.intellij.openapi.project.DumbAware;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Disposer;
@@ -31,46 +34,49 @@
  * @author <a href="mailto:[email protected]">Alexey Efimov</a>
  */
 final class ImageFileEditorProvider implements FileEditorProvider, DumbAware {
-    @NonNls private static final String EDITOR_TYPE_ID = "images";
+  @NonNls private static final String EDITOR_TYPE_ID = "images";
 
-    private final ImageFileTypeManager typeManager;
+  private final ImageFileTypeManager typeManager;
 
-    ImageFileEditorProvider(ImageFileTypeManager typeManager) {
-        this.typeManager = typeManager;
-    }
+  ImageFileEditorProvider(ImageFileTypeManager typeManager) {
+    this.typeManager = typeManager;
+  }
 
-    public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
-        return typeManager.isImage(file);
-    }
+  @Override
+  public boolean accept(@NotNull Project project, @NotNull VirtualFile file) {
+    return typeManager.isImage(file);
+  }
 
-    @NotNull
-    public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {
-        return new ImageFileEditorImpl(project, file);
-    }
+  @Override
+  @NotNull
+  public FileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file) {
+    return new ImageFileEditorImpl(project, file);
+  }
 
-    public void disposeEditor(@NotNull FileEditor editor) {
-      Disposer.dispose(editor);
-    }
+  @Override
+  public void disposeEditor(@NotNull FileEditor editor) {
+    Disposer.dispose(editor);
+  }
 
-    @NotNull
-    public FileEditorState readState(@NotNull Element sourceElement, @NotNull Project project, @NotNull VirtualFile file) {
-        return new FileEditorState() {
-            public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
-                return false;
-            }
-        };
-    }
+  @Override
+  @NotNull
+  public FileEditorState readState(@NotNull Element sourceElement, @NotNull Project project, @NotNull VirtualFile file) {
+    return FileEditorState.INSTANCE;
+  }
 
-    public void writeState(@NotNull FileEditorState state, @NotNull Project project, @NotNull Element targetElement) {
-    }
+  @Override
+  public void writeState(@NotNull FileEditorState state, @NotNull Project project, @NotNull Element targetElement) {
+  }
 
-    @NotNull
-    public String getEditorTypeId() {
-        return EDITOR_TYPE_ID;
-    }
+  @Override
+  @NotNull
+  public String getEditorTypeId() {
+    return EDITOR_TYPE_ID;
+  }
 
-    @NotNull
-    public FileEditorPolicy getPolicy() {
-        return FileEditorPolicy.HIDE_DEFAULT_EDITOR;
-    }
+  @Override
+  @NotNull
+  public FileEditorPolicy getPolicy() {
+    return FileEditorPolicy.HIDE_DEFAULT_EDITOR;
+  }
 }
diff --git a/images/src/org/intellij/images/editor/impl/ImageFileEditorState.java b/images/src/org/intellij/images/editor/impl/ImageFileEditorState.java
index 6a7dab4..2fdb949 100644
--- a/images/src/org/intellij/images/editor/impl/ImageFileEditorState.java
+++ b/images/src/org/intellij/images/editor/impl/ImageFileEditorState.java
@@ -43,6 +43,7 @@
     this.zoomFactor = zoomFactor;
   }
 
+  @Override
   public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
     return otherState instanceof ImageFileEditorState;
   }
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
index b67a815..0f13731 100644
--- a/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
+++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildManager.java
@@ -924,8 +924,6 @@
     launcherCp.add(ClasspathBootstrap.getResourcePath(launcherClass));
     launcherCp.add(compilerPath);
     ClasspathBootstrap.appendJavaCompilerClasspath(launcherCp);
-    // this will disable standard extensions to ensure javac is loaded from the right tools.jar
-    cmdLine.addParameter("-Djava.ext.dirs=");
     cmdLine.addParameter("-classpath");
     cmdLine.addParameter(classpathToString(launcherCp));
     
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java b/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java
index 135b154..e0a7ffa 100644
--- a/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java
+++ b/java/compiler/impl/src/com/intellij/compiler/server/BuildMessageDispatcher.java
@@ -41,7 +41,7 @@
 
   private static final AttributeKey<SessionData> SESSION_DATA = new AttributeKey<SessionData>("BuildMessageDispatcher.sessionData");
 
-  private final Map<UUID, SessionData> myMessageHandlers = new ConcurrentHashMap<UUID, SessionData>();
+  private final Map<UUID, SessionData> myMessageHandlers = new ConcurrentHashMap<UUID, SessionData>(16, 0.75f, 1);
   private final Set<UUID> myCanceledSessions = new ConcurrentHashSet<UUID>();
 
   public void registerBuildMessageHandler(UUID sessionId,
diff --git a/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java b/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java
index 3cb1260..ef9d84b 100644
--- a/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java
+++ b/java/compiler/impl/src/com/intellij/compiler/server/DefaultMessageHandler.java
@@ -15,19 +15,18 @@
  */
 package com.intellij.compiler.server;
 
-import com.intellij.compiler.make.CachingSearcher;
 import com.intellij.lang.java.JavaLanguage;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProcessCanceledException;
 import com.intellij.openapi.project.DumbService;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Computable;
 import com.intellij.openapi.util.Ref;
-import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
 import com.intellij.psi.search.*;
-import com.intellij.psi.util.PsiUtil;
+import com.intellij.util.SmartList;
 import com.intellij.util.cls.ClsUtil;
 import com.intellij.util.concurrency.SequentialTaskExecutor;
 import io.netty.channel.Channel;
@@ -45,15 +44,11 @@
  */
 public abstract class DefaultMessageHandler implements BuilderMessageHandler {
   private static final Logger LOG = Logger.getInstance("#com.intellij.compiler.server.DefaultMessageHandler");
-  private final int MAX_CONSTANT_SEARCHES = Registry.intValue("compiler.max.static.constants.searches");
   private final Project myProject;
-  private int myConstantSearchesCount = 0;
-  private final CachingSearcher mySearcher;
   private final SequentialTaskExecutor myTaskExecutor = new SequentialTaskExecutor(PooledThreadExecutor.INSTANCE);
 
   protected DefaultMessageHandler(Project project) {
     myProject = project;
-    mySearcher = new CachingSearcher(project);
   }
 
   @Override
@@ -62,6 +57,7 @@
 
   @Override
   public final void handleBuildMessage(final Channel channel, final UUID sessionId, final CmdlineRemoteProto.Message.BuilderMessage msg) {
+    //noinspection EnumSwitchStatementWhichMissesCases
     switch (msg.getType()) {
       case BUILD_EVENT:
         handleBuildEvent(sessionId, msg.getBuildEvent());
@@ -100,16 +96,20 @@
         LOG.debug("Constant search task: cannot search in dumb mode");
       }
       else {
-        ApplicationManager.getApplication().runReadAction(new Runnable() {
-          @Override
-          public void run() {
-            try {
-              String qualifiedName = ownerClassName.replace('$', '.');
-              final PsiClass[] classes = JavaPsiFacade.getInstance(myProject).findClasses(qualifiedName, GlobalSearchScope.allScope(myProject));
-              if (isRemoved) {
+        final String qualifiedName = ownerClassName.replace('$', '.');
+        final PsiClass[] classes = ApplicationManager.getApplication().runReadAction(new Computable<PsiClass[]>() {
+          public PsiClass[] compute() {
+            return JavaPsiFacade.getInstance(myProject).findClasses(qualifiedName, GlobalSearchScope.allScope(myProject));
+          }
+        });
+
+        try {
+          if (isRemoved) {
+            ApplicationManager.getApplication().runReadAction(new Runnable() {
+              public void run() {
                 if (classes.length > 0) {
                   for (PsiClass aClass : classes) {
-                    final boolean success = performRemovedConstantSearch(aClass, fieldName, accessFlags, affectedPaths);
+                    final boolean success = aClass.isValid() && performRemovedConstantSearch(aClass, fieldName, accessFlags, affectedPaths);
                     if (!success) {
                       isSuccess.set(Boolean.FALSE);
                       break;
@@ -122,44 +122,49 @@
                   );
                 }
               }
-              else {
-                if (classes.length > 0) {
-                  boolean foundAtLeastOne = false;
+            });
+          }
+          else {
+            if (classes.length > 0) {
+              final Collection<PsiField> changedFields = ApplicationManager.getApplication().runReadAction(new Computable<Collection<PsiField>>() {
+                public Collection<PsiField> compute() {
+                  final List<PsiField> fields = new SmartList<PsiField>();
                   for (PsiClass aClass : classes) {
-                    PsiField changedField = null;
-                    for (PsiField psiField : aClass.getFields()) {
-                      if (fieldName.equals(psiField.getName())) {
-                        changedField = psiField;
-                        break;
-                      }
+                    if (!aClass.isValid()) {
+                      return Collections.emptyList();
                     }
-                    if (changedField == null) {
-                      continue;
-                    }
-                    foundAtLeastOne = true;
-                    final boolean success = performChangedConstantSearch(aClass, changedField, accessFlags, accessChanged, affectedPaths);
-                    if (!success) {
-                      isSuccess.set(Boolean.FALSE);
-                      break;
+                    final PsiField changedField = aClass.findFieldByName(fieldName, false);
+                    if (changedField != null) {
+                      fields.add(changedField);
                     }
                   }
-                  if (!foundAtLeastOne) {
-                    isSuccess.set(Boolean.FALSE);
-                    LOG.debug("Constant search task: field " + fieldName + " not found in classes " + qualifiedName);
-                  }
+                  return fields;
                 }
-                else {
-                  isSuccess.set(Boolean.FALSE);
-                  LOG.debug("Constant search task: class " + qualifiedName + " not found");
+              });
+              if (changedFields.isEmpty()) {
+                isSuccess.set(Boolean.FALSE);
+                LOG.debug("Constant search task: field " + fieldName + " not found in classes " + qualifiedName);
+              }
+              else {
+                for (final PsiField changedField : changedFields) {
+                  if (!accessChanged && ClsUtil.isPrivate(accessFlags)) {
+                    // optimization: don't need to search, cause may be used only in this class
+                    continue;
+                  }
+                  affectDirectUsages(changedField, accessFlags, accessChanged, affectedPaths);
                 }
               }
             }
-            catch (Throwable e) {
+            else {
               isSuccess.set(Boolean.FALSE);
-              LOG.debug("Constant search task: failed with message " + e.getMessage());
+              LOG.debug("Constant search task: class " + qualifiedName + " not found");
             }
           }
-        });
+        }
+        catch (Throwable e) {
+          isSuccess.set(Boolean.FALSE);
+          LOG.debug("Constant search task: failed with message " + e.getMessage());
+        }
       }
     }
     finally {
@@ -188,6 +193,7 @@
       // wait some time
       for (int idx = 0; idx < 5; idx++) {
         try {
+          //noinspection BusyWait
           Thread.sleep(10L);
         }
         catch (InterruptedException ignored) {
@@ -201,52 +207,13 @@
     return isDumb;
   }
 
-  private boolean performChangedConstantSearch(PsiClass aClass, PsiField field, int accessFlags, boolean isAccessibilityChange, Set<String> affectedPaths) {
-    if (!isAccessibilityChange && ClsUtil.isPrivate(accessFlags)) {
-      return true; // optimization: don't need to search, cause may be used only in this class
-    }
-    final Set<PsiElement> usages = new HashSet<PsiElement>();
-    try {
-      addUsages(field, usages, isAccessibilityChange);
-      for (final PsiElement usage : usages) {
-        affect(usage, affectedPaths);
-        //final PsiClass ownerClass = getOwnerClass(usage);
-        //if (ownerClass != null && !ownerClass.equals(aClass)) {
-        //  affect(ownerClass, affectedPaths);
-        //}
-        //else if (ownerClass == null) {
-        //  affect(usage, affectedPaths);
-        //}
-      }
-    }
-    catch (PsiInvalidElementAccessException ignored) {
-      LOG.debug("Constant search task: PIEAE thrown while searching of usages of changed constant");
-      return false;
-    }
-    catch (ProcessCanceledException ignored) {
-      LOG.debug("Constant search task: PCE thrown while searching of usages of changed constant");
-      return false;
-    }
-    return true;
-  }
 
-
-  private boolean performRemovedConstantSearch(@Nullable final PsiClass aClass, String fieldName, int accessFlags, final Set<String> affectedPaths) {
-    SearchScope searchScope = GlobalSearchScope.projectScope(myProject);
-    if (aClass != null && ClsUtil.isPackageLocal(accessFlags)) {
-      final PsiFile containingFile = aClass.getContainingFile();
-      if (containingFile instanceof PsiJavaFile) {
-        final String packageName = ((PsiJavaFile)containingFile).getPackageName();
-        final PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage(packageName);
-        if (aPackage != null) {
-          searchScope = PackageScope.packageScope(aPackage, false);
-          searchScope = searchScope.intersectWith(aClass.getUseScope());
-        }
-      }
-    }
+  private boolean performRemovedConstantSearch(@Nullable final PsiClass aClass, String fieldName, int fieldAccessFlags, final Set<String> affectedPaths) {
     final PsiSearchHelper psiSearchHelper = PsiSearchHelper.SERVICE.getInstance(myProject);
 
     final Ref<Boolean> result = new Ref<Boolean>(Boolean.TRUE);
+    final PsiFile fieldContainingFile = aClass != null? aClass.getContainingFile() : null;
+
     processIdentifiers(psiSearchHelper, new PsiElementProcessor<PsiIdentifier>() {
       @Override
       public boolean execute(@NotNull PsiIdentifier identifier) {
@@ -254,9 +221,13 @@
           final PsiElement parent = identifier.getParent();
           if (parent instanceof PsiReferenceExpression) {
             final PsiClass ownerClass = getOwnerClass(parent);
-            if (ownerClass != null /*&& !ownerClass.equals(aClass)*/) {
-              if (ownerClass.getQualifiedName() != null) {
-                affect(ownerClass, affectedPaths);
+            if (ownerClass != null && ownerClass.getQualifiedName() != null) {
+              final PsiFile usageFile = ownerClass.getContainingFile();
+              if (usageFile != null && !usageFile.equals(fieldContainingFile)) {
+                final VirtualFile vFile = usageFile.getOriginalFile().getVirtualFile();
+                if (vFile != null) {
+                  affectedPaths.add(vFile.getPath());
+                }
               }
             }
           }
@@ -268,19 +239,25 @@
           return false;
         }
       }
-    }, fieldName, searchScope, UsageSearchContext.IN_CODE);
+    }, fieldName, getSearchScope(aClass, fieldAccessFlags), UsageSearchContext.IN_CODE);
 
     return result.get();
   }
 
-  private static void affect(PsiElement ownerClass, Set<String> affectedPaths) {
-    final PsiFile containingPsi = ownerClass.getContainingFile();
-    if (containingPsi != null) {
-      final VirtualFile vFile = containingPsi.getOriginalFile().getVirtualFile();
-      if (vFile != null) {
-        affectedPaths.add(vFile.getPath());
+  private SearchScope getSearchScope(PsiClass aClass, int fieldAccessFlags) {
+    SearchScope searchScope = GlobalSearchScope.projectScope(myProject);
+    if (aClass != null && ClsUtil.isPackageLocal(fieldAccessFlags)) {
+      final PsiFile containingFile = aClass.getContainingFile();
+      if (containingFile instanceof PsiJavaFile) {
+        final String packageName = ((PsiJavaFile)containingFile).getPackageName();
+        final PsiPackage aPackage = JavaPsiFacade.getInstance(myProject).findPackage(packageName);
+        if (aPackage != null) {
+          searchScope = PackageScope.packageScope(aPackage, false);
+          searchScope = searchScope.intersectWith(aClass.getUseScope());
+        }
       }
     }
+    return searchScope;
   }
 
   private static boolean processIdentifiers(PsiSearchHelper helper, @NotNull final PsiElementProcessor<PsiIdentifier> processor, @NotNull final String identifier, @NotNull SearchScope searchScope, short searchContext) {
@@ -290,35 +267,59 @@
         return !(element instanceof PsiIdentifier) || processor.execute((PsiIdentifier)element);
       }
     };
-    return helper.processElementsWithWord(processor1, searchScope, identifier, searchContext, true);
+    return helper.processElementsWithWord(processor1, searchScope, identifier, searchContext, true, false);
   }
 
-  private void addUsages(PsiField psiField, Collection<PsiElement> usages, final boolean ignoreAccessScope) throws ProcessCanceledException {
-    final int count = myConstantSearchesCount;
-    if (count > MAX_CONSTANT_SEARCHES) {
-      throw new ProcessCanceledException();
-    }
-    Collection<PsiReference> references = mySearcher.findReferences(psiField, ignoreAccessScope)/*doFindReferences(searchHelper, psiField)*/;
-
-    myConstantSearchesCount++;
-
-    for (final PsiReference ref : references) {
-      if (!(ref instanceof PsiReferenceExpression)) {
-        continue;
-      }
-      PsiElement e = ref.getElement();
-      usages.add(e);
-      PsiField ownerField = getOwnerField(e);
-      if (ownerField != null) {
-        if (ownerField.hasModifierProperty(PsiModifier.FINAL)) {
-          PsiExpression initializer = ownerField.getInitializer();
-          if (initializer != null && PsiUtil.isConstantExpression(initializer)) {
-            // if the field depends on the compile-time-constant expression and is itself final
-            addUsages(ownerField, usages, ignoreAccessScope);
+  private void affectDirectUsages(final PsiField psiField, final int fieldAccessFlags, final boolean ignoreAccessScope, final Set<String> affectedPaths) throws ProcessCanceledException {
+    ApplicationManager.getApplication().runReadAction(new Runnable() {
+      public void run() {
+        if (psiField.isValid()) {
+          final PsiFile fieldContainingFile = psiField.getContainingFile();
+          final Set<PsiFile> processedFiles = new HashSet<PsiFile>();
+          if (fieldContainingFile != null) {
+            processedFiles.add(fieldContainingFile);
+          }
+          // if field is invalid, the file might be changed, so next time it is compiled,
+          // the constant value change, if any, will be processed
+          final Collection<PsiReferenceExpression> references = doFindReferences(psiField, fieldAccessFlags, ignoreAccessScope);
+          for (final PsiReferenceExpression ref : references) {
+            final PsiElement usage = ref.getElement();
+            final PsiFile containingPsi = usage.getContainingFile();
+            if (containingPsi != null && processedFiles.add(containingPsi)) {
+              final VirtualFile vFile = containingPsi.getOriginalFile().getVirtualFile();
+              if (vFile != null) {
+                affectedPaths.add(vFile.getPath());
+              }
+            }
           }
         }
       }
-    }
+    });
+  }
+
+  private Collection<PsiReferenceExpression> doFindReferences(final PsiField psiField, int fieldAccessFlags, boolean ignoreAccessScope) {
+    final SmartList<PsiReferenceExpression> result = new SmartList<PsiReferenceExpression>();
+
+    final SearchScope searchScope = ignoreAccessScope? GlobalSearchScope.projectScope(myProject) : getSearchScope(psiField.getContainingClass(), fieldAccessFlags);
+
+    processIdentifiers(PsiSearchHelper.SERVICE.getInstance(myProject), new PsiElementProcessor<PsiIdentifier>() {
+      @Override
+      public boolean execute(@NotNull PsiIdentifier identifier) {
+        final PsiElement parent = identifier.getParent();
+        if (parent instanceof PsiReferenceExpression) {
+          final PsiReferenceExpression refExpression = (PsiReferenceExpression)parent;
+          if (refExpression.isReferenceTo(psiField)) {
+            synchronized (result) {
+              // processor's code may be invoked from multiple threads
+              result.add(refExpression);
+            }
+          }
+        }
+        return true;
+      }
+    }, psiField.getName(), searchScope, UsageSearchContext.IN_CODE);
+
+    return result;
   }
 
   @Nullable
@@ -340,18 +341,4 @@
     return null;
   }
 
-  @Nullable
-  private static PsiField getOwnerField(PsiElement element) {
-    while (!(element instanceof PsiFile)) {
-      if (element instanceof PsiClass) {
-        break;
-      }
-      if (element instanceof PsiField) { // top-level class
-        return (PsiField)element;
-      }
-      element = element.getParent();
-    }
-    return null;
-  }
-
 }
diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/SetValueAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/SetValueAction.java
index 04f9dcb..8adff3f 100644
--- a/java/debugger/impl/src/com/intellij/debugger/actions/SetValueAction.java
+++ b/java/debugger/impl/src/com/intellij/debugger/actions/SetValueAction.java
@@ -481,8 +481,10 @@
 
     stateManager.addListener(new DebuggerContextListener() {
       public void changeEvent(DebuggerContextImpl newContext, int event) {
-        stateManager.removeListener(this);
-        editor.cancelEditing();
+        if (event != DebuggerSession.EVENT_THREADS_REFRESH) {
+          stateManager.removeListener(this);
+          editor.cancelEditing();
+        }
       }
     });
 
diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ToggleFieldBreakpointAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ToggleFieldBreakpointAction.java
index 54d1545..39a3977 100644
--- a/java/debugger/impl/src/com/intellij/debugger/actions/ToggleFieldBreakpointAction.java
+++ b/java/debugger/impl/src/com/intellij/debugger/actions/ToggleFieldBreakpointAction.java
@@ -19,8 +19,11 @@
 import com.intellij.debugger.DebuggerManagerEx;
 import com.intellij.debugger.InstanceFilter;
 import com.intellij.debugger.SourcePosition;
+import com.intellij.debugger.engine.DebugProcessImpl;
 import com.intellij.debugger.engine.DebuggerUtils;
+import com.intellij.debugger.engine.events.DebuggerContextCommandImpl;
 import com.intellij.debugger.engine.requests.RequestManagerImpl;
+import com.intellij.debugger.impl.DebuggerContextImpl;
 import com.intellij.debugger.impl.DebuggerSession;
 import com.intellij.debugger.ui.breakpoints.Breakpoint;
 import com.intellij.debugger.ui.breakpoints.BreakpointManager;
@@ -29,12 +32,14 @@
 import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
 import com.intellij.debugger.ui.impl.watch.FieldDescriptorImpl;
 import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.fileEditor.FileEditorManager;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.fileTypes.StdFileTypes;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
 import com.intellij.psi.search.GlobalSearchScope;
@@ -83,7 +88,10 @@
 
             RequestManagerImpl.createRequests(fieldBreakpoint);
 
-            manager.editBreakpoint(fieldBreakpoint, CommonDataKeys.EDITOR.getData(e.getDataContext()));
+            final Editor editor = CommonDataKeys.EDITOR.getData(e.getDataContext());
+            if (editor != null) {
+              manager.editBreakpoint(fieldBreakpoint, editor);
+            }
           }
         }
         else {
@@ -126,7 +134,7 @@
   @Nullable
   public static SourcePosition getPlace(AnActionEvent event) {
     final DataContext dataContext = event.getDataContext();
-    Project project = event.getData(CommonDataKeys.PROJECT);
+    final Project project = event.getData(CommonDataKeys.PROJECT);
     if(project == null) {
       return null;
     }
@@ -142,8 +150,28 @@
 
     final DebuggerTreeNodeImpl selectedNode = DebuggerAction.getSelectedNode(dataContext);
     if(selectedNode != null && selectedNode.getDescriptor() instanceof FieldDescriptorImpl) {
-      FieldDescriptorImpl descriptor = (FieldDescriptorImpl)selectedNode.getDescriptor();
-      return descriptor.getSourcePosition(project, DebuggerAction.getDebuggerContext(dataContext));
+      final DebuggerContextImpl debuggerContext = DebuggerAction.getDebuggerContext(dataContext);
+      final DebugProcessImpl debugProcess = debuggerContext.getDebugProcess();
+      if (debugProcess != null) { // if there is an active debugsession
+        final Ref<SourcePosition> positionRef = new Ref<SourcePosition>(null);
+        debugProcess.getManagerThread().invokeAndWait(new DebuggerContextCommandImpl(debuggerContext) {
+          public Priority getPriority() {
+            return Priority.HIGH;
+          }
+          public void threadAction() {
+            ApplicationManager.getApplication().runReadAction(new Runnable() {
+              public void run() {
+                final FieldDescriptorImpl descriptor = (FieldDescriptorImpl)selectedNode.getDescriptor();
+                positionRef.set(descriptor.getSourcePosition(project, debuggerContext));
+              }
+            });
+          }
+        });
+        final SourcePosition sourcePosition = positionRef.get();
+        if (sourcePosition != null) {
+          return sourcePosition;
+        }
+      }
     }
 
     if(DebuggerAction.isContextView(event)) {
diff --git a/java/debugger/impl/src/com/intellij/debugger/actions/ViewTextAction.java b/java/debugger/impl/src/com/intellij/debugger/actions/ViewTextAction.java
index 9c4ec5d..d539de5 100644
--- a/java/debugger/impl/src/com/intellij/debugger/actions/ViewTextAction.java
+++ b/java/debugger/impl/src/com/intellij/debugger/actions/ViewTextAction.java
@@ -19,14 +19,10 @@
 import com.intellij.debugger.ui.impl.watch.DebuggerTreeNodeImpl;
 import com.intellij.debugger.ui.impl.watch.NodeDescriptorImpl;
 import com.intellij.debugger.ui.impl.watch.ValueDescriptorImpl;
-import com.intellij.openapi.editor.Document;
-import com.intellij.openapi.editor.EditorFactory;
-import com.intellij.openapi.editor.ex.EditorEx;
-import com.intellij.openapi.editor.impl.DocumentImpl;
-import com.intellij.openapi.fileTypes.FileTypes;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.ui.EditorTextField;
+import com.intellij.xdebugger.impl.ui.TextViewer;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
@@ -55,7 +51,7 @@
       setCancelButtonText("Close");
       setCrossClosesWindow(true);
 
-      myTextViewer = new TextViewer(project);
+      myTextViewer = new TextViewer(project, true, true);
       init();
     }
 
@@ -78,33 +74,5 @@
       panel.setPreferredSize(new Dimension(300, 200));
       return panel;
     }
-
   }
-
-
-  private static class TextViewer extends EditorTextField {
-
-    private TextViewer(Project project) {
-      super(createDocument(), project, FileTypes.PLAIN_TEXT, true, false);
-    }
-
-    private static Document createDocument() {
-      final Document document = EditorFactory.getInstance().createDocument("");
-      if (document instanceof DocumentImpl) {
-        ((DocumentImpl)document).setAcceptSlashR(true);
-      }
-      return document;
-    }
-
-    protected EditorEx createEditor() {
-      final EditorEx editor = super.createEditor();
-      editor.setHorizontalScrollbarVisible(true);
-      editor.setVerticalScrollbarVisible(true);
-      editor.setEmbeddedIntoDialogWrapper(true);
-      editor.getComponent().setPreferredSize(null);
-      editor.getSettings().setUseSoftWraps(true);
-      return editor;
-    }
-  }
-
 }
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java
index 58f4c7b..f9c7b84 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessEvents.java
@@ -22,6 +22,7 @@
 import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
 import com.intellij.debugger.engine.requests.LocatableEventRequestor;
 import com.intellij.debugger.engine.requests.MethodReturnValueWatcher;
+import com.intellij.debugger.impl.DebuggerSession;
 import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
 import com.intellij.debugger.jdi.VirtualMachineProxyImpl;
 import com.intellij.debugger.requests.Requestor;
@@ -39,7 +40,6 @@
 import com.intellij.openapi.ui.MessageType;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.Pair;
-import com.intellij.openapi.util.registry.Registry;
 import com.intellij.xdebugger.impl.XDebugSessionImpl;
 import com.sun.jdi.InternalException;
 import com.sun.jdi.ThreadReference;
@@ -182,7 +182,7 @@
             getManagerThread().invokeAndWait(new DebuggerCommandImpl() {
               protected void action() throws Exception {
                 
-                if (eventSet.suspendPolicy() == EventRequest.SUSPEND_ALL && !enableBreakpointsDuringEvaluation()) {
+                if (eventSet.suspendPolicy() == EventRequest.SUSPEND_ALL && !DebuggerSession.enableBreakpointsDuringEvaluation()) {
                   // check if there is already one request with policy SUSPEND_ALL
                   for (SuspendContextImpl context : getSuspendManager().getEventContexts()) {
                     if (context.getSuspendPolicy() == EventRequest.SUSPEND_ALL) {
@@ -420,7 +420,7 @@
         final SuspendManager suspendManager = getSuspendManager();
         SuspendContextImpl evaluatingContext = SuspendManagerUtil.getEvaluatingContext(suspendManager, getSuspendContext().getThread());
 
-        if (evaluatingContext != null && !enableBreakpointsDuringEvaluation()) {
+        if (evaluatingContext != null && !DebuggerSession.enableBreakpointsDuringEvaluation()) {
           // is inside evaluation, so ignore any breakpoints
           suspendManager.voteResume(suspendContext);
           return;
@@ -476,10 +476,6 @@
     });
   }
 
-  private static boolean enableBreakpointsDuringEvaluation() {
-    return Registry.is("debugger.enable.breakpoints.during.evaluation");
-  }
-
   private void processDefaultEvent(SuspendContextImpl suspendContext) {
     preprocessEvent(suspendContext, null);
     getSuspendManager().voteResume(suspendContext);
diff --git a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
index dc9d1e9..a5b1be2 100644
--- a/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/engine/DebugProcessImpl.java
@@ -99,7 +99,7 @@
   private final Project myProject;
   private final RequestManagerImpl myRequestManager;
 
-  private VirtualMachineProxyImpl myVirtualMachineProxy = null;
+  private volatile VirtualMachineProxyImpl myVirtualMachineProxy = null;
   protected EventDispatcher<DebugProcessListener> myDebugProcessDispatcher = EventDispatcher.create(DebugProcessListener.class);
   protected EventDispatcher<EvaluationListener> myEvaluationDispatcher = EventDispatcher.create(EvaluationListener.class);
 
@@ -685,11 +685,13 @@
   }
 
   public boolean canRedefineClasses() {
-    return myVirtualMachineProxy != null && myVirtualMachineProxy.canRedefineClasses();
+    final VirtualMachineProxyImpl vm = myVirtualMachineProxy;
+    return vm != null && vm.canRedefineClasses();
   }
 
   public boolean canWatchFieldModification() {
-    return myVirtualMachineProxy != null && myVirtualMachineProxy.canWatchFieldModification();
+    final VirtualMachineProxyImpl vm = myVirtualMachineProxy;
+    return vm != null && vm.canWatchFieldModification();
   }
 
   public boolean isInInitialState() {
@@ -714,10 +716,11 @@
 
   public VirtualMachineProxyImpl getVirtualMachineProxy() {
     DebuggerManagerThreadImpl.assertIsManagerThread();
-    if (myVirtualMachineProxy == null) {
+    final VirtualMachineProxyImpl vm = myVirtualMachineProxy;
+    if (vm == null) {
       throw new VMDisconnectedException();
     }
-    return myVirtualMachineProxy;
+    return vm;
   }
 
   public void appendPositionManager(final PositionManager positionManager) {
@@ -1820,7 +1823,8 @@
   }
 
   public boolean isPausePressed() {
-    return myVirtualMachineProxy != null && myVirtualMachineProxy.isPausePressed();
+    final VirtualMachineProxyImpl vm = myVirtualMachineProxy;
+    return vm != null && vm.isPausePressed();
   }
 
   public DebuggerCommandImpl createPauseCommand() {
diff --git a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java
index aa24a43..19de95a 100644
--- a/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java
+++ b/java/debugger/impl/src/com/intellij/debugger/impl/DebuggerSession.java
@@ -21,6 +21,7 @@
 import com.intellij.debugger.engine.evaluation.EvaluateException;
 import com.intellij.debugger.engine.evaluation.EvaluationListener;
 import com.intellij.debugger.engine.events.SuspendContextCommandImpl;
+import com.intellij.debugger.engine.jdi.StackFrameProxy;
 import com.intellij.debugger.engine.requests.RequestManagerImpl;
 import com.intellij.debugger.jdi.StackFrameProxyImpl;
 import com.intellij.debugger.jdi.ThreadReferenceProxyImpl;
@@ -43,9 +44,11 @@
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Computable;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.Pair;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.psi.PsiCompiledElement;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiFile;
@@ -284,7 +287,12 @@
   public void resume() {
     final SuspendContextImpl suspendContext = getSuspendContext();
     if(suspendContext != null) {
-      mySteppingThroughThreads.clear();
+      if (suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_ALL) {
+        mySteppingThroughThreads.clear();
+      }
+      else {
+        mySteppingThroughThreads.remove(suspendContext.getThread());
+      }
       resetIgnoreStepFiltersFlag();
       resumeAction(myDebugProcess.createResumeCommand(suspendContext), EVENT_RESUME);
     }
@@ -408,6 +416,15 @@
         LOG.debug("paused");
       }
 
+      if (!shouldSetAsActiveContext(suspendContext)) {
+        DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() {
+          public void run() {
+            getContextManager().fireStateChanged(getContextManager().getContext(), EVENT_THREADS_REFRESH);
+          }
+        });
+        return;
+      }
+
       ThreadReferenceProxyImpl currentThread   = suspendContext.getThread();
       final StackFrameContext positionContext;
 
@@ -503,9 +520,10 @@
             else if (sourceMissing) {
               // adjust position to be position of the breakpoint in order to show the real originator of the event
               position = breakpointPosition;
+              final StackFrameProxy frameProxy = positionContext.getFrameProxy();
               String className;
               try {
-                className = positionContext.getFrameProxy().location().declaringType().name();
+                className = frameProxy != null? frameProxy.location().declaringType().name() : "";
               }
               catch (EvaluateException e) {
                 className = "";
@@ -527,6 +545,23 @@
       });
     }
 
+    private boolean shouldSetAsActiveContext(final SuspendContextImpl suspendContext) {
+      final ThreadReferenceProxyImpl newThread = suspendContext.getThread();
+      if (newThread == null || suspendContext.getSuspendPolicy() == EventRequest.SUSPEND_ALL || isSteppingThrough(newThread)) {
+        return true;
+      }
+      final SuspendContextImpl currentSuspendContext = getContextManager().getContext().getSuspendContext();
+      if (currentSuspendContext == null) {
+        return true;
+      }
+      if (enableBreakpointsDuringEvaluation()) {
+        final ThreadReferenceProxyImpl currentThread = currentSuspendContext.getThread();
+        return currentThread == null || Comparing.equal(currentThread.getThreadReference(), newThread.getThreadReference());
+      }
+      return false;
+    }
+
+
     public void resumed(final SuspendContextImpl suspendContext) {
       final SuspendContextImpl currentContext = getProcess().getSuspendManager().getPausedContext();
       DebuggerInvocationUtil.invokeLater(getProject(), new Runnable() {
@@ -626,4 +661,9 @@
       });
     }
   }
+
+  public static boolean enableBreakpointsDuringEvaluation() {
+    return Registry.is("debugger.enable.breakpoints.during.evaluation");
+  }
+
 }
diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java
index 1960766..a78cb13 100644
--- a/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java
+++ b/java/debugger/impl/src/com/intellij/debugger/ui/breakpoints/LineBreakpoint.java
@@ -31,7 +31,6 @@
 import com.intellij.debugger.impl.DebuggerUtilsEx;
 import com.intellij.debugger.jdi.StackFrameProxyImpl;
 import com.intellij.icons.AllIcons;
-import com.intellij.lang.java.JavaLanguage;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
@@ -73,7 +72,7 @@
   private static final Logger LOG = Logger.getInstance("#com.intellij.debugger.ui.breakpoints.LineBreakpoint");
 
   @Nullable
-  private OwnerMethod myOwnerMethod;
+  private String myOwnerMethodName;
   public static final @NonNls Key<LineBreakpoint> CATEGORY = BreakpointCategory.lookup("line_breakpoints");
 
   protected LineBreakpoint(Project project) {
@@ -138,7 +137,7 @@
       final RangeHighlighter highlighter = getHighlighter();
       offset = highlighter != null? highlighter.getStartOffset() : -1;
     }
-    myOwnerMethod = findOwnerMethod(file, offset);
+    myOwnerMethodName = findOwnerMethod(file, offset);
   }
 
   @Override
@@ -211,18 +210,6 @@
   }
 
   protected boolean acceptLocation(DebugProcessImpl debugProcess, ReferenceType classType, Location loc) {
-    final OwnerMethod owner = myOwnerMethod;
-    if (owner != null && owner.isJavaFile) {
-      // Additional filtering applicable to java files only.
-      // Consider:
-      //  proc(()->{System.out.println("Task 1");}, ()->{System.out.println("Task 2");});  <breakpoint at this line>
-      //
-      // there will be 3 locations for this line: one corresponding to calling method, and two locations from
-      // the lambda expression implementation methods.
-      // Without additional filtering, breakpoint request will be set on each location,
-      // while we do not need to stop in lambda expressions here
-      return owner.matches(loc);
-    }
     return true;
   }
 
@@ -438,16 +425,16 @@
   }
 
   @Nullable
-  private static OwnerMethod findOwnerMethod(final PsiFile file, final int offset) {
+  private static String findOwnerMethod(final PsiFile file, final int offset) {
     if (offset < 0 || file instanceof JspFile) {
       return null;
     }
     if (file instanceof PsiClassOwner) {
-      return ApplicationManager.getApplication().runReadAction(new Computable<OwnerMethod>() {
+      return ApplicationManager.getApplication().runReadAction(new Computable<String>() {
         @Override
-        public OwnerMethod compute() {
+        public String compute() {
           final PsiMethod method = DebuggerUtilsEx.findPsiMethod(file, offset);
-          return method != null? new OwnerMethod(method, file instanceof PsiJavaFile && JavaLanguage.INSTANCE.equals(file.getLanguage())) : null;
+          return method != null? method.getName() : null;
         }
       });
     }
@@ -577,28 +564,7 @@
 
   @Nullable
   public String getMethodName() {
-    final OwnerMethod owner = myOwnerMethod;
-    return owner != null? owner.name : null;
+    return myOwnerMethodName;
   }
 
-  private static final class OwnerMethod {
-    @NotNull
-    final String name;
-    final boolean isConstructor;
-    final boolean isJavaFile;
-
-    OwnerMethod(@NotNull PsiMethod method, boolean isJavaFile) {
-      this(method.getName(), method.isConstructor(), isJavaFile);
-    }
-
-    OwnerMethod(@NotNull String name, boolean isConstructor, boolean isJavaFile) {
-      this.name = name;
-      this.isConstructor = isConstructor;
-      this.isJavaFile = isJavaFile;
-    }
-
-    boolean matches(Location loc) {
-      return isConstructor? loc.method().isConstructor() : name.equals(loc.method().name());
-    }
-  }
 }
diff --git a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java
index 586dadf..4b3f145 100644
--- a/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java
+++ b/java/debugger/impl/src/com/intellij/debugger/ui/impl/watch/FieldDescriptorImpl.java
@@ -25,7 +25,6 @@
 import com.intellij.debugger.engine.evaluation.EvaluateException;
 import com.intellij.debugger.engine.evaluation.EvaluateExceptionUtil;
 import com.intellij.debugger.engine.evaluation.EvaluationContextImpl;
-import com.intellij.debugger.engine.events.DebuggerContextCommandImpl;
 import com.intellij.debugger.impl.DebuggerContextImpl;
 import com.intellij.debugger.impl.DebuggerSession;
 import com.intellij.debugger.impl.PositionUtil;
@@ -34,8 +33,6 @@
 import com.intellij.debugger.ui.tree.NodeDescriptor;
 import com.intellij.debugger.ui.tree.render.ClassRenderer;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Computable;
-import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.search.GlobalSearchScope;
@@ -104,40 +101,20 @@
         // trying to search, assuming declaring class is an anonymous class
         final DebugProcessImpl debugProcess = context.getDebugProcess();
         if (debugProcess != null) {
-          final Computable<PsiClass> classComputable = new Computable<PsiClass>() {
-            public PsiClass compute() {
-              try {
-                final List<Location> locations = type.allLineLocations();
-                if (!locations.isEmpty()) {
-                  // important: use the last location to be sure the position will be within the anonymous class
-                  final Location lastLocation = locations.get(locations.size() - 1);
-                  final SourcePosition position = debugProcess.getPositionManager().getSourcePosition(lastLocation);
-                  if (position != null) {
-                    return JVMNameUtil.getClassAt(position);
-                  }
-                }
+          try {
+            final List<Location> locations = type.allLineLocations();
+            if (!locations.isEmpty()) {
+              // important: use the last location to be sure the position will be within the anonymous class
+              final Location lastLocation = locations.get(locations.size() - 1);
+              final SourcePosition position = debugProcess.getPositionManager().getSourcePosition(lastLocation);
+              if (position != null) {
+                aClass = JVMNameUtil.getClassAt(position);
               }
-              catch (AbsentInformationException ignored) {
-              }
-              catch (ClassNotPreparedException ignored) {
-              }
-              return null;
             }
-          };
-          if (!DebuggerManagerThreadImpl.isManagerThread()) {
-            final Ref<PsiClass> classRef = new Ref<PsiClass>(null);
-            debugProcess.getManagerThread().invokeAndWait(new DebuggerContextCommandImpl(context) {
-              public Priority getPriority() {
-                return Priority.HIGH;
-              }
-              public void threadAction() {
-                classRef.set(classComputable.compute());
-              }
-            });
-            aClass = classRef.get();
           }
-          else {
-            aClass = classComputable.compute();
+          catch (AbsentInformationException ignored) {
+          }
+          catch (ClassNotPreparedException ignored) {
           }
         }
       }
diff --git a/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java b/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java
index c208872..00b7549 100644
--- a/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java
+++ b/java/debugger/impl/src/org/jetbrains/java/debugger/breakpoints/JavaBreakpointType.java
@@ -2,11 +2,8 @@
 
 import com.intellij.debugger.DebuggerBundle;
 import com.intellij.debugger.engine.DebuggerUtils;
-import com.intellij.facet.FacetManager;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.fileTypes.StdFileTypes;
-import com.intellij.openapi.module.Module;
-import com.intellij.openapi.module.ModuleUtilCore;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiFile;
@@ -31,18 +28,8 @@
 
   @Override
   public boolean canPutAt(@NotNull final VirtualFile file, final int line, @NotNull Project project) {
-    if (SystemProperties.getBooleanProperty("java.debugger.xBreakpoint", false)) {
-      boolean result = doCanPutAt(PsiManager.getInstance(project).findFile(file));
-
-      // todo now applicable only if modules has facets, remove this check when java xbreakpoint will work
-      if (result && SystemProperties.getBooleanProperty("java.debugger.xBreakpoint.onlyIfHasFacets", false)) {
-        Module module = ModuleUtilCore.findModuleForFile(file, project);
-        return module != null && FacetManager.getInstance(module).getAllFacets().length > 0;
-      }
-
-      return result;
-    }
-    return false;
+    return SystemProperties.getBooleanProperty("java.debugger.xBreakpoint", false) &&
+           doCanPutAt(PsiManager.getInstance(project).findFile(file));
   }
 
   @Override
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java
index 0e522a8..2552631 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/BaseLibrariesConfigurable.java
@@ -47,6 +47,7 @@
 
 import javax.swing.tree.DefaultTreeModel;
 import javax.swing.tree.TreeNode;
+import javax.swing.tree.TreePath;
 import java.util.*;
 
 public abstract class BaseLibrariesConfigurable extends BaseStructureConfigurable  {
@@ -258,14 +259,23 @@
   }
 
   public void removeLibrary(@NotNull LibraryProjectStructureElement element) {
-    getModelProvider().getModifiableModel().removeLibrary(element.getLibrary());
-    myContext.getDaemonAnalyzer().removeElement(element);
-    final MyNode node = findNodeByObject(myRoot, element.getLibrary());
-    if (node != null) {
-      removePaths(TreeUtil.getPathFromRoot(node));
-    }
+    removeLibraries(Collections.singletonList(element));
   }
 
+  public void removeLibraries(@NotNull List<LibraryProjectStructureElement> libraries) {
+    List<TreePath> pathsToRemove = new ArrayList<TreePath>();
+    for (LibraryProjectStructureElement element : libraries) {
+      getModelProvider().getModifiableModel().removeLibrary(element.getLibrary());
+      MyNode node = findNodeByObject(myRoot, element.getLibrary());
+      if (node != null) {
+        pathsToRemove.add(TreeUtil.getPathFromRoot(node));
+      }
+    }
+    myContext.getDaemonAnalyzer().removeElements(libraries);
+    removePaths(pathsToRemove.toArray(new TreePath[pathsToRemove.size()]));
+  }
+
+
   @Override
   protected boolean removeLibrary(final Library library) {
     final LibraryTable table = library.getTable();
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java
index 930cb51..1fc3dbd 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/LibraryProjectStructureElement.java
@@ -41,6 +41,7 @@
 
 import java.lang.reflect.InvocationHandler;
 import java.lang.reflect.Proxy;
+import java.util.ArrayList;
 import java.util.Arrays;
 import java.util.Collections;
 import java.util.List;
@@ -148,7 +149,7 @@
 
   @Override
   public ProjectStructureProblemDescription createUnusedElementWarning() {
-    final List<ConfigurationErrorQuickFix> fixes = Arrays.asList(new AddLibraryToDependenciesFix(), new RemoveLibraryFix());
+    final List<ConfigurationErrorQuickFix> fixes = Arrays.asList(new AddLibraryToDependenciesFix(), new RemoveLibraryFix(), new RemoveAllUnusedLibrariesFix());
     return new ProjectStructureProblemDescription("Library '" + StringUtil.escapeXml(myLibrary.getName()) + "'" + " is not used", null, createPlace(),
                                                   ProjectStructureProblemType.unused("unused-library"), ProjectStructureProblemDescription.ProblemLevel.PROJECT,
                                                   fixes, false);
@@ -225,4 +226,24 @@
       BaseLibrariesConfigurable.getInstance(myContext.getProject(), myLibrary.getTable().getTableLevel()).removeLibrary(LibraryProjectStructureElement.this);
     }
   }
+
+  private class RemoveAllUnusedLibrariesFix extends ConfigurationErrorQuickFix {
+    private RemoveAllUnusedLibrariesFix() {
+      super("Remove All Unused Libraries");
+    }
+
+    @Override
+    public void performFix() {
+      BaseLibrariesConfigurable configurable = BaseLibrariesConfigurable.getInstance(myContext.getProject(), LibraryTablesRegistrar.PROJECT_LEVEL);
+      Library[] libraries = configurable.getModelProvider().getModifiableModel().getLibraries();
+      List<LibraryProjectStructureElement> toRemove = new ArrayList<LibraryProjectStructureElement>();
+      for (Library library : libraries) {
+        LibraryProjectStructureElement libraryElement = new LibraryProjectStructureElement(myContext, library);
+        if (myContext.getDaemonAnalyzer().getUsages(libraryElement).isEmpty()) {
+          toRemove.add(libraryElement);
+        }
+      }
+      configurable.removeLibraries(toRemove);
+    }
+  }
 }
diff --git a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectStructureDaemonAnalyzer.java b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectStructureDaemonAnalyzer.java
index 91183b9b..97ed5b0 100644
--- a/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectStructureDaemonAnalyzer.java
+++ b/java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/projectRoot/daemon/ProjectStructureDaemonAnalyzer.java
@@ -7,13 +7,13 @@
 import com.intellij.openapi.roots.ui.configuration.projectRoot.StructureConfigurableContext;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.MultiValuesMap;
+import com.intellij.util.Alarm;
 import com.intellij.util.EventDispatcher;
 import com.intellij.util.ui.update.MergingUpdateQueue;
 import com.intellij.util.ui.update.Update;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import javax.swing.*;
 import java.util.*;
 import java.util.concurrent.atomic.AtomicBoolean;
 
@@ -29,6 +29,7 @@
   private final Set<ProjectStructureElement> myElementsToShowWarningIfUnused = new HashSet<ProjectStructureElement>();
   private final Map<ProjectStructureElement, ProjectStructureProblemDescription> myWarningsAboutUnused = new HashMap<ProjectStructureElement, ProjectStructureProblemDescription>();
   private final MergingUpdateQueue myAnalyzerQueue;
+  private final MergingUpdateQueue myResultsUpdateQueue;
   private final EventDispatcher<ProjectStructureDaemonAnalyzerListener> myDispatcher = EventDispatcher.create(ProjectStructureDaemonAnalyzerListener.class);
   private final AtomicBoolean myStopped = new AtomicBoolean(false);
   private final ProjectConfigurationProblems myProjectConfigurationProblems;
@@ -36,7 +37,9 @@
   public ProjectStructureDaemonAnalyzer(StructureConfigurableContext context) {
     Disposer.register(context, this);
     myProjectConfigurationProblems = new ProjectConfigurationProblems(this, context);
-    myAnalyzerQueue = new MergingUpdateQueue("Project Structure Daemon Analyzer", 300, false, null, this, null, false);
+    myAnalyzerQueue = new MergingUpdateQueue("Project Structure Daemon Analyzer", 300, false, null, this, null, Alarm.ThreadToUse.POOLED_THREAD);
+    myResultsUpdateQueue = new MergingUpdateQueue("Project Structure Analysis Results Updater", 300, false, MergingUpdateQueue.ANY_COMPONENT,
+                                                  this, null, Alarm.ThreadToUse.SWING_THREAD);
   }
 
   private void doUpdate(final ProjectStructureElement element, final boolean check, final boolean collectUsages) {
@@ -63,21 +66,7 @@
         ProjectStructureValidator.check(element, problemsHolder);
       }
     }.execute();
-    invokeLater(new Runnable() {
-      @Override
-      public void run() {
-        if (myStopped.get()) return;
-
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("updating problems for " + element);
-        }
-        final ProjectStructureProblemDescription warning = myWarningsAboutUnused.get(element);
-        if (warning != null)
-          problemsHolder.registerProblem(warning);
-        myProblemHolders.put(element, problemsHolder);
-        myDispatcher.getMulticaster().problemsChanged(element);
-      }
-    });
+    myResultsUpdateQueue.queue(new ProblemsComputedUpdate(element, problemsHolder));
   }
 
   private void doCollectUsages(final ProjectStructureElement element) {
@@ -92,18 +81,9 @@
         result.setResult(getUsagesInElement(element));
       }
     }.execute().getResultObject();
-
-    invokeLater(new Runnable() {
-      @Override
-      public void run() {
-        if (myStopped.get() || usages == null) return;
-
-        if (LOG.isDebugEnabled()) {
-          LOG.debug("updating usages for " + element);
-        }
-        updateUsages(element, usages);
-      }
-    });
+    if (usages != null) {
+      myResultsUpdateQueue.queue(new UsagesCollectedUpdate(element, usages));
+    }
   }
 
   private static List<ProjectStructureElementUsage> getUsagesInElement(final ProjectStructureElement element) {
@@ -116,11 +96,7 @@
       addUsage(usage);
     }
     myElementWithNotCalculatedUsages.remove(element);
-    reportUnusedElements();
-  }
-
-  private static void invokeLater(Runnable runnable) {
-    SwingUtilities.invokeLater(runnable);
+    myResultsUpdateQueue.queue(new ReportUnusedElementsUpdate());
   }
 
   public void queueUpdate(@NotNull final ProjectStructureElement element) {
@@ -141,21 +117,28 @@
   }
 
   public void removeElement(ProjectStructureElement element) {
-    myElementWithNotCalculatedUsages.remove(element);
-    myElementsToShowWarningIfUnused.remove(element);
-    myWarningsAboutUnused.remove(element);
-    myProblemHolders.remove(element);
-    final Collection<ProjectStructureElementUsage> usages = mySourceElement2Usages.removeAll(element);
-    if (usages != null) {
-      for (ProjectStructureElementUsage usage : usages) {
-        myProblemHolders.remove(usage.getContainingElement());
-      }
-    }
-    removeUsagesInElement(element);
-    myDispatcher.getMulticaster().problemsChanged(element);
-    reportUnusedElements();
+    removeElements(Collections.singletonList(element));
   }
 
+  public void removeElements(@NotNull List<? extends ProjectStructureElement> elements) {
+    myElementWithNotCalculatedUsages.removeAll(elements);
+    myElementsToShowWarningIfUnused.removeAll(elements);
+    for (ProjectStructureElement element : elements) {
+      myWarningsAboutUnused.remove(element);
+      myProblemHolders.remove(element);
+      final Collection<ProjectStructureElementUsage> usages = mySourceElement2Usages.removeAll(element);
+      if (usages != null) {
+        for (ProjectStructureElementUsage usage : usages) {
+          myProblemHolders.remove(usage.getContainingElement());
+        }
+      }
+      removeUsagesInElement(element);
+      myDispatcher.getMulticaster().problemsChanged(element);
+    }
+    myResultsUpdateQueue.queue(new ReportUnusedElementsUpdate());
+  }
+
+
   private void reportUnusedElements() {
     if (!myElementWithNotCalculatedUsages.isEmpty()) return;
 
@@ -205,8 +188,10 @@
     LOG.debug("analyzer stopped");
     myStopped.set(true);
     myAnalyzerQueue.cancelAllUpdates();
+    myResultsUpdateQueue.cancelAllUpdates();
     clearCaches();
     myAnalyzerQueue.deactivate();
+    myResultsUpdateQueue.deactivate();
   }
 
   public void clearCaches() {
@@ -232,6 +217,7 @@
   public void dispose() {
     myStopped.set(true);
     myAnalyzerQueue.cancelAllUpdates();
+    myResultsUpdateQueue.cancelAllUpdates();
   }
 
   @Nullable
@@ -256,6 +242,7 @@
   public void reset() {
     LOG.debug("analyzer started");
     myAnalyzerQueue.activate();
+    myResultsUpdateQueue.activate();
     myAnalyzerQueue.queue(new Update("reset") {
       @Override
       public void run() {
@@ -270,9 +257,7 @@
     mySourceElement2Usages.clear();
     myContainingElement2Usages.clear();
     myElementWithNotCalculatedUsages.clear();
-    if (myProjectConfigurationProblems != null) {
-      myProjectConfigurationProblems.clearProblems();
-    }
+    myProjectConfigurationProblems.clearProblems();
   }
 
   private class AnalyzeElementUpdate extends Update {
@@ -312,4 +297,78 @@
       }
     }
   }
+
+  private class UsagesCollectedUpdate extends Update {
+    private final ProjectStructureElement myElement;
+    private final List<ProjectStructureElementUsage> myUsages;
+    private final Object[] myEqualityObjects;
+
+    public UsagesCollectedUpdate(ProjectStructureElement element, List<ProjectStructureElementUsage> usages) {
+      super(element);
+      myElement = element;
+      myUsages = usages;
+      myEqualityObjects = new Object[]{element, "usages collected"};
+    }
+
+    @NotNull
+    @Override
+    public Object[] getEqualityObjects() {
+      return myEqualityObjects;
+    }
+
+    @Override
+    public void run() {
+      if (myStopped.get()) return;
+
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("updating usages for " + myElement);
+      }
+      updateUsages(myElement, myUsages);
+    }
+  }
+
+  private class ProblemsComputedUpdate extends Update {
+    private final ProjectStructureElement myElement;
+    private final ProjectStructureProblemsHolderImpl myProblemsHolder;
+    private final Object[] myEqualityObjects;
+
+    public ProblemsComputedUpdate(ProjectStructureElement element, ProjectStructureProblemsHolderImpl problemsHolder) {
+      super(element);
+      myElement = element;
+      myProblemsHolder = problemsHolder;
+      myEqualityObjects = new Object[]{element, "problems computed"};
+    }
+
+    @NotNull
+    @Override
+    public Object[] getEqualityObjects() {
+      return myEqualityObjects;
+    }
+
+    @Override
+    public void run() {
+      if (myStopped.get()) return;
+
+      if (LOG.isDebugEnabled()) {
+        LOG.debug("updating problems for " + myElement);
+      }
+      final ProjectStructureProblemDescription warning = myWarningsAboutUnused.get(myElement);
+      if (warning != null) {
+        myProblemsHolder.registerProblem(warning);
+      }
+      myProblemHolders.put(myElement, myProblemsHolder);
+      myDispatcher.getMulticaster().problemsChanged(myElement);
+    }
+  }
+
+  private class ReportUnusedElementsUpdate extends Update {
+    private ReportUnusedElementsUpdate() {
+      super("unused elements");
+    }
+
+    @Override
+    public void run() {
+      reportUnusedElements();
+    }
+  }
 }
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java
index e11e2c0..8ee44f4 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/analysis/AnnotationsHighlightUtil.java
@@ -292,11 +292,14 @@
   private static final ElementPattern<PsiElement> ANY_ANNOTATION_ALLOWED = psiElement().andOr(
     psiElement().withParent(PsiNameValuePair.class),
     psiElement().withParents(PsiArrayInitializerMemberValue.class, PsiNameValuePair.class),
+    psiElement().withParents(PsiArrayInitializerMemberValue.class, PsiAnnotationMethod.class),
     psiElement().withParent(PsiAnnotationMethod.class).afterLeaf(PsiKeyword.DEFAULT)
   );
 
   @Nullable
-  public static HighlightInfo checkApplicability(@NotNull PsiAnnotation annotation, @NotNull LanguageLevel languageLevel,@NotNull PsiFile containingFile) {
+  public static HighlightInfo checkApplicability(@NotNull PsiAnnotation annotation,
+                                                 @NotNull LanguageLevel languageLevel,
+                                                 @NotNull PsiFile containingFile) {
     if (ANY_ANNOTATION_ALLOWED.accepts(annotation)) {
       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 365dd5a..5946e8a 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
@@ -29,7 +29,6 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.projectRoots.JavaSdkVersion;
 import com.intellij.openapi.projectRoots.JavaVersionService;
-import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.pom.java.LanguageLevel;
@@ -202,7 +201,7 @@
   public void visitAnnotation(PsiAnnotation annotation) {
     super.visitAnnotation(annotation);
     if (!myHolder.hasErrorResults()) myHolder.add(HighlightUtil.checkAnnotationFeature(annotation, myLanguageLevel, myFile));
-    if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkApplicability(annotation, myLanguageLevel,myFile));
+    if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkApplicability(annotation, myLanguageLevel, myFile));
     if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkAnnotationType(annotation));
     if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkMissingAttributes(annotation));
     if (!myHolder.hasErrorResults()) myHolder.add(AnnotationsHighlightUtil.checkTargetAnnotationDuplicates(annotation));
@@ -314,7 +313,7 @@
                     final PsiSubstitutor substitutor = LambdaUtil.getSubstitutor(interfaceMethod, resolveResult);
                     if (expression.hasFormalParameterTypes()) {
                       for (int i = 0; i < lambdaParameters.length; i++) {
-                        if (!Comparing.equal(lambdaParameters[i].getType(), substitutor.substitute(parameters[i].getType()))) {
+                        if (!PsiTypesUtil.compareTypes(lambdaParameters[i].getType(), substitutor.substitute(parameters[i].getType()), true)) {
                           HighlightInfo result = HighlightInfo.newHighlightInfo(HighlightInfoType.ERROR)
                             .range(lambdaParameters[i])
                             .descriptionAndTooltip(incompatibleTypesMessage)
@@ -1080,7 +1079,7 @@
         final PsiTypeParameterListOwner owner = ((PsiTypeParameter)resolved).getOwner();
         if (owner instanceof PsiClass) {
           final PsiClass outerClass = (PsiClass)owner;
-          if (!InheritanceUtil.hasEnclosingInstanceInScope(outerClass, ref, true, false)) {
+          if (!InheritanceUtil.hasEnclosingInstanceInScope(outerClass, ref, false, false)) {
             myHolder.add(HighlightClassUtil.reportIllegalEnclosingUsage(ref, aClass, (PsiClass)owner, ref));
           }
         }
@@ -1240,7 +1239,7 @@
         }
       }
     }
-    
+
     if (!myHolder.hasErrorResults()) {
       myHolder.add(PsiMethodReferenceHighlightingUtil.checkRawConstructorReference(expression));
     }
diff --git a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java
index f574b49..09f879b 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInsight/daemon/impl/quickfix/AddTypeArgumentsConditionalFix.java
@@ -75,7 +75,7 @@
       public String fun(PsiTypeParameter parameter) {
         final PsiType substituteTypeParam = mySubstitutor.substitute(parameter);
         LOG.assertTrue(substituteTypeParam != null);
-        return substituteTypeParam.getCanonicalText();
+        return GenericsUtil.eliminateWildcards(substituteTypeParam).getCanonicalText();
       }
     }, ", ") + ">";
     final PsiExpression expression = myExpression.getMethodExpression().getQualifierExpression();
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeMethodReferenceInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeMethodReferenceInspection.java
index 2bc0a28..558c3c0 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeMethodReferenceInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/AnonymousCanBeMethodReferenceInspection.java
@@ -118,7 +118,7 @@
           .canBeMethodReferenceProblem(methods[0].getBody(), parameters, anonymousClass.getBaseClassType());
         if (callExpression == null) return;
         final String methodRefText =
-          LambdaCanBeMethodReferenceInspection.createMethodReferenceText(callExpression, anonymousClass.getBaseClassType());
+          LambdaCanBeMethodReferenceInspection.createMethodReferenceText(callExpression, anonymousClass.getBaseClassType(), parameters);
 
         if (methodRefText != null) {
           final String canonicalText = anonymousClass.getBaseClassType().getCanonicalText();
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java
index 83783f5..8a8a6db 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/LambdaCanBeMethodReferenceInspection.java
@@ -24,6 +24,7 @@
 import com.intellij.psi.codeStyle.JavaCodeStyleManager;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
+import com.intellij.psi.util.TypeConversionUtil;
 import com.intellij.util.ArrayUtilRt;
 import org.jetbrains.annotations.Nls;
 import org.jetbrains.annotations.NotNull;
@@ -114,8 +115,8 @@
       if (argumentList != null) {
         final PsiExpression[] expressions = argumentList.getExpressions();
 
-        final PsiMethod psiMethod = methodCall.resolveMethod();
-        final PsiClass containingClass;
+        PsiMethod psiMethod = methodCall.resolveMethod();
+        PsiClass containingClass;
         boolean isConstructor;
         if (psiMethod == null) {
           isConstructor = true;
@@ -131,6 +132,12 @@
         }
         if (containingClass == null) return null;
         boolean isReceiverType = PsiMethodReferenceUtil.isReceiverType(functionalInterfaceType, containingClass, psiMethod);
+        if (isReceiverType && psiMethod != null) {
+          PsiMethod nonAmbiguousMethod = ensureNonAmbiguousMethod(parameters, psiMethod);
+          if (nonAmbiguousMethod == null) return null;
+          psiMethod = nonAmbiguousMethod;
+          containingClass = nonAmbiguousMethod.getContainingClass();
+        }
         final boolean staticOrValidConstructorRef;
         if (isConstructor) {
           staticOrValidConstructorRef =
@@ -181,6 +188,12 @@
             }
 
             @Override
+            public void visitNewExpression(PsiNewExpression expression) {
+              usedInQualifier.set(true);
+              super.visitNewExpression(expression);
+            }
+
+            @Override
             public void visitMethodCallExpression(PsiMethodCallExpression expression) {
               usedInQualifier.set(true);
               super.visitMethodCallExpression(expression);
@@ -206,13 +219,35 @@
   }
 
   @Nullable
-  protected static String createMethodReferenceText(PsiElement element, PsiType functionalInterfaceType) {
+  private static PsiMethod ensureNonAmbiguousMethod(PsiParameter[] parameters, @NotNull PsiMethod psiMethod) {
+    String methodName = psiMethod.getName();
+    PsiClass containingClass = psiMethod.getContainingClass();
+    if (containingClass == null) return null;
+    for (PsiMethod method : containingClass.findMethodsByName(methodName, false)) {
+      PsiParameter[] candidateParams = method.getParameterList().getParameters();
+      if (candidateParams.length == 1) {
+        if (TypeConversionUtil.areTypesConvertible(candidateParams[0].getType(), parameters[0].getType())) {
+          for (PsiMethod superMethod : psiMethod.findDeepestSuperMethods()) {
+            PsiMethod validSuperMethod = ensureNonAmbiguousMethod(parameters, superMethod);
+            if (validSuperMethod != null) return validSuperMethod;
+          }
+          return null;
+        }
+      }
+    }
+    return psiMethod;
+  }
+
+  @Nullable
+  protected static String createMethodReferenceText(final PsiElement element,
+                                                    final PsiType functionalInterfaceType,
+                                                    final PsiParameter[] parameters) {
     String methodRefText = null;
     if (element instanceof PsiMethodCallExpression) {
       final PsiMethodCallExpression methodCall = (PsiMethodCallExpression)element;
       final PsiMethod psiMethod = methodCall.resolveMethod();
       if (psiMethod == null) return null;
-      final PsiClass containingClass = psiMethod.getContainingClass();
+      PsiClass containingClass = psiMethod.getContainingClass();
       LOG.assertTrue(containingClass != null);
       final PsiReferenceExpression methodExpression = methodCall.getMethodExpression();
       final PsiExpression qualifierExpression = methodExpression.getQualifierExpression();
@@ -221,8 +256,15 @@
         boolean isReceiverType = PsiMethodReferenceUtil.isReceiverType(functionalInterfaceType, containingClass, psiMethod);
         final String qualifier;
         if (isReceiverType) {
-          final PsiType qualifierExpressionType = qualifierExpression.getType();
-          qualifier = qualifierExpressionType != null ? qualifierExpressionType.getCanonicalText() : getClassReferenceName(containingClass);
+          final PsiMethod nonAmbiguousMethod = ensureNonAmbiguousMethod(parameters, psiMethod);
+          LOG.assertTrue(nonAmbiguousMethod != null);
+          final PsiClass nonAmbiguousContainingClass = nonAmbiguousMethod.getContainingClass();
+          if (!containingClass.equals(nonAmbiguousContainingClass)) {
+            qualifier = getClassReferenceName(nonAmbiguousContainingClass);
+          } else {
+            final PsiType qualifierExpressionType = qualifierExpression.getType();
+            qualifier = qualifierExpressionType != null ? qualifierExpressionType.getCanonicalText() : getClassReferenceName(nonAmbiguousContainingClass);
+          }
         }
         else {
           qualifier = qualifierExpression.getText();
@@ -298,7 +340,8 @@
       final PsiLambdaExpression lambdaExpression = PsiTreeUtil.getParentOfType(element, PsiLambdaExpression.class);
       if (lambdaExpression == null) return;
       final PsiType functionalInterfaceType = lambdaExpression.getFunctionalInterfaceType();
-      final String methodRefText = createMethodReferenceText(element, functionalInterfaceType);
+      final String methodRefText = createMethodReferenceText(element, functionalInterfaceType,
+                                                             lambdaExpression.getParameterList().getParameters());
 
       if (methodRefText != null) {
         final PsiElementFactory factory = JavaPsiFacade.getElementFactory(project);
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java
similarity index 97%
rename from java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java
rename to java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java
index ac49a62..f35609a 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/RedundantSuppressInspectionBase.java
@@ -43,7 +43,7 @@
 /**
  * @author cdr
  */
-public class RedundantSuppressInspection extends GlobalInspectionTool{
+public class RedundantSuppressInspectionBase extends GlobalInspectionTool {
   private BidirectionalMap<String, QuickFix> myQuickFixes = null;
   private static final Logger LOG = Logger.getInstance("#com.intellij.codeInspection.RedundantSuppressInspection");
 
@@ -87,7 +87,7 @@
                             @NotNull final ProblemDescriptionsProcessor problemDescriptionsProcessor) {
     globalContext.getRefManager().iterate(new RefJavaVisitor() {
       @Override public void visitClass(@NotNull RefClass refClass) {
-        if (!globalContext.shouldCheck(refClass, RedundantSuppressInspection.this)) return;
+        if (!globalContext.shouldCheck(refClass, RedundantSuppressInspectionBase.this)) return;
         CommonProblemDescriptor[] descriptors = checkElement(refClass, manager, globalContext.getProject());
         if (descriptors != null) {
           for (CommonProblemDescriptor descriptor : descriptors) {
@@ -192,7 +192,7 @@
     PsiFile file = psiElement.getContainingFile();
     final AnalysisScope scope = new AnalysisScope(file);
 
-    final GlobalInspectionContextBase globalContext = new GlobalInspectionContextBase(file.getProject());
+    final GlobalInspectionContextBase globalContext = createContext(file);
     globalContext.setCurrentScope(scope);
     final RefManagerImpl refManager = (RefManagerImpl)globalContext.getRefManager();
     refManager.inspectionReadActionStarted();
@@ -314,6 +314,10 @@
     return result.toArray(new ProblemDescriptor[result.size()]);
   }
 
+  protected GlobalInspectionContextBase createContext(PsiFile file) {
+    return new GlobalInspectionContextBase(file.getProject());
+  }
+
   protected InspectionToolWrapper[] getInspectionTools(PsiElement psiElement, @NotNull InspectionManager manager) {
     ModifiableModel model = InspectionProjectProfileManager.getInstance(manager.getProject()).getInspectionProfile().getModifiableModel();
     InspectionProfileWrapper profile = new InspectionProfileWrapper((InspectionProfile)model);
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 8d845ff..22c919c 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
@@ -94,6 +94,10 @@
       return null;
     }
 
+    PsiElement parent = codeFragment.getParent();
+    if (parent instanceof PsiLambdaExpression && codeFragment instanceof PsiExpression) {
+      addInstruction(new CheckReturnValueInstruction(codeFragment));
+    }
     myCurrentFlow.setFields(myFields.toArray(new DfaVariableValue[myFields.size()]));
 
     addInstruction(new ReturnInstruction(false));
@@ -528,6 +532,15 @@
     finishElement(statement);
   }
 
+  @Override
+  public void visitLambdaExpression(PsiLambdaExpression expression) {
+    startElement(expression);
+    DfaValue dfaValue = myFactory.createValue(expression);
+    addInstruction(new PushInstruction(dfaValue, expression));
+    addInstruction(new LambdaInstruction(expression));
+    finishElement(expression);
+  }
+
   @Override public void visitReturnStatement(PsiReturnStatement statement) {
     startElement(statement);
 
@@ -538,7 +551,7 @@
       if (method != null) {
         generateBoxingUnboxingInstructionFor(returnValue, method.getReturnType());
       }
-      addInstruction(new CheckReturnValueInstruction(statement));
+      addInstruction(new CheckReturnValueInstruction(returnValue));
     }
 
     returnCheckingFinally();
@@ -1874,7 +1887,7 @@
     }
 
     final PsiTypeElement typeElement = castExpression.getCastType();
-    if (typeElement != null && operand != null) {
+    if (typeElement != null && operand != null && operand.getType() != null) {
       if (typeElement.getType() instanceof PsiPrimitiveType &&
           UnnecessaryExplicitNumericCastInspection.isPrimitiveNumericCastNecessary(castExpression)) {
         addInstruction(new PopInstruction());
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
index c6314f7..305085c 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspectionBase.java
@@ -192,7 +192,7 @@
   }
 
   @Nullable
-  private LocalQuickFix[] createNPEFixes(PsiExpression qualifier, PsiExpression expression) {
+  private LocalQuickFix[] createNPEFixes(PsiExpression qualifier, PsiExpression expression, boolean onTheFly) {
     if (qualifier == null || expression == null) return null;
     if (qualifier instanceof PsiMethodCallExpression) return null;
     if (qualifier instanceof PsiLiteralExpression && ((PsiLiteralExpression)qualifier).getValue() == null) return null;
@@ -208,7 +208,7 @@
         fixes.add(new AddAssertStatementFix(binary));
       }
 
-      addSurroundWithIfFix(qualifier, fixes);
+      addSurroundWithIfFix(qualifier, fixes, onTheFly);
 
       if (ReplaceWithTernaryOperatorFix.isAvailable(qualifier, expression)) {
         fixes.add(new ReplaceWithTernaryOperatorFix(qualifier));
@@ -221,7 +221,7 @@
     }
   }
 
-  protected void addSurroundWithIfFix(PsiExpression qualifier, List<LocalQuickFix> fixes) {
+  protected void addSurroundWithIfFix(PsiExpression qualifier, List<LocalQuickFix> fixes, boolean onTheFly) {
   }
 
   private void createDescription(StandardDataFlowRunner runner, ProblemsHolder holder, DataFlowInstructionVisitor visitor) {
@@ -238,7 +238,7 @@
     HashSet<PsiElement> reportedAnchors = new HashSet<PsiElement>();
     for (PsiElement element : visitor.getProblems(NullabilityProblem.callNPE)) {
       if (reportedAnchors.add(element)) {
-        reportCallMayProduceNpe(holder, (PsiMethodCallExpression)element);
+        reportCallMayProduceNpe(holder, (PsiMethodCallExpression)element, holder.isOnTheFly());
       }
     }
     for (PsiElement element : visitor.getProblems(NullabilityProblem.fieldAccessNPE)) {
@@ -340,7 +340,7 @@
       final String text = isNullLiteralExpression(expr)
                           ? "Passing <code>null</code> argument to non annotated parameter"
                           : "Argument <code>#ref</code> #loc might be null but passed to non annotated parameter";
-      LocalQuickFix[] fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr);
+      LocalQuickFix[] fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr, holder.isOnTheFly());
       final PsiElement parent = expr.getParent();
       if (parent instanceof PsiExpressionList) {
         final int idx = ArrayUtilRt.find(((PsiExpressionList)parent).getExpressions(), expr);
@@ -364,8 +364,8 @@
     }
   }
 
-  private void reportCallMayProduceNpe(ProblemsHolder holder, PsiMethodCallExpression callExpression) {
-    LocalQuickFix[] fix = createNPEFixes(callExpression.getMethodExpression().getQualifierExpression(), callExpression);
+  private void reportCallMayProduceNpe(ProblemsHolder holder, PsiMethodCallExpression callExpression, boolean onTheFly) {
+    LocalQuickFix[] fix = createNPEFixes(callExpression.getMethodExpression().getQualifierExpression(), callExpression, onTheFly);
 
     holder.registerProblem(callExpression,
                            InspectionsBundle.message("dataflow.message.npe.method.invocation"),
@@ -374,13 +374,13 @@
 
   private void reportFieldAccessMayProduceNpe(ProblemsHolder holder, PsiElement elementToAssert, PsiExpression expression) {
     if (expression instanceof PsiArrayAccessExpression) {
-      LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert, expression);
+      LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert, expression, holder.isOnTheFly());
       holder.registerProblem(expression,
                              InspectionsBundle.message("dataflow.message.npe.array.access"),
                              fix);
     }
     else {
-      LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert, expression);
+      LocalQuickFix[] fix = createNPEFixes((PsiExpression)elementToAssert, expression, holder.isOnTheFly());
       assert elementToAssert != null;
       holder.registerProblem(elementToAssert,
                              InspectionsBundle.message("dataflow.message.npe.field.access"),
@@ -454,7 +454,7 @@
       final String text = isNullLiteralExpression(expr)
                           ? InspectionsBundle.message("dataflow.message.passing.null.argument")
                           : InspectionsBundle.message("dataflow.message.passing.nullable.argument");
-      LocalQuickFix[] fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr);
+      LocalQuickFix[] fixes = createNPEFixes((PsiExpression)expr, (PsiExpression)expr, holder.isOnTheFly());
       holder.registerProblem(expr, text, fixes);
     }
   }
@@ -479,8 +479,8 @@
 
   private static void reportNullableReturns(StandardDataFlowRunner runner, DataFlowInstructionVisitor visitor, ProblemsHolder holder, Set<PsiElement> reportedAnchors) {
     for (PsiElement statement : visitor.getProblems(NullabilityProblem.nullableReturn)) {
-      final PsiExpression expr = ((PsiReturnStatement)statement).getReturnValue();
-      assert expr != null;
+      assert statement instanceof PsiExpression; 
+      final PsiExpression expr = (PsiExpression)statement;
       if (!reportedAnchors.add(expr)) continue;
 
       if (runner.isInNotNullMethod()) {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java
index 09c4612..6c5c909 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/DataFlowRunner.java
@@ -226,6 +226,10 @@
         }
       }
     }
+    else if (instruction instanceof LambdaInstruction) {
+      PsiLambdaExpression lambdaExpression = ((LambdaInstruction)instruction).getLambdaExpression();
+      registerNestedClosures(instructionState, lambdaExpression);
+    }
     else if (instruction instanceof EmptyInstruction) {
       PsiElement anchor = ((EmptyInstruction)instruction).getAnchor();
       if (anchor instanceof PsiDeclarationStatement) {
@@ -255,6 +259,14 @@
       myNestedClosures.putValue(field, createClosureState(state));
     }
   }
+  
+  private void registerNestedClosures(DfaInstructionState instructionState, PsiLambdaExpression expr) {
+    DfaMemoryState state = instructionState.getMemoryState();
+    PsiElement body = expr.getBody();
+    if (body != null) {
+      myNestedClosures.putValue(body, createClosureState(state));
+    }
+  }
 
   protected ControlFlowAnalyzer createControlFlowAnalyzer() {
     return new ControlFlowAnalyzer(myValueFactory);
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InstructionVisitor.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InstructionVisitor.java
index b1d3203..0b9f0b0 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InstructionVisitor.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/InstructionVisitor.java
@@ -54,6 +54,10 @@
     return nextInstruction(instruction, runner, memState);
   }
 
+  public DfaInstructionState[] visitLambdaExpression(LambdaInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
+    return nextInstruction(instruction, runner, memState);
+  }
+
   public DfaInstructionState[] visitConditionalGoto(ConditionalGotoInstruction instruction, DataFlowRunner runner, DfaMemoryState memState) {
     DfaValue cond = memState.pop();
 
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardDataFlowRunner.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardDataFlowRunner.java
index 3ada3e84..2652c6f 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardDataFlowRunner.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/StandardDataFlowRunner.java
@@ -27,10 +27,7 @@
 import com.intellij.codeInsight.NullableNotNullManager;
 import com.intellij.codeInspection.dataFlow.instructions.InstanceofInstruction;
 import com.intellij.codeInspection.dataFlow.instructions.Instruction;
-import com.intellij.psi.CommonClassNames;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiType;
+import com.intellij.psi.*;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.HashSet;
@@ -49,13 +46,23 @@
 
   @Override
   protected void prepareAnalysis(@NotNull PsiElement psiBlock, Iterable<DfaMemoryState> initialStates) {
-    myIsInMethod = psiBlock.getParent() instanceof PsiMethod;
+    PsiElement parent = psiBlock.getParent();
+    myIsInMethod = parent instanceof PsiMethod;
     if (myIsInMethod) {
-      PsiMethod method = (PsiMethod)psiBlock.getParent();
+      PsiMethod method = (PsiMethod)parent;
       PsiType returnType = method.getReturnType();
       myInNullableMethod = NullableNotNullManager.isNullable(method) ||
                            returnType != null && returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID);
       myInNotNullMethod = NullableNotNullManager.isNotNull(method);
+    } else if (parent instanceof PsiLambdaExpression) {
+      PsiMethod method = LambdaUtil.getFunctionalInterfaceMethod(((PsiLambdaExpression)parent).getFunctionalInterfaceType());
+      if (method != null) {
+        myIsInMethod = true;
+        PsiType returnType = method.getReturnType();
+        myInNullableMethod = NullableNotNullManager.isNullable(method) ||
+                             returnType != null && returnType.equalsToText(CommonClassNames.JAVA_LANG_VOID);
+        myInNotNullMethod = NullableNotNullManager.isNotNull(method);
+      }
     }
 
     myCCEInstructions.clear();
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/CheckReturnValueInstruction.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/CheckReturnValueInstruction.java
index a668a7b..6d17463 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/CheckReturnValueInstruction.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/CheckReturnValueInstruction.java
@@ -19,16 +19,16 @@
 import com.intellij.codeInspection.dataFlow.DfaInstructionState;
 import com.intellij.codeInspection.dataFlow.DfaMemoryState;
 import com.intellij.codeInspection.dataFlow.InstructionVisitor;
-import com.intellij.psi.PsiReturnStatement;
+import com.intellij.psi.PsiElement;
 
 /**
  * @author max
  */
 public class CheckReturnValueInstruction extends Instruction {
-  private final PsiReturnStatement myReturn;
+  private final PsiElement myReturnValue;
 
-  public CheckReturnValueInstruction(final PsiReturnStatement aReturn) {
-    myReturn = aReturn;
+  public CheckReturnValueInstruction(final PsiElement returnValue) {
+    myReturnValue = returnValue;
   }
 
   @Override
@@ -36,8 +36,8 @@
     return visitor.visitCheckReturnValue(this, runner, stateBefore);
   }
 
-  public PsiReturnStatement getReturn() {
-    return myReturn;
+  public PsiElement getReturn() {
+    return myReturnValue;
   }
 
   public String toString() {
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/LambdaInstruction.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/LambdaInstruction.java
new file mode 100644
index 0000000..a0cedb9
--- /dev/null
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dataFlow/instructions/LambdaInstruction.java
@@ -0,0 +1,44 @@
+/*
+ * 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.codeInspection.dataFlow.instructions;
+
+import com.intellij.codeInspection.dataFlow.DataFlowRunner;
+import com.intellij.codeInspection.dataFlow.DfaInstructionState;
+import com.intellij.codeInspection.dataFlow.DfaMemoryState;
+import com.intellij.codeInspection.dataFlow.InstructionVisitor;
+import com.intellij.psi.PsiLambdaExpression;
+
+public class LambdaInstruction extends Instruction {
+  private final PsiLambdaExpression myLambdaExpression;
+
+  public LambdaInstruction(PsiLambdaExpression lambdaExpression) {
+    myLambdaExpression = lambdaExpression;
+  }
+
+  public PsiLambdaExpression getLambdaExpression() {
+    return myLambdaExpression;
+  }
+
+  @Override
+  public DfaInstructionState[] accept(DataFlowRunner runner, DfaMemoryState stateBefore, InstructionVisitor visitor) {
+    return visitor.visitLambdaExpression(this, runner, stateBefore);
+  }
+
+  @Override
+  public String toString() {
+    return "LambdaInstruction";
+  }
+}
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/dependencyViolation/DependencyInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/dependencyViolation/DependencyInspectionBase.java
index e39bc8e1..bd13202 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/dependencyViolation/DependencyInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/dependencyViolation/DependencyInspectionBase.java
@@ -30,7 +30,7 @@
 import java.util.ArrayList;
 import java.util.List;
 
-public class DependencyInspectionBase extends AbstractBaseJavaLocalInspectionTool {
+public class DependencyInspectionBase extends BaseJavaBatchLocalInspectionTool {
   private static final String GROUP_DISPLAY_NAME = "";
   private static final String DISPLAY_NAME = InspectionsBundle.message("illegal.package.dependencies");
   @NonNls private static final String SHORT_NAME = "Dependency";
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java
index ca03e7f..33cd004 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocLocalInspectionBase.java
@@ -44,7 +44,7 @@
 
 import java.util.*;
 
-public class JavaDocLocalInspectionBase extends AbstractBaseJavaLocalInspectionTool {
+public class JavaDocLocalInspectionBase extends BaseJavaBatchLocalInspectionTool {
   private static final Logger LOG = Logger.getInstance("com.intellij.codeInspection.javaDoc.JavaDocLocalInspectionBase");
   @NonNls protected static final String NONE = "none";
   @NonNls protected static final String PUBLIC = "public";
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspectionBase.java
index 6a9aa1b3..bfe23989 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/javaDoc/JavaDocReferenceInspectionBase.java
@@ -31,7 +31,7 @@
 import java.util.List;
 import java.util.Set;
 
-public class JavaDocReferenceInspectionBase extends AbstractBaseJavaLocalInspectionTool {
+public class JavaDocReferenceInspectionBase  extends BaseJavaBatchLocalInspectionTool {
   @NonNls private static final String SHORT_NAME = "JavadocReference";
 
   private static ProblemDescriptor createDescriptor(@NotNull PsiElement element, String template, InspectionManager manager,
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java b/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java
index 028e9b7..d4cff693 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/localCanBeFinal/LocalCanBeFinal.java
@@ -18,6 +18,7 @@
 import com.intellij.codeInsight.FileModificationService;
 import com.intellij.codeInsight.daemon.GroupNames;
 import com.intellij.codeInspection.*;
+import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.psi.*;
@@ -44,6 +45,8 @@
 
   public boolean REPORT_VARIABLES = true;
   public boolean REPORT_PARAMETERS = true;
+  public boolean REPORT_CATCH_PARAMETERS = true;
+  public boolean REPORT_FOREACH_PARAMETERS = true;
 
   private final LocalQuickFix myQuickFix;
   @NonNls public static final String SHORT_NAME = "LocalCanBeFinal";
@@ -148,6 +151,7 @@
       @Override
       public void visitCatchSection(PsiCatchSection section) {
         super.visitCatchSection(section);
+        if (!REPORT_CATCH_PARAMETERS) return;
         final PsiParameter parameter = section.getParameter();
         if (PsiTreeUtil.getParentOfType(parameter, PsiClass.class) != PsiTreeUtil.getParentOfType(body, PsiClass.class)) {
           return;
@@ -164,6 +168,7 @@
 
       @Override public void visitForeachStatement(PsiForeachStatement statement) {
         super.visitForeachStatement(statement);
+        if (!REPORT_FOREACH_PARAMETERS) return;
         final PsiParameter param = statement.getIterationParameter();
         if (PsiTreeUtil.getParentOfType(param, PsiClass.class) != PsiTreeUtil.getParentOfType(body, PsiClass.class)) {
           return;
@@ -219,7 +224,7 @@
       }
     });
 
-    if (body.getParent() instanceof PsiMethod && isReportParameters()) {
+    if (body.getParent() instanceof PsiMethod && REPORT_PARAMETERS) {
       final PsiMethod method = (PsiMethod)body.getParent();
       if (!(method instanceof SyntheticElement)) { // e.g. JspHolderMethod
         Collections.addAll(result, method.getParameterList().getParameters());
@@ -231,6 +236,16 @@
       if (shouldBeIgnored(variable)) {
         iterator.remove();
       }
+      final PsiElement parent = variable.getParent();
+      if (!(parent instanceof PsiDeclarationStatement)) {
+        continue;
+      }
+      final PsiDeclarationStatement declarationStatement = (PsiDeclarationStatement)parent;
+      final PsiElement[] elements = declarationStatement.getDeclaredElements();
+      final PsiElement grandParent = parent.getParent();
+      if (elements.length > 1 && grandParent instanceof PsiForStatement) {
+        iterator.remove(); // do not report when more than 1 variable declared in for loop
+      }
     }
 
     for (PsiVariable writtenVariable : writtenVariables) {
@@ -261,19 +276,21 @@
 
   private boolean shouldBeIgnored(PsiVariable psiVariable) {
     if (psiVariable.hasModifierProperty(PsiModifier.FINAL)) return true;
-    return isLocalVariable(psiVariable) ? !isReportVariables() : !isReportParameters();
-  }
-
-  private static boolean isLocalVariable(PsiVariable variable) {
-    if (variable instanceof PsiLocalVariable) {
-      return true;
+    if (psiVariable instanceof PsiLocalVariable) {
+      return !REPORT_VARIABLES;
     }
-    if (!(variable instanceof PsiParameter)) {
-      return false;
+    if (psiVariable instanceof PsiParameter) {
+      final PsiParameter parameter = (PsiParameter)psiVariable;
+      final PsiElement declarationScope = parameter.getDeclarationScope();
+      if (declarationScope instanceof PsiCatchSection) {
+        return !REPORT_CATCH_PARAMETERS;
+      }
+      else if (declarationScope instanceof PsiForeachStatement) {
+        return !REPORT_FOREACH_PARAMETERS;
+      }
+      return !REPORT_PARAMETERS;
     }
-    final PsiParameter parameter = (PsiParameter)variable;
-    final PsiElement declarationScope = parameter.getDeclarationScope();
-    return !(declarationScope instanceof PsiMethod) && !(declarationScope instanceof PsiLambdaExpression);
+    return true;
   }
 
   @Override
@@ -326,55 +343,12 @@
 
   @Override
   public JComponent createOptionsPanel() {
-    return new OptionsPanel();
-  }
-
-  private boolean isReportVariables() {
-    return REPORT_VARIABLES;
-  }
-
-  private boolean isReportParameters() {
-    return REPORT_PARAMETERS;
-  }
-
-  private class OptionsPanel extends JPanel {
-    private final JCheckBox myReportVariablesCheckbox;
-    private final JCheckBox myReportParametersCheckbox;
-
-    private OptionsPanel() {
-      super(new GridBagLayout());
-
-      GridBagConstraints gc = new GridBagConstraints();
-      gc.weighty = 0;
-      gc.weightx = 1;
-      gc.fill = GridBagConstraints.HORIZONTAL;
-      gc.anchor = GridBagConstraints.NORTHWEST;
-
-
-      myReportVariablesCheckbox = new JCheckBox(InspectionsBundle.message("inspection.local.can.be.final.option"));
-      myReportVariablesCheckbox.setSelected(REPORT_VARIABLES);
-      myReportVariablesCheckbox.getModel().addChangeListener(new ChangeListener() {
-        @Override
-        public void stateChanged(ChangeEvent e) {
-          REPORT_VARIABLES = myReportVariablesCheckbox.isSelected();
-        }
-      });
-      gc.gridy = 0;
-      add(myReportVariablesCheckbox, gc);
-
-      myReportParametersCheckbox = new JCheckBox(InspectionsBundle.message("inspection.local.can.be.final.option1"));
-      myReportParametersCheckbox.setSelected(REPORT_PARAMETERS);
-      myReportParametersCheckbox.getModel().addChangeListener(new ChangeListener() {
-        @Override
-        public void stateChanged(ChangeEvent e) {
-          REPORT_PARAMETERS = myReportParametersCheckbox.isSelected();
-        }
-      });
-
-      gc.weighty = 1;
-      gc.gridy++;
-      add(myReportParametersCheckbox, gc);
-    }
+    final MultipleCheckboxOptionsPanel panel = new MultipleCheckboxOptionsPanel(this);
+    panel.addCheckbox(InspectionsBundle.message("inspection.local.can.be.final.option"), "REPORT_VARIABLES");
+    panel.addCheckbox(InspectionsBundle.message("inspection.local.can.be.final.option1"), "REPORT_PARAMETERS");
+    panel.addCheckbox(InspectionsBundle.message("inspection.local.can.be.final.option2"), "REPORT_CATCH_PARAMETERS");
+    panel.addCheckbox(InspectionsBundle.message("inspection.local.can.be.final.option3"), "REPORT_FOREACH_PARAMETERS");
+    return panel;
   }
 
   @Override
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java b/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java
index bb3c4ea..2770432 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/miscGenerics/RedundantTypeArgsInspection.java
@@ -74,14 +74,18 @@
   public ProblemDescriptor[] getDescriptions(@NotNull PsiElement place, @NotNull final InspectionManager inspectionManager, boolean isOnTheFly) {
     final List<ProblemDescriptor> problems = new ArrayList<ProblemDescriptor>();
     place.accept(new JavaRecursiveElementWalkingVisitor() {
-      @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) {
+      @Override
+      public void visitMethodCallExpression(PsiMethodCallExpression expression) {
+        super.visitMethodCallExpression(expression);
         final PsiType[] typeArguments = expression.getTypeArguments();
         if (typeArguments.length > 0) {
           checkCallExpression(expression.getMethodExpression(), typeArguments, expression, inspectionManager, problems);
         }
       }
 
-      @Override public void visitNewExpression(PsiNewExpression expression) {
+      @Override
+      public void visitNewExpression(PsiNewExpression expression) {
+        super.visitNewExpression(expression);
         final PsiType[] typeArguments = expression.getTypeArguments();
         if (typeArguments.length > 0) {
           final PsiJavaCodeReferenceElement classReference = expression.getClassReference();
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspectionBase.java
index e12f10c..72b71c0 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/suspiciousNameCombination/SuspiciousNameCombinationInspectionBase.java
@@ -117,7 +117,8 @@
         PsiExpression expr = variable.getInitializer();
         if (expr instanceof PsiReferenceExpression) {
           PsiReferenceExpression refExpr = (PsiReferenceExpression) expr;
-          checkCombination(variable, variable.getName(), refExpr.getReferenceName(), "suspicious.name.assignment");
+          PsiIdentifier nameIdentifier = variable.getNameIdentifier();
+          checkCombination(nameIdentifier != null ? nameIdentifier : variable, variable.getName(), refExpr.getReferenceName(), "suspicious.name.assignment");
         }
       }
     }
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java
index bb8556d..276b451 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/FieldCanBeLocalInspectionBase.java
@@ -18,10 +18,7 @@
 import com.intellij.codeInsight.AnnotationUtil;
 import com.intellij.codeInsight.daemon.GroupNames;
 import com.intellij.codeInsight.daemon.ImplicitUsageProvider;
-import com.intellij.codeInspection.AbstractBaseJavaLocalInspectionTool;
-import com.intellij.codeInspection.InspectionsBundle;
-import com.intellij.codeInspection.LocalQuickFix;
-import com.intellij.codeInspection.ProblemsHolder;
+import com.intellij.codeInspection.*;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.JDOMExternalizableStringList;
@@ -41,7 +38,7 @@
 import java.util.List;
 import java.util.Set;
 
-public class FieldCanBeLocalInspectionBase extends AbstractBaseJavaLocalInspectionTool {
+public class FieldCanBeLocalInspectionBase extends BaseJavaBatchLocalInspectionTool {
   @NonNls public static final String SHORT_NAME = "FieldCanBeLocal";
   public final JDOMExternalizableStringList EXCLUDE_ANNOS = new JDOMExternalizableStringList();
   public boolean IGNORE_FIELDS_USED_IN_MULTIPLE_METHODS = true;
diff --git a/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspectionBase.java b/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspectionBase.java
index 8ea58d6..7c9cd30 100644
--- a/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspectionBase.java
+++ b/java/java-analysis-impl/src/com/intellij/codeInspection/varScopeCanBeNarrowed/ParameterCanBeLocalInspectionBase.java
@@ -26,7 +26,7 @@
 
 import java.util.*;
 
-public class ParameterCanBeLocalInspectionBase extends AbstractBaseJavaLocalInspectionTool {
+public class ParameterCanBeLocalInspectionBase extends BaseJavaBatchLocalInspectionTool {
   @NonNls public static final String SHORT_NAME = "ParameterCanBeLocal";
 
   @NotNull
diff --git a/java/java-analysis-impl/src/com/intellij/lang/java/JavaSyntaxHighlighterFactory.java b/java/java-analysis-impl/src/com/intellij/lang/java/JavaSyntaxHighlighterFactory.java
index 7ee3d7b..2c427bd 100644
--- a/java/java-analysis-impl/src/com/intellij/lang/java/JavaSyntaxHighlighterFactory.java
+++ b/java/java-analysis-impl/src/com/intellij/lang/java/JavaSyntaxHighlighterFactory.java
@@ -49,7 +49,7 @@
     if (project != null && file != null) {
       PsiFile psiFile = PsiManager.getInstance(project).findFile(file);
       if (psiFile instanceof ClsFileImpl) {
-        LanguageLevel sourceLevel = ((ClsFileImpl)psiFile).getSourceLanguageLevel();
+        LanguageLevel sourceLevel = ((ClsFileImpl)psiFile).getLanguageLevel();
         return new JavaFileHighlighter(sourceLevel);
       }
     }
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 2367ce3..81cb9b5 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/AllClassesGetter.java
@@ -193,14 +193,14 @@
 
 
   private static String getPackagePrefix(final PsiElement context, final int offset) {
-    final String fileText = context.getContainingFile().getText();
+    final CharSequence fileText = context.getContainingFile().getViewProvider().getContents();
     int i = offset - 1;
     while (i >= 0) {
       final char c = fileText.charAt(i);
       if (!Character.isJavaIdentifierPart(c) && c != '.') break;
       i--;
     }
-    String prefix = fileText.substring(i + 1, offset);
+    String prefix = fileText.subSequence(i + 1, offset).toString();
     final int j = prefix.lastIndexOf('.');
     return j > 0 ? prefix.substring(0, j) : "";
   }
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java b/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java
index aa1293a..bcfa4f0 100644
--- a/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/JavaSmartCompletionContributor.java
@@ -94,7 +94,20 @@
     @Override
     public boolean accepts(@NotNull PsiElement element, ProcessingContext context) {
       final PsiElement rulezzRef = element.getParent();
-      return rulezzRef != null && LambdaUtil.isValidLambdaContext(rulezzRef.getParent());
+      return rulezzRef != null &&
+             rulezzRef instanceof PsiReferenceExpression &&
+             ((PsiReferenceExpression)rulezzRef).getQualifier() == null &&
+             LambdaUtil.isValidLambdaContext(rulezzRef.getParent());
+    }});
+
+  static final PsiElementPattern.Capture<PsiElement> METHOD_REFERENCE = psiElement().with(new PatternCondition<PsiElement>("METHOD_REFERENCE_CONTEXT") {
+    @Override
+    public boolean accepts(@NotNull PsiElement element, ProcessingContext context) {
+      final PsiElement rulezzRef = element.getParent();
+      return rulezzRef != null &&
+             rulezzRef instanceof PsiMethodReferenceExpression &&
+             ((PsiReferenceExpression)rulezzRef).getQualifier() != element &&
+             LambdaUtil.isValidLambdaContext(rulezzRef.getParent());
     }});
 
   @Nullable
@@ -319,6 +332,7 @@
     });
 
     extend(CompletionType.SMART, LAMBDA, new LambdaCompletionProvider());
+    extend(CompletionType.SMART, METHOD_REFERENCE, new MethodReferenceCompletionProvider());
   }
 
   private static void addExpectedTypeMembers(CompletionParameters params,
diff --git a/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java b/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java
new file mode 100644
index 0000000..dbd2fc8
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInsight/completion/MethodReferenceCompletionProvider.java
@@ -0,0 +1,61 @@
+/*
+ * 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.codeInsight.completion;
+
+import com.intellij.codeInsight.ExpectedTypeInfo;
+import com.intellij.codeInsight.ExpectedTypeInfoImpl;
+import com.intellij.codeInsight.TailType;
+import com.intellij.codeInsight.lookup.LookupElement;
+import com.intellij.codeInsight.lookup.LookupElementBuilder;
+import com.intellij.psi.*;
+import com.intellij.psi.filters.ElementFilter;
+import com.intellij.psi.util.PsiUtil;
+import com.intellij.util.Consumer;
+import com.intellij.util.ProcessingContext;
+import org.jetbrains.annotations.NotNull;
+
+public class MethodReferenceCompletionProvider extends CompletionProvider<CompletionParameters> {
+  @Override
+  protected void addCompletions(@NotNull CompletionParameters parameters,
+                                ProcessingContext context,
+                                @NotNull final CompletionResultSet result) {
+    if (!PsiUtil.isLanguageLevel8OrHigher(parameters.getOriginalFile())) return;
+    final ExpectedTypeInfo[] expectedTypes = JavaSmartCompletionContributor.getExpectedTypes(parameters);
+    for (ExpectedTypeInfo expectedType : expectedTypes) {
+      final PsiType defaultType = expectedType.getDefaultType();
+      if (LambdaHighlightingUtil.checkInterfaceFunctional(defaultType) == null) {
+        final PsiType returnType = LambdaUtil.getFunctionalInterfaceReturnType(defaultType);
+        if (returnType != null) {
+          final ExpectedTypeInfoImpl typeInfo =
+            new ExpectedTypeInfoImpl(returnType, ExpectedTypeInfo.TYPE_OR_SUBTYPE, returnType, TailType.UNKNOWN, null,
+                                     ExpectedTypeInfoImpl.NULL);
+          Consumer<LookupElement> noTypeCheck = new Consumer<LookupElement>() {
+            @Override
+            public void consume(final LookupElement lookupElement) {
+              result.addElement(lookupElement);
+            }
+          };
+
+          final Runnable runnable = ReferenceExpressionCompletionContributor
+            .fillCompletionVariants(new JavaSmartCompletionParameters(parameters, typeInfo), noTypeCheck);
+          if (runnable != null) {
+            runnable.run();
+          }
+        }
+      }
+    }
+  }
+}
diff --git a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java
index e58de29..8f854b1 100644
--- a/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java
+++ b/java/java-impl/src/com/intellij/codeInsight/generation/OverrideImplementUtil.java
@@ -246,7 +246,10 @@
 
   public static void annotateOnOverrideImplement(PsiMethod method, PsiClass targetClass, PsiMethod overridden, boolean insertOverride) {
     if (insertOverride && canInsertOverride(overridden, targetClass)) {
-      AddAnnotationPsiFix.addPhysicalAnnotation(Override.class.getName(), PsiNameValuePair.EMPTY_ARRAY, method.getModifierList());
+      final String overrideAnnotationName = Override.class.getName();
+      if (!AnnotationUtil.isAnnotated(method, overrideAnnotationName, false, true)) {
+        AddAnnotationPsiFix.addPhysicalAnnotation(overrideAnnotationName, PsiNameValuePair.EMPTY_ARRAY, method.getModifierList());
+      }
     }
     final Module module = ModuleUtilCore.findModuleForPsiElement(targetClass);
     final GlobalSearchScope moduleScope = module != null ? GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module) : null;
diff --git a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExceptionsHandler.java b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExceptionsHandler.java
index 495bad2..bd57f73 100644
--- a/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExceptionsHandler.java
+++ b/java/java-impl/src/com/intellij/codeInsight/highlighting/HighlightExceptionsHandler.java
@@ -89,7 +89,9 @@
               }
               else if (psiExpression instanceof PsiNewExpression) {
                 PsiJavaCodeReferenceElement ref = ((PsiNewExpression)psiExpression).getClassReference();
-                addOccurrence(ref);
+                if (ref != null) {
+                  addOccurrence(ref);
+                }
               }
               else {
                 addOccurrence(statement.getException());
diff --git a/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/MethodParameterInfoHandler.java b/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/MethodParameterInfoHandler.java
index 63e9ba0..427383c 100644
--- a/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/MethodParameterInfoHandler.java
+++ b/java/java-impl/src/com/intellij/codeInsight/hint/api/impls/MethodParameterInfoHandler.java
@@ -228,10 +228,15 @@
       PsiExpression arg = args[j];
       assert parm.isValid();
       assert arg.isValid();
-      PsiType parmType = substitutor.substitute(parm.getType());
+      PsiType parmType = parm.getType();
       PsiType argType = arg.getType();
+      if (argType == null) continue;
+      if (parmType instanceof PsiEllipsisType && parmType.getArrayDimensions() == argType.getArrayDimensions() + 1) {
+        parmType = ((PsiEllipsisType)parmType).getComponentType();
+      }
+      parmType = substitutor.substitute(parmType);
 
-      if (argType != null && !parmType.isAssignableFrom(argType)) {
+      if (!parmType.isAssignableFrom(argType)) {
         return false;
       }
     }
diff --git a/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java b/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java
new file mode 100644
index 0000000..22d61cb
--- /dev/null
+++ b/java/java-impl/src/com/intellij/codeInspection/RedundantSuppressInspection.java
@@ -0,0 +1,32 @@
+/*
+ * 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.codeInspection;
+
+import com.intellij.codeInspection.ex.GlobalInspectionContextBase;
+import com.intellij.codeInspection.ex.InspectionManagerEx;
+import com.intellij.psi.PsiFile;
+
+/**
+ * User: anna
+ * Date: 11/27/13
+ */
+public class RedundantSuppressInspection extends RedundantSuppressInspectionBase {
+  @Override
+  protected GlobalInspectionContextBase createContext(PsiFile file) {
+    final InspectionManagerEx inspectionManagerEx = ((InspectionManagerEx)InspectionManager.getInstance(file.getProject()));
+    return inspectionManagerEx.createNewGlobalContext(false);
+  }
+}
diff --git a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java
index bb3354b..b1c0421 100644
--- a/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java
+++ b/java/java-impl/src/com/intellij/codeInspection/dataFlow/DataFlowInspection.java
@@ -35,8 +35,8 @@
 
 public class DataFlowInspection extends DataFlowInspectionBase {
   @Override
-  protected void addSurroundWithIfFix(PsiExpression qualifier, List<LocalQuickFix> fixes) {
-    if (SurroundWithIfFix.isAvailable(qualifier)) {
+  protected void addSurroundWithIfFix(PsiExpression qualifier, List<LocalQuickFix> fixes, boolean onTheFly) {
+    if (onTheFly && SurroundWithIfFix.isAvailable(qualifier)) {
       fixes.add(new SurroundWithIfFix(qualifier));
     }
   }
diff --git a/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/FileHeaderChecker.java b/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/FileHeaderChecker.java
index ffdd14f..85ccbf9 100644
--- a/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/FileHeaderChecker.java
+++ b/java/java-impl/src/com/intellij/codeInspection/defaultFileTemplateUsage/FileHeaderChecker.java
@@ -55,7 +55,7 @@
       .getDefaultTemplate(FileTemplateManager.FILE_HEADER_TEMPLATE_NAME),
                                          file.getProject(), offsetToProperty
     );
-    Matcher matcher = pattern.matcher(file.getText());
+    Matcher matcher = pattern.matcher(file.getViewProvider().getContents());
     if (matcher.matches()) {
       final int startOffset = matcher.start(1);
       final int endOffset = matcher.end(1);
diff --git a/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java b/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java
index e56a432..2106f17 100644
--- a/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java
+++ b/java/java-impl/src/com/intellij/ide/projectView/actions/MarkGeneratedSourceRootAction.java
@@ -35,7 +35,7 @@
 public class MarkGeneratedSourceRootAction extends MarkRootActionBase {
   public MarkGeneratedSourceRootAction() {
     Presentation presentation = getTemplatePresentation();
-    presentation.setIcon(AllIcons.Modules.SourceRoot);
+    presentation.setIcon(AllIcons.Modules.GeneratedSourceRoot);
     presentation.setText("Generated Sources Root");
     presentation.setDescription("Mark directory as a source root for generated files");
   }
diff --git a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java
index fe598e3..fbd46ac8 100644
--- a/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java
+++ b/java/java-impl/src/com/intellij/javadoc/JavadocConfiguration.java
@@ -56,9 +56,7 @@
 import java.io.FileWriter;
 import java.io.IOException;
 import java.io.PrintWriter;
-import java.util.Collection;
-import java.util.List;
-import java.util.Set;
+import java.util.*;
 
 /**
  * @author Eugene Zhuravlev
@@ -230,36 +228,7 @@
 
       parameters.addParametersString(OTHER_OPTIONS);
 
-      final Set<Module> modules = new HashSet<Module>();
-      myGenerationOptions.accept(new PsiRecursiveElementWalkingVisitor() {
-        @Override
-        public void visitFile(PsiFile file) {
-          final Module module = ModuleUtilCore.findModuleForPsiElement(file);
-          if (module != null) {
-            modules.add(module);
-          }
-        }
-      });
-      final PathsList classPath;
-      final OrderEnumerator orderEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules);
-      if (jdk.getSdkType() instanceof JavaSdk) {
-        classPath = orderEnumerator.withoutSdk().withoutModuleSourceEntries().getPathsList();
-      }
-      else {
-        //libraries are included into jdk
-        classPath = orderEnumerator.withoutModuleSourceEntries().getPathsList();
-      }
-      final String classPathString = classPath.getPathsString();
-      if (classPathString.length() > 0) {
-        parameters.add("-classpath");
-        parameters.add(classPathString);
-      }
-
-      if (OUTPUT_DIRECTORY != null) {
-        parameters.add("-d");
-        parameters.add(OUTPUT_DIRECTORY.replace('/', File.separatorChar));
-      }
-
+      final Set<Module> modules = new LinkedHashSet<Module>();
       try {
         final File sourcePathTempFile = FileUtil.createTempFile("javadoc", "args.txt", true);
         parameters.add("@" + sourcePathTempFile.getCanonicalPath());
@@ -274,10 +243,10 @@
                                                  scopeType == AnalysisScope.MODULES ||
                                                  scopeType == AnalysisScope.PROJECT ||
                                                  scopeType == AnalysisScope.DIRECTORY;
-              myGenerationOptions.accept(new MyContentIterator(myProject, packages, sources, usePackageNotation));
+              myGenerationOptions.accept(new MyContentIterator(myProject, packages, sources, modules, usePackageNotation));
             }
           };
-          if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRunnable, "Search for sources to generate javadoc in...", false, myProject)) {
+          if (!ProgressManager.getInstance().runProcessWithProgressSynchronously(findRunnable, "Search for sources to generate javadoc in...", true, myProject)) {
             return;
           }
           if (packages.size() + sources.size() == 0) {
@@ -319,6 +288,27 @@
       catch (IOException e) {
         LOGGER.error(e);
       }
+
+      final PathsList classPath;
+      final OrderEnumerator orderEnumerator = ProjectRootManager.getInstance(myProject).orderEntries(modules);
+      if (jdk.getSdkType() instanceof JavaSdk) {
+        classPath = orderEnumerator.withoutSdk().withoutModuleSourceEntries().getPathsList();
+      }
+      else {
+        //libraries are included into jdk
+        classPath = orderEnumerator.withoutModuleSourceEntries().getPathsList();
+      }
+      final String classPathString = classPath.getPathsString();
+      if (classPathString.length() > 0) {
+        parameters.add("-classpath");
+        parameters.add(classPathString);
+      }
+
+      if (OUTPUT_DIRECTORY != null) {
+        parameters.add("-d");
+        parameters.add(OUTPUT_DIRECTORY.replace('/', File.separatorChar));
+      }
+
     }
 
     @NotNull
@@ -343,9 +333,15 @@
     private final PsiManager myPsiManager;
     private final Collection<String> myPackages;
     private final Collection<String> mySourceFiles;
+    private final Set<Module> myModules;
     private final boolean myUsePackageNotation;
 
-    public MyContentIterator(Project project, Collection<String> packages, Collection<String> sources, boolean canUsePackageNotation) {
+    public MyContentIterator(Project project,
+                             Collection<String> packages,
+                             Collection<String> sources,
+                             Set<Module> modules,
+                             boolean canUsePackageNotation) {
+      myModules = modules;
       myUsePackageNotation = canUsePackageNotation;
       myPsiManager = PsiManager.getInstance(project);
       myPackages = packages;
@@ -357,7 +353,10 @@
       final VirtualFile fileOrDir = file.getVirtualFile();
       if (fileOrDir == null) return;
       if (!fileOrDir.isInLocalFileSystem()) return;
-      final Module module = ModuleUtil.findModuleForFile(fileOrDir, myPsiManager.getProject());
+      final Module module = ModuleUtilCore.findModuleForFile(fileOrDir, myPsiManager.getProject());
+      if (module != null) {
+        myModules.add(module);
+      }
       if (file instanceof PsiJavaFile) {
         final PsiJavaFile javaFile = (PsiJavaFile)file;
         final String packageName = javaFile.getPackageName();
diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntryDependencyInfo.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntryDependencyInfo.java
new file mode 100644
index 0000000..f579044
--- /dev/null
+++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/ArrangementEntryDependencyInfo.java
@@ -0,0 +1,55 @@
+/*
+ * 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.
+ * 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.codeStyle.arrangement;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Denis Zhdanov
+ * @since 9/19/12 6:41 PM
+ */
+public class ArrangementEntryDependencyInfo {
+
+  @NotNull private final List<ArrangementEntryDependencyInfo> myDependentEntries = new ArrayList<ArrangementEntryDependencyInfo>();
+  
+  @NotNull private final JavaElementArrangementEntry myAnchorEntry;
+
+  public ArrangementEntryDependencyInfo(@NotNull JavaElementArrangementEntry entry) {
+    myAnchorEntry= entry;
+  }
+
+  public void addDependentEntryInfo(@NotNull ArrangementEntryDependencyInfo info) {
+    myDependentEntries.add(info);
+  }
+  
+  @NotNull
+  public List<ArrangementEntryDependencyInfo> getDependentEntriesInfos() {
+    return myDependentEntries;
+  }
+
+  @NotNull
+  public JavaElementArrangementEntry getAnchorEntry() {
+    return myAnchorEntry;
+  }
+
+  @Override
+  public String toString() {
+    return myAnchorEntry.toString();
+  }
+}
diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementMethodDependencyInfo.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementMethodDependencyInfo.java
deleted file mode 100644
index c4cb392..0000000
--- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementMethodDependencyInfo.java
+++ /dev/null
@@ -1,56 +0,0 @@
-/*
- * 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.
- * 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.codeStyle.arrangement;
-
-import org.jetbrains.annotations.NotNull;
-
-import java.util.ArrayList;
-import java.util.List;
-
-/**
- * @author Denis Zhdanov
- * @since 9/19/12 6:41 PM
- */
-public class JavaArrangementMethodDependencyInfo {
-
-  @NotNull private final List<JavaArrangementMethodDependencyInfo> myDependentMethods
-    = new ArrayList<JavaArrangementMethodDependencyInfo>();
-  
-  @NotNull private final JavaElementArrangementEntry myAnchorMethod;
-
-  public JavaArrangementMethodDependencyInfo(@NotNull JavaElementArrangementEntry method) {
-    myAnchorMethod = method;
-  }
-
-  public void addDependentMethodInfo(@NotNull JavaArrangementMethodDependencyInfo info) {
-    myDependentMethods.add(info);
-  }
-  
-  @NotNull
-  public List<JavaArrangementMethodDependencyInfo> getDependentMethodInfos() {
-    return myDependentMethods;
-  }
-
-  @NotNull
-  public JavaElementArrangementEntry getAnchorMethod() {
-    return myAnchorMethod;
-  }
-
-  @Override
-  public String toString() {
-    return myAnchorMethod.toString();
-  }
-}
diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java
index 3497c23..2796fec 100644
--- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java
+++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementParseInfo.java
@@ -17,6 +17,7 @@
 
 import com.intellij.openapi.util.Pair;
 import com.intellij.psi.PsiClass;
+import com.intellij.psi.PsiField;
 import com.intellij.psi.PsiMethod;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
@@ -40,8 +41,8 @@
   @NotNull private final Map<Pair<String/* property name */, String/* class name */>, JavaArrangementPropertyInfo> myProperties
     = new HashMap<Pair<String, String>, JavaArrangementPropertyInfo>();
 
-  @NotNull private final List<JavaArrangementMethodDependencyInfo> myMethodDependencyRoots
-    = new ArrayList<JavaArrangementMethodDependencyInfo>();
+  @NotNull private final List<ArrangementEntryDependencyInfo> myMethodDependencyRoots
+    = new ArrayList<ArrangementEntryDependencyInfo>();
 
   @NotNull private final Map<PsiMethod /* anchor */, Set<PsiMethod /* dependencies */>> myMethodDependencies
     = new HashMap<PsiMethod, Set<PsiMethod>>();
@@ -54,10 +55,10 @@
 
   @NotNull private final Set<PsiMethod> myTmpMethodDependencyRoots = new LinkedHashSet<PsiMethod>();
   @NotNull private final Set<PsiMethod> myDependentMethods         = new HashSet<PsiMethod>();
-
-
   private boolean myRebuildMethodDependencies;
 
+  @NotNull private FieldDependenciesManager myFieldDependenciesManager = new FieldDependenciesManager();
+
   @NotNull
   public List<JavaElementArrangementEntry> getEntries() {
     return myEntries;
@@ -74,16 +75,16 @@
 
   /**
    * @return    list of method dependency roots, i.e. there is a possible case that particular method
-   *            {@link JavaArrangementMethodDependencyInfo#getDependentMethodInfos() calls another method}, it calls other methods
+   *            {@link ArrangementEntryDependencyInfo#getDependentEntriesInfos() calls another method}, it calls other methods
    *            and so forth
    */
   @NotNull
-  public List<JavaArrangementMethodDependencyInfo> getMethodDependencyRoots() {
+  public List<ArrangementEntryDependencyInfo> getMethodDependencyRoots() {
     if (myRebuildMethodDependencies) {
       myMethodDependencyRoots.clear();
-      Map<PsiMethod, JavaArrangementMethodDependencyInfo> cache = new HashMap<PsiMethod, JavaArrangementMethodDependencyInfo>();
+      Map<PsiMethod, ArrangementEntryDependencyInfo> cache = new HashMap<PsiMethod, ArrangementEntryDependencyInfo>();
       for (PsiMethod method : myTmpMethodDependencyRoots) {
-        JavaArrangementMethodDependencyInfo info = buildMethodDependencyInfo(method, cache);
+        ArrangementEntryDependencyInfo info = buildMethodDependencyInfo(method, cache);
         if (info != null) {
           myMethodDependencyRoots.add(info);
         }
@@ -94,20 +95,20 @@
   }
 
   @Nullable
-  private JavaArrangementMethodDependencyInfo buildMethodDependencyInfo(@NotNull final PsiMethod method,
-                                                                        @NotNull Map<PsiMethod, JavaArrangementMethodDependencyInfo> cache)
+  private ArrangementEntryDependencyInfo buildMethodDependencyInfo(@NotNull final PsiMethod method,
+                                                                        @NotNull Map<PsiMethod, ArrangementEntryDependencyInfo> cache)
   {
     JavaElementArrangementEntry entry = myMethodEntriesMap.get(method);
     if (entry == null) {
       return null;
     }
-    JavaArrangementMethodDependencyInfo result = new JavaArrangementMethodDependencyInfo(entry);
-    Stack<Pair<PsiMethod, JavaArrangementMethodDependencyInfo>> toProcess
-      = new Stack<Pair<PsiMethod, JavaArrangementMethodDependencyInfo>>();
+    ArrangementEntryDependencyInfo result = new ArrangementEntryDependencyInfo(entry);
+    Stack<Pair<PsiMethod, ArrangementEntryDependencyInfo>> toProcess
+      = new Stack<Pair<PsiMethod, ArrangementEntryDependencyInfo>>();
     toProcess.push(Pair.create(method, result));
     Set<PsiMethod> usedMethods = ContainerUtilRt.newHashSet();
     while (!toProcess.isEmpty()) {
-      Pair<PsiMethod, JavaArrangementMethodDependencyInfo> pair = toProcess.pop();
+      Pair<PsiMethod, ArrangementEntryDependencyInfo> pair = toProcess.pop();
       Set<PsiMethod> dependentMethods = myMethodDependencies.get(pair.first);
       if (dependentMethods == null) {
         continue;
@@ -122,12 +123,12 @@
         if (dependentEntry == null) {
           continue;
         }
-        JavaArrangementMethodDependencyInfo dependentMethodInfo = cache.get(dependentMethod);
+        ArrangementEntryDependencyInfo dependentMethodInfo = cache.get(dependentMethod);
         if (dependentMethodInfo == null) {
-          cache.put(dependentMethod, dependentMethodInfo = new JavaArrangementMethodDependencyInfo(dependentEntry));
+          cache.put(dependentMethod, dependentMethodInfo = new ArrangementEntryDependencyInfo(dependentEntry));
         }
-        Pair<PsiMethod, JavaArrangementMethodDependencyInfo> dependentPair = Pair.create(dependentMethod, dependentMethodInfo);
-        pair.second.addDependentMethodInfo(dependentPair.second);
+        Pair<PsiMethod, ArrangementEntryDependencyInfo> dependentPair = Pair.create(dependentMethod, dependentMethodInfo);
+        pair.second.addDependentEntryInfo(dependentPair.second);
         toProcess.push(dependentPair);
       }
     }
@@ -156,6 +157,10 @@
     myMethodEntriesMap.put(method, entry);
   }
 
+  public void onFieldEntryCreated(@NotNull PsiField field, @NotNull JavaElementArrangementEntry entry) {
+    myFieldDependenciesManager.registerFieldAndEntry(field, entry);
+  }
+
   public void onOverriddenMethod(@NotNull PsiMethod baseMethod, @NotNull PsiMethod overridingMethod) {
     PsiClass clazz = baseMethod.getContainingClass();
     if (clazz == null) {
@@ -203,23 +208,67 @@
   /**
    * Is expected to be called when new method dependency is detected. Here given <code>'base method'</code> calls
    * <code>'dependent method'</code>.
-   * 
-   * @param baseMethod       method which calls another method
-   * @param dependentMethod  method being called
    */
-  public void registerDependency(@NotNull PsiMethod baseMethod, @NotNull PsiMethod dependentMethod) {
-    myTmpMethodDependencyRoots.remove(dependentMethod);
-    if (!myDependentMethods.contains(baseMethod)) {
-      myTmpMethodDependencyRoots.add(baseMethod);
+  public void registerMethodCallDependency(@NotNull PsiMethod caller, @NotNull PsiMethod callee) {
+    myTmpMethodDependencyRoots.remove(callee);
+    if (!myDependentMethods.contains(caller)) {
+      myTmpMethodDependencyRoots.add(caller);
     }
-    myDependentMethods.add(dependentMethod);
-    Set<PsiMethod> methods = myMethodDependencies.get(baseMethod);
+    myDependentMethods.add(callee);
+    Set<PsiMethod> methods = myMethodDependencies.get(caller);
     if (methods == null) {
-      myMethodDependencies.put(baseMethod, methods = new LinkedHashSet<PsiMethod>());
+      myMethodDependencies.put(caller, methods = new LinkedHashSet<PsiMethod>());
     }
-    if (!methods.contains(dependentMethod)) {
-      methods.add(dependentMethod);
+    if (!methods.contains(callee)) {
+      methods.add(callee);
     }
     myRebuildMethodDependencies = true;
   }
-}
+
+  public void registerFieldInitializationDependency(@NotNull PsiField fieldToInitialize, @NotNull PsiField usedInInitialization) {
+    myFieldDependenciesManager.registerInitializationDependency(fieldToInitialize, usedInInitialization);
+  }
+
+  @NotNull
+  public List<ArrangementEntryDependencyInfo> getFieldDependencyRoots() {
+    return myFieldDependenciesManager.getRoots();
+  }
+
+  private static class FieldDependenciesManager {
+    private final Map<PsiField, Set<PsiField>> myFieldDependencies = ContainerUtil.newHashMap();
+    private final Map<PsiField, ArrangementEntryDependencyInfo> myFieldInfosMap = ContainerUtil.newHashMap();
+
+
+    public void registerFieldAndEntry(@NotNull PsiField field, @NotNull JavaElementArrangementEntry entry) {
+      myFieldInfosMap.put(field, new ArrangementEntryDependencyInfo(entry));
+    }
+
+    public void registerInitializationDependency(@NotNull PsiField fieldToInitialize, @NotNull PsiField usedInInitialization) {
+      Set<PsiField> fields = myFieldDependencies.get(fieldToInitialize);
+      if (fields == null) {
+        fields = new HashSet<PsiField>();
+        myFieldDependencies.put(fieldToInitialize, fields);
+      }
+      fields.add(usedInInitialization);
+    }
+
+    @NotNull
+    public List<ArrangementEntryDependencyInfo> getRoots() {
+      List<ArrangementEntryDependencyInfo> list = ContainerUtil.newArrayList();
+
+      for (Map.Entry<PsiField, Set<PsiField>> entry : myFieldDependencies.entrySet()) {
+        ArrangementEntryDependencyInfo currentInfo = myFieldInfosMap.get(entry.getKey());
+
+        for (PsiField usedInInitialization : entry.getValue()) {
+          ArrangementEntryDependencyInfo fieldInfo = myFieldInfosMap.get(usedInInitialization);
+          if (fieldInfo != null)
+            currentInfo.addDependentEntryInfo(fieldInfo);
+        }
+
+        list.add(currentInfo);
+      }
+
+      return list;
+    }
+  }
+}
\ No newline at end of file
diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java
index a5fd586..826ad21 100644
--- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java
+++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaArrangementVisitor.java
@@ -17,7 +17,6 @@
 
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.util.TextRange;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.arrangement.std.ArrangementSettingsToken;
 import com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens;
@@ -29,10 +28,7 @@
 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 java.util.*;
 
 import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType.*;
 import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Modifier.*;
@@ -163,10 +159,40 @@
         break;
       }
     }
+
     JavaElementArrangementEntry entry = createNewEntry(field, range, FIELD, field.getName(), true);
-    processEntry(entry, field, field.getInitializer());
+    if (entry == null)
+      return;
+
+    PsiExpression fieldInitializer = field.getInitializer();
+    processEntry(entry, field, fieldInitializer);
+    myInfo.onFieldEntryCreated(field, entry);
+
+    if (fieldInitializer != null) {
+      List<PsiField> referencedFields = getReferencedFields(fieldInitializer);
+      for (PsiField referencedField : referencedFields) {
+        myInfo.registerFieldInitializationDependency(field, referencedField);
+      }
+    }
   }
 
+  @NotNull
+  private List<PsiField> getReferencedFields(@NotNull PsiExpression expression) {
+    final List<PsiField> referencedElements = new ArrayList<PsiField>();
+    expression.accept(new JavaRecursiveElementVisitor() {
+      @Override
+      public void visitReferenceExpression(PsiReferenceExpression expression) {
+        PsiElement ref = expression.resolve();
+        if (ref instanceof PsiField) {
+          referencedElements.add((PsiField)ref);
+        }
+      }
+    });
+
+    return referencedElements;
+  }
+
+
   @Nullable
   private static PsiElement getPreviousNonWsComment(@Nullable PsiElement element, int minOffset) {
     if (element == null) {
@@ -443,7 +469,7 @@
         assert myBaseMethod != null;
         PsiMethod m = (PsiMethod)e;
         if (m.getContainingClass() == myBaseMethod.getContainingClass()) {
-          myInfo.registerDependency(myBaseMethod, m);
+          myInfo.registerMethodCallDependency(myBaseMethod, m);
         }
       }
       
diff --git a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java
index 001745c..cc35e7d 100644
--- a/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java
+++ b/java/java-impl/src/com/intellij/psi/codeStyle/arrangement/JavaRearranger.java
@@ -121,12 +121,12 @@
 
   private static void setupUtilityMethods(@NotNull JavaArrangementParseInfo info, @NotNull ArrangementSettingsToken orderType) {
     if (DEPTH_FIRST.equals(orderType)) {
-      for (JavaArrangementMethodDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
+      for (ArrangementEntryDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
         setupDepthFirstDependency(rootInfo);
       }
     }
     else if (BREADTH_FIRST.equals(orderType)) {
-      for (JavaArrangementMethodDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
+      for (ArrangementEntryDependencyInfo rootInfo : info.getMethodDependencyRoots()) {
         setupBreadthFirstDependency(rootInfo);
       }
     }
@@ -135,25 +135,25 @@
     }
   }
 
-  private static void setupDepthFirstDependency(@NotNull JavaArrangementMethodDependencyInfo info) {
-    for (JavaArrangementMethodDependencyInfo dependencyInfo : info.getDependentMethodInfos()) {
+  private static void setupDepthFirstDependency(@NotNull ArrangementEntryDependencyInfo info) {
+    for (ArrangementEntryDependencyInfo dependencyInfo : info.getDependentEntriesInfos()) {
       setupDepthFirstDependency(dependencyInfo);
-      JavaElementArrangementEntry dependentEntry = dependencyInfo.getAnchorMethod();
+      JavaElementArrangementEntry dependentEntry = dependencyInfo.getAnchorEntry();
       if (dependentEntry.getDependencies() == null) {
-        dependentEntry.addDependency(info.getAnchorMethod());
+        dependentEntry.addDependency(info.getAnchorEntry());
       }
     }
   }
 
-  private static void setupBreadthFirstDependency(@NotNull JavaArrangementMethodDependencyInfo info) {
-    Deque<JavaArrangementMethodDependencyInfo> toProcess = new ArrayDeque<JavaArrangementMethodDependencyInfo>();
+  private static void setupBreadthFirstDependency(@NotNull ArrangementEntryDependencyInfo info) {
+    Deque<ArrangementEntryDependencyInfo> toProcess = new ArrayDeque<ArrangementEntryDependencyInfo>();
     toProcess.add(info);
     while (!toProcess.isEmpty()) {
-      JavaArrangementMethodDependencyInfo current = toProcess.removeFirst();
-      for (JavaArrangementMethodDependencyInfo dependencyInfo : current.getDependentMethodInfos()) {
-        JavaElementArrangementEntry dependencyMethod = dependencyInfo.getAnchorMethod();
+      ArrangementEntryDependencyInfo current = toProcess.removeFirst();
+      for (ArrangementEntryDependencyInfo dependencyInfo : current.getDependentEntriesInfos()) {
+        JavaElementArrangementEntry dependencyMethod = dependencyInfo.getAnchorEntry();
         if (dependencyMethod.getDependencies() == null) {
-          dependencyMethod.addDependency(current.getAnchorMethod());
+          dependencyMethod.addDependency(current.getAnchorEntry());
         }
         toProcess.addLast(dependencyInfo);
       }
@@ -216,9 +216,21 @@
         }
       }
     }
+    setupFieldInitializationDependencies(parseInfo.getFieldDependencyRoots());
     return parseInfo.getEntries();
   }
 
+
+  public void setupFieldInitializationDependencies(@NotNull List<ArrangementEntryDependencyInfo> list) {
+    for (ArrangementEntryDependencyInfo info : list) {
+      JavaElementArrangementEntry anchorField = info.getAnchorEntry();
+      for (ArrangementEntryDependencyInfo fieldUsedInInitialization : info.getDependentEntriesInfos()) {
+        anchorField.addDependency(fieldUsedInInitialization.getAnchorEntry());
+      }
+    }
+  }
+
+
   @Override
   public int getBlankLines(@NotNull CodeStyleSettings settings,
                            @Nullable JavaElementArrangementEntry parent,
diff --git a/java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java b/java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java
index 8efae16..795e66e 100644
--- a/java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java
+++ b/java/java-impl/src/com/intellij/psi/impl/JavaDirectoryIconProvider.java
@@ -23,7 +23,7 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.roots.SourceFolder;
-import com.intellij.openapi.roots.ui.configuration.ModuleSourceRootEditHandler;
+import com.intellij.openapi.roots.ui.configuration.SourceRootPresentation;
 import com.intellij.openapi.vfs.JarFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.JavaDirectoryService;
@@ -63,7 +63,7 @@
         }
       }
       else if (sourceFolder != null) {
-        symbolIcon = ModuleSourceRootEditHandler.getEditHandler(sourceFolder.getRootType()).getRootIcon();
+        symbolIcon = SourceRootPresentation.getSourceRootIcon(sourceFolder);
       }
       else if (JavaDirectoryService.getInstance().getPackage(psiDirectory) != null) {
         symbolIcon = PlatformIcons.PACKAGE_ICON;
diff --git a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java
index 6026d8f..ee207fb 100644
--- a/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/changeClassSignature/ChangeClassSignatureProcessor.java
@@ -26,6 +26,7 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.changeSignature.ChangeSignatureUtil;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.util.RefactoringUIUtil;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.usageView.UsageViewDescriptor;
@@ -33,6 +34,7 @@
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.MultiMap;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
 
@@ -117,6 +119,28 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.changeClassSignature";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myClass);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myClass);
+    return data;
+  }
+
   private void doRefactoring(UsageInfo[] usages) throws IncorrectOperationException {
     final PsiTypeParameter[] typeParameters = myClass.getTypeParameters();
     final boolean[] toRemoveParms = detectRemovedParameters(typeParameters);
diff --git a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessor.java b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessor.java
index 1f9ec4d..17cef58 100644
--- a/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
diff --git a/java/java-impl/src/com/intellij/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java
index c3a8d72..5804445 100644
--- a/java/java-impl/src/com/intellij/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/convertToInstanceMethod/ConvertToInstanceMethodProcessor.java
@@ -32,6 +32,7 @@
 import com.intellij.psi.util.TypeConversionUtil;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.move.moveInstanceMethod.MoveInstanceMethodViewDescriptor;
 import com.intellij.refactoring.util.*;
 import com.intellij.usageView.UsageInfo;
@@ -132,6 +133,28 @@
   }
 
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.makeInstance";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(new PsiElement[]{myMethod, myTargetClass});
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myTargetClass);
+    return data;
+  }
+
   protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
     UsageInfo[] usagesIn = refUsages.get();
     MultiMap<PsiElement, String> conflicts = new MultiMap<PsiElement, String>();
diff --git a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java
index 986f98b..93d9f089 100644
--- a/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/encapsulateFields/EncapsulateFieldsProcessor.java
@@ -1,4 +1,3 @@
-
 /*
  * Copyright 2000-2013 JetBrains s.r.o.
  *
@@ -27,6 +26,7 @@
 import com.intellij.psi.util.*;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.refactoring.util.DocCommentPolicy;
 import com.intellij.refactoring.util.RefactoringUIUtil;
@@ -39,6 +39,7 @@
 import com.intellij.util.containers.HashMap;
 import com.intellij.util.containers.MultiMap;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
 
@@ -72,6 +73,39 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.encapsulateFields";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    final List<PsiElement> fields = new ArrayList<PsiElement>();
+    for (FieldDescriptor fieldDescriptor : myFieldDescriptors) {
+      fields.add(fieldDescriptor.getField());
+    }
+    data.addElements(fields);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    List<PsiElement> elements = new ArrayList<PsiElement>();
+    if (myNameToGetter != null) {
+      elements.addAll(myNameToGetter.values());
+    }
+    if (myNameToSetter != null) {
+      elements.addAll(myNameToSetter.values());
+    }
+    data.addElements(elements);
+    return data;
+  }
+
   @NotNull
   protected UsageViewDescriptor createUsageViewDescriptor(UsageInfo[] usages) {
     FieldDescriptor[] fields = new FieldDescriptor[myFieldDescriptors.length];
diff --git a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java
index f3f7c85..659ebfb 100644
--- a/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/extractMethod/ExtractMethodHandler.java
@@ -45,6 +45,8 @@
 import com.intellij.refactoring.RefactoringActionHandler;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.refactoring.util.RefactoringUtil;
 import com.intellij.refactoring.util.duplicates.DuplicatesImpl;
@@ -151,7 +153,14 @@
         PostprocessReformattingAspect.getInstance(project).postponeFormattingInside(new Runnable() {
           public void run() {
             try {
+              project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC)
+                .refactoringStarted("refactoring.extract.method", new RefactoringEventData());
+              
               processor.doRefactoring();
+
+              final RefactoringEventData data = new RefactoringEventData();
+              data.addElement(processor.getExtractedMethod());
+              project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone("refactoring.extract.method", data);
             }
             catch (IncorrectOperationException e) {
               LOG.error(e);
diff --git a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseProcessor.java b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseProcessor.java
index 0d608e7..aae2d48 100644
--- a/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/extractSuperclass/ExtractSuperBaseProcessor.java
@@ -25,6 +25,7 @@
 import com.intellij.psi.util.InheritanceUtil;
 import com.intellij.psi.util.MethodSignatureUtil;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.turnRefsToSuper.TurnRefsToSuperProcessorBase;
 import com.intellij.refactoring.util.DocCommentPolicy;
 import com.intellij.refactoring.util.RefactoringUIUtil;
@@ -33,11 +34,14 @@
 import com.intellij.usageView.UsageInfo;
 import com.intellij.usageView.UsageViewDescriptor;
 import com.intellij.usageView.UsageViewUtil;
+import com.intellij.util.Function;
 import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.Collection;
+import java.util.List;
 
 /**
  * @author dsl
@@ -102,6 +106,34 @@
     return false;
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.extractSuper";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myClass);
+    data.addMembers(myMemberInfos, new Function<MemberInfo, PsiElement>() {
+      @Override
+      public PsiElement fun(MemberInfo info) {
+        return info.getMember();
+      }
+    });
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myClass);
+    return data;
+  }
+
   @NotNull
   protected UsageInfo[] findUsages() {
     PsiReference[] refs = ReferencesSearch.search(myClass, GlobalSearchScope.projectScope(myProject), false).toArray(new PsiReference[0]);
diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java
index 508a32f..f6ef8ff 100644
--- a/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineConstantFieldProcessor.java
@@ -27,6 +27,8 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.rename.NonCodeUsageInfoFactory;
 import com.intellij.refactoring.util.*;
 import com.intellij.usageView.UsageInfo;
@@ -34,6 +36,7 @@
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.MultiMap;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
 
@@ -168,6 +171,20 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myField);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.inline.field";
+  }
+
   private void inlineExpressionUsage(PsiExpression expr,
                                      PsiExpression initializer1) throws IncorrectOperationException {
     if (myField.isWritable()) {
diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java
index 72938065..aaece25 100644
--- a/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineMethodProcessor.java
@@ -47,6 +47,8 @@
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.introduceParameter.Util;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.rename.NonCodeUsageInfoFactory;
 import com.intellij.refactoring.rename.RenameJavaVariableProcessor;
 import com.intellij.refactoring.util.*;
@@ -389,6 +391,20 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.inline.method";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    final RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myMethod);
+    return data;
+  }
+
   private void doRefactoring(UsageInfo[] usages) {
     try {
       if (myInlineThisOnly) {
diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterExpressionProcessor.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterExpressionProcessor.java
index b7caffe..81c5b69 100644
--- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterExpressionProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterExpressionProcessor.java
@@ -50,7 +50,7 @@
   private final PsiParameter myParameter;
   private PsiExpression myInitializer;
   private final boolean mySameClass;
-  private final PsiMethod myCallingMethod;
+  private final PsiCodeBlock myCallingBlock;
   private final boolean myCreateLocal;
 
   public InlineParameterExpressionProcessor(final PsiCallExpression methodCall,
@@ -67,7 +67,7 @@
 
     PsiClass callingClass = PsiTreeUtil.getParentOfType(methodCall, PsiClass.class);
     mySameClass = (callingClass == myMethod.getContainingClass());
-    myCallingMethod = PsiTreeUtil.getParentOfType(myMethodCall, PsiMethod.class);
+    myCallingBlock = PsiTreeUtil.getTopmostParentOfType(myMethodCall, PsiCodeBlock.class);
   }
 
   @Override
@@ -110,7 +110,7 @@
         final PsiElement element = expression.resolve();
         if (element instanceof PsiLocalVariable) {
           final PsiLocalVariable localVariable = (PsiLocalVariable)element;
-          final PsiElement[] elements = DefUseUtil.getDefs(myCallingMethod.getBody(), localVariable, expression);
+          final PsiElement[] elements = DefUseUtil.getDefs(myCallingBlock, localVariable, expression);
           if (elements.length == 1) {
             PsiExpression localInitializer = null;
             if (elements[0] instanceof PsiLocalVariable) {
diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java
index 58d4d1e..e5c9490 100644
--- a/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineParameterHandler.java
@@ -33,6 +33,8 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.refactoring.HelpID;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.refactoring.util.InlineUtil;
 import com.intellij.refactoring.util.RefactoringMessageDialog;
@@ -47,6 +49,7 @@
 public class InlineParameterHandler extends JavaInlineActionHandler {
   private static final Logger LOG = Logger.getInstance("#com.intellij.refactoring.inline.InlineParameterHandler");
   public static final String REFACTORING_NAME = RefactoringBundle.message("inline.parameter.refactoring");
+  public static final String REFACTORING_ID = "refactoring.inline.parameter";
 
   public boolean canInlineElement(PsiElement element) {
     if (element instanceof PsiParameter) {
@@ -212,8 +215,13 @@
       }
     }
 
+    final RefactoringEventData data = new RefactoringEventData();
+    data.addElement(psiElement.copy());
+    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, data);
 
     SameParameterValueInspection.InlineParameterValueFix.inlineSameParameterValue(method, psiParameter, constantExpression);
+
+    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, null);
   }
 
   @Nullable
diff --git a/java/java-impl/src/com/intellij/refactoring/inline/InlineStaticImportHandler.java b/java/java-impl/src/com/intellij/refactoring/inline/InlineStaticImportHandler.java
index 6abc17b..41173c9 100644
--- a/java/java-impl/src/com/intellij/refactoring/inline/InlineStaticImportHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/inline/InlineStaticImportHandler.java
@@ -23,6 +23,8 @@
 import com.intellij.psi.PsiImportStaticStatement;
 import com.intellij.psi.PsiJavaCodeReferenceElement;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 
 import java.util.List;
 
@@ -36,6 +38,7 @@
 public class InlineStaticImportHandler extends JavaInlineActionHandler {
 
   private static final String REFACTORING_NAME = "Expand static import";
+  public static final String REFACTORING_ID = "refactoring.inline.import";
 
   @Override
   public boolean canInlineElement(PsiElement element) {
@@ -48,11 +51,18 @@
     final PsiImportStaticStatement staticStatement = PsiTreeUtil.getParentOfType(element, PsiImportStaticStatement.class);
     final List<PsiJavaCodeReferenceElement> referenceElements =
       collectReferencesThrough(element.getContainingFile(), null, staticStatement);
+
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(element);
+    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(REFACTORING_ID, data);
+    
+
     new WriteCommandAction(project, REFACTORING_NAME){
       @Override
       protected void run(Result result) throws Throwable {
         replaceAllAndDeleteImport(referenceElements, null, staticStatement);
       }
     }.execute();
+    project.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(REFACTORING_ID, null);
   }
 }
diff --git a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java
index ab340a5..ced5768 100644
--- a/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/inlineSuperClass/InlineSuperClassRefactoringProcessor.java
@@ -30,6 +30,7 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.psi.util.TypeConversionUtil;
 import com.intellij.refactoring.inlineSuperClass.usageInfo.*;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.memberPushDown.PushDownConflicts;
 import com.intellij.refactoring.memberPushDown.PushDownProcessor;
 import com.intellij.refactoring.util.*;
@@ -318,6 +319,29 @@
     }.run();
   }
 
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    final RefactoringEventData data = new RefactoringEventData();
+    data.addElement(mySuperClass);
+    data.addElements(myTargetClasses);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    final RefactoringEventData data = new RefactoringEventData();
+    data.addElements(myTargetClasses);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.inline.class";
+  }
+
   private void replaceInnerTypeUsages() {
     final JavaPsiFacade facade = JavaPsiFacade.getInstance(myProject);
     final PsiElementFactory elementFactory = facade.getElementFactory();
diff --git a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java
index ba3ba8a..076734e 100644
--- a/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/introduceParameter/IntroduceParameterProcessor.java
@@ -41,6 +41,7 @@
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.changeSignature.ChangeSignatureProcessor;
 import com.intellij.refactoring.introduceVariable.IntroduceVariableBase;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.util.*;
 import com.intellij.refactoring.util.occurrences.ExpressionOccurrenceManager;
 import com.intellij.refactoring.util.occurrences.LocalVariableOccurrenceManager;
@@ -336,6 +337,20 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.introduceParameter";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(new PsiElement[] {myLocalVariable, myExpressionToSearch});
+    return data;
+  }
+
   protected void performRefactoring(UsageInfo[] usages) {
     try {
       PsiElementFactory factory = JavaPsiFacade.getInstance(myManager.getProject()).getElementFactory();
diff --git a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java
index 4ec3a13..53162cd 100644
--- a/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java
+++ b/java/java-impl/src/com/intellij/refactoring/introduceVariable/IntroduceVariableBase.java
@@ -37,10 +37,7 @@
 import com.intellij.openapi.editor.markup.TextAttributes;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Key;
-import com.intellij.openapi.util.Pass;
-import com.intellij.openapi.util.Ref;
-import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.util.*;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.WindowManager;
@@ -414,6 +411,12 @@
       final PsiExpression toBeExpression = createReplacement(fakeInitializer, project, prefix, suffix, parent, rangeMarker, refIdx);
       toBeExpression.accept(errorsVisitor);
       if (hasErrors[0]) return null;
+      if (literalExpression != null) {
+        PsiType type = toBeExpression.getType();
+        if (type != null && !type.equals(literalExpression.getType())) {
+          return null;
+        }
+      }
 
       final PsiReferenceExpression refExpr = PsiTreeUtil.getParentOfType(toBeExpression.findElementAt(refIdx[0]), PsiReferenceExpression.class);
       if (refExpr == null) return null;
@@ -692,6 +695,7 @@
     while (true) {
       if (containerParent instanceof PsiFile) break;
       if (containerParent instanceof PsiMethod) break;
+      if (containerParent instanceof PsiLambdaExpression) break;
       if (!skipForStatement && containerParent instanceof PsiForStatement) break;
       containerParent = containerParent.getParent();
       if (containerParent instanceof PsiCodeBlock) {
diff --git a/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java b/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java
index be8cab8..df8b69c 100644
--- a/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java
+++ b/java/java-impl/src/com/intellij/refactoring/invertBoolean/InvertBooleanHandler.java
@@ -68,7 +68,7 @@
     new InvertBooleanDialog(var).show();
   }
 
-  public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, @NotNull DataContext dataContext) {
+  public void invoke(@NotNull Project project, @NotNull PsiElement[] elements, DataContext dataContext) {
     if (elements.length == 1) {
       if (elements[0] instanceof PsiMethod) {
         invoke((PsiMethod)elements[0], project, null);
diff --git a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodOrClassStaticProcessor.java b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodOrClassStaticProcessor.java
index 2e6467b..758e102 100644
--- a/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodOrClassStaticProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/makeStatic/MakeMethodOrClassStaticProcessor.java
@@ -36,6 +36,7 @@
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.ui.ConflictsDialog;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
 import com.intellij.refactoring.util.ConflictsUtil;
@@ -48,6 +49,7 @@
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.MultiMap;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.HashSet;
@@ -72,6 +74,28 @@
     return new MakeMethodOrClassStaticViewDescriptor(myMember);
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.makeStatic";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myMember);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myMember);
+    return data;
+  }
+
   protected final boolean preprocessUsages(final Ref<UsageInfo[]> refUsages) {
     UsageInfo[] usagesIn = refUsages.get();
     if (myPrepareSuccessfulSwingThreadCallback != null) {
diff --git a/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java b/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java
index 310d591..5e6ac95 100644
--- a/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/memberPullUp/PullUpProcessor.java
@@ -42,6 +42,7 @@
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.classMembers.MemberInfoBase;
 import com.intellij.refactoring.listeners.JavaRefactoringListenerManager;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.listeners.impl.JavaRefactoringListenerManagerImpl;
 import com.intellij.refactoring.util.DocCommentPolicy;
 import com.intellij.refactoring.util.RefactoringUIUtil;
@@ -49,10 +50,12 @@
 import com.intellij.refactoring.util.duplicates.MethodDuplicatesHandler;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.usageView.UsageViewDescriptor;
+import com.intellij.util.Function;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.Query;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
 
@@ -94,6 +97,26 @@
     return result.isEmpty() ? UsageInfo.EMPTY_ARRAY : result.toArray(new UsageInfo[result.size()]);
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.pullUp";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(mySourceClass);
+    data.addMembers(myMembersToMove, new Function<MemberInfo, PsiElement>() {
+      @Override
+      public PsiElement fun(MemberInfo info) {
+        return info.getMember();
+      }
+    });
+    return data;
+  }
+
   protected void performRefactoring(UsageInfo[] usages) {
     moveMembersToBase();
     moveFieldInitializations();
diff --git a/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java b/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java
index a6cecc7..3113925 100644
--- a/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/memberPushDown/PushDownProcessor.java
@@ -38,15 +38,18 @@
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.listeners.JavaRefactoringListenerManager;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.listeners.impl.JavaRefactoringListenerManagerImpl;
 import com.intellij.refactoring.util.DocCommentPolicy;
 import com.intellij.refactoring.util.RefactoringUtil;
 import com.intellij.refactoring.util.classMembers.MemberInfo;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.usageView.UsageViewDescriptor;
+import com.intellij.util.Function;
 import com.intellij.util.IncorrectOperationException;
 import com.intellij.util.containers.HashSet;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
 
@@ -77,6 +80,41 @@
     return new PushDownUsageViewDescriptor(myClass);
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.psuDown";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myClass);
+    data.addMembers(myMemberInfos, new Function<MemberInfo, PsiElement>() {
+      @Override
+      public PsiElement fun(MemberInfo info) {
+        return info.getMember();
+      }
+    });
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    final List<PsiElement> elements = new ArrayList<PsiElement>();
+    for (UsageInfo usage : usages) {
+      PsiElement element = usage.getElement();
+      if (element instanceof PsiClass) {
+        elements.add(element);
+      }
+    }
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(elements);
+    return data;
+  }
+
   @NotNull
   protected UsageInfo[] findUsages() {
     final PsiClass[] inheritors = ClassInheritorsSearch.search(myClass, false).toArray(PsiClass.EMPTY_ARRAY);
diff --git a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java
index 5a086c7..f398dfd 100644
--- a/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java
+++ b/java/java-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveClassesOrPackagesProcessor.java
@@ -37,6 +37,7 @@
 import com.intellij.refactoring.PackageWrapper;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.move.MoveCallback;
 import com.intellij.refactoring.move.MoveClassesOrPackagesCallback;
 import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor;
@@ -217,7 +218,28 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.move";
+  }
 
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(myElementsToMove);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(myTargetPackage.getDirectories());
+    data.addElement(JavaPsiFacade.getInstance(myProject).findPackage(myTargetPackage.getQualifiedName()));
+    return data;
+  }
 
   protected boolean preprocessUsages(Ref<UsageInfo[]> refUsages) {
     final UsageInfo[] usages = refUsages.get();
diff --git a/java/java-impl/src/com/intellij/refactoring/util/RefactoringConflictsUtil.java b/java/java-impl/src/com/intellij/refactoring/util/RefactoringConflictsUtil.java
index 2ec39e0..aece13d 100644
--- a/java/java-impl/src/com/intellij/refactoring/util/RefactoringConflictsUtil.java
+++ b/java/java-impl/src/com/intellij/refactoring/util/RefactoringConflictsUtil.java
@@ -149,9 +149,10 @@
       PsiReferenceExpression refExpr = (PsiReferenceExpression)scope;
       PsiElement refElement = refExpr.resolve();
       if (refElement instanceof PsiMember) {
-        if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false)) {
-          PsiExpression qualifier = refExpr.getQualifierExpression();
-          PsiClass accessClass = (PsiClass)(qualifier != null ? PsiUtil.getAccessObjectClass(qualifier).getElement() : null);
+        PsiExpression qualifier = refExpr.getQualifierExpression();
+        PsiClass accessClass = (PsiClass)(qualifier != null ? PsiUtil.getAccessObjectClass(qualifier).getElement() : null);
+        if (!RefactoringHierarchyUtil.willBeInTargetClass(refElement, moving, targetClass, false) &&
+            (accessClass == null || !RefactoringHierarchyUtil.willBeInTargetClass(accessClass, moving, targetClass, false))) {
           checkAccessibility((PsiMember)refElement, context, accessClass, member, conflicts);
         }
       }
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 6d8f91b..4851504 100644
--- a/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/LambdaUtil.java
@@ -455,7 +455,12 @@
           if (!tryToSubstitute) return cachedType;
         }
 
-        final PsiElement gParent = expressionList.getParent();
+        PsiElement gParent = expressionList.getParent();
+
+        if (gParent instanceof PsiAnonymousClass) {
+          gParent = gParent.getParent();
+        }
+
         if (gParent instanceof PsiCall) {
           final PsiCall contextCall = (PsiCall)gParent;
           final JavaResolveResult resolveResult = contextCall.resolveMethodGenerics();
diff --git a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java
index ad92cfe..96930eb 100644
--- a/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/PsiMethodReferenceUtil.java
@@ -87,6 +87,7 @@
       myReferenceTypeQualified = referenceTypeQualified;
     }
 
+    @Nullable
     public PsiClass getContainingClass() {
       return myContainingClass;
     }
diff --git a/java/java-psi-api/src/com/intellij/psi/PsiSubstitutor.java b/java/java-psi-api/src/com/intellij/psi/PsiSubstitutor.java
index c60ece8..ddc301e 100644
--- a/java/java-psi-api/src/com/intellij/psi/PsiSubstitutor.java
+++ b/java/java-psi-api/src/com/intellij/psi/PsiSubstitutor.java
@@ -29,12 +29,7 @@
  * @see com.intellij.psi.JavaResolveResult#getSubstitutor()
  */
 public interface PsiSubstitutor {
-  Key<PsiSubstitutor> KEY = new KeyWithDefaultValue<PsiSubstitutor>("SUBSTITUTOR") {
-    @Override
-    public PsiSubstitutor getDefaultValue() {
-      return EMPTY;
-    }
-  };
+  Key<PsiSubstitutor> KEY = KeyWithDefaultValue.<PsiSubstitutor>create("SUBSTITUTOR", EmptySubstitutor.getInstance());
 
   /**
    * Empty, or natural, substitutor. For any type parameter <code>T</code>,
diff --git a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
index c6a8d71..0851f26 100644
--- a/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
+++ b/java/java-psi-api/src/com/intellij/psi/infos/MethodCandidateInfo.java
@@ -111,22 +111,24 @@
       }
       else {
         final PsiSubstitutor substitutor = getSubstitutor();
-        level = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() {
+        Integer boxedLevel = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() {
           @Override
           public Integer compute() {
             return PsiUtil.getApplicabilityLevel(getElement(), substitutor, myArgumentTypes, myLanguageLevel);
           }
         });
+        level = boxedLevel != null ? boxedLevel : getApplicabilityLevel();
       }
       if (level > ApplicabilityLevel.NOT_APPLICABLE && !isTypeArgumentsApplicable()) level = ApplicabilityLevel.NOT_APPLICABLE;
       return level;
     }
-    return ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() {
+    Integer boxedLevel = ourOverloadGuard.doPreventingRecursion(myArgumentList, false, new Computable<Integer>() {
       @Override
       public Integer compute() {
         return getApplicabilityLevelInner();
       }
     });
+    return boxedLevel != null ? boxedLevel : getApplicabilityLevel();
   }
 
   public PsiSubstitutor getSiteSubstitutor() {
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 f64f207..c448926 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
@@ -17,6 +17,7 @@
 
 import com.intellij.lang.ASTNode;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Condition;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
@@ -215,4 +216,16 @@
     }
     return null;
   }
+  
+  public static boolean compareTypes(PsiType leftType, PsiType rightType, boolean ignoreEllipsis) {
+    if (ignoreEllipsis) {
+      if (leftType instanceof PsiEllipsisType) {
+        leftType = ((PsiEllipsisType)leftType).toArrayType();
+      }
+      if (rightType instanceof PsiEllipsisType) {
+        rightType = ((PsiEllipsisType)rightType).toArrayType();
+      }
+    }
+    return Comparing.equal(leftType, rightType);
+  }
 }
diff --git a/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java b/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java
index 7bb65a1..6df6f2a 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/RedundantCastUtil.java
@@ -17,10 +17,12 @@
 
 import com.intellij.codeInsight.AnnotationUtil;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Ref;
 import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.CodeStyleManager;
+import com.intellij.psi.codeStyle.JavaCodeStyleManager;
 import com.intellij.psi.tree.IElementType;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.IncorrectOperationException;
@@ -465,9 +467,11 @@
       final PsiType expectedTypeByParent = PsiTypesUtil.getExpectedTypeByParent(typeCast);
       if (expectedTypeByParent != null) {
         try {
+          final Project project = operand.getProject();
+          final String uniqueVariableName = JavaCodeStyleManager.getInstance(project).suggestUniqueVariableName("l", parent, false);
           final PsiDeclarationStatement declarationStatement =
-            (PsiDeclarationStatement)JavaPsiFacade.getElementFactory(operand.getProject()).createStatementFromText(
-              expectedTypeByParent.getCanonicalText() + " l = " + operand.getText() + ";", parent);
+            (PsiDeclarationStatement)JavaPsiFacade.getElementFactory(project).createStatementFromText(
+              expectedTypeByParent.getCanonicalText() + " " + uniqueVariableName + " = " + operand.getText() + ";", parent);
           final PsiExpression initializer = ((PsiLocalVariable)declarationStatement.getDeclaredElements()[0]).getInitializer();
           LOG.assertTrue(initializer != null, operand.getText());
           opType = initializer.getType();
diff --git a/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java b/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java
index c2b09bf..381eabc 100644
--- a/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java
+++ b/java/java-psi-api/src/com/intellij/psi/util/TypesDistinctProver.java
@@ -36,8 +36,6 @@
   }
 
   protected static boolean provablyDistinct(PsiType type1, PsiType type2, int level) {
-    if (type1 instanceof PsiClassType && ((PsiClassType)type1).resolve() instanceof PsiTypeParameter && level < 2) return false;
-    if (type2 instanceof PsiClassType && ((PsiClassType)type2).resolve() instanceof PsiTypeParameter && level < 2) return false;
     if (type1 instanceof PsiWildcardType) {
       if (type2 instanceof PsiWildcardType) {
         return provablyDistinct((PsiWildcardType)type1, (PsiWildcardType)type2, true);
@@ -119,11 +117,33 @@
 
     final PsiClass boundClass1 = classResolveResult1.getElement();
     final PsiClass boundClass2 = classResolveResult2.getElement();
+
+    if (boundClass1 instanceof PsiTypeParameter && level < 2) {
+      if (!distinguishFromTypeParam((PsiTypeParameter)boundClass1, boundClass2, type1)) return false;
+    }
+
+    if (boundClass2 instanceof PsiTypeParameter && level < 2) {
+      if (!distinguishFromTypeParam((PsiTypeParameter)boundClass2, boundClass1, type2)) return false;
+    }
     return type2 != null && type1 != null && !type1.equals(type2) &&
            (!InheritanceUtil.isInheritorOrSelf(boundClass1, boundClass2, true) ||
             !InheritanceUtil.isInheritorOrSelf(boundClass2, boundClass1, true));
   }
 
+  private static boolean distinguishFromTypeParam(PsiTypeParameter typeParam, PsiClass boundClass, PsiType type1) {
+    final PsiClassType[] paramBounds = typeParam.getExtendsListTypes();
+    if (paramBounds.length == 0 && type1 instanceof PsiClassType) return false;
+    for (PsiClassType classType : paramBounds) {
+      final PsiClass paramBound = classType.resolve();
+      if (paramBound != null &&
+          (InheritanceUtil.isInheritorOrSelf(paramBound, boundClass, true) ||
+           InheritanceUtil.isInheritorOrSelf(boundClass, paramBound, true))) {
+        return false;
+      }
+    }
+    return true;
+  }
+
   public static boolean provablyDistinct(PsiWildcardType type1, PsiWildcardType type2, boolean rejectInconsistentRaw) {
     if (type1.isSuper() && type2.isSuper()) return false;
     if (type1.isExtends() && type2.isExtends()) {
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 2b3359c..11de043 100644
--- a/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java
+++ b/java/java-psi-impl/src/com/intellij/codeInsight/ExceptionUtil.java
@@ -376,7 +376,7 @@
   }
 
   @NotNull
-  public static List<PsiClassType> getUnhandledExceptions(PsiElement element) {
+  public static List<PsiClassType> getUnhandledExceptions(@NotNull PsiElement element) {
     if (element instanceof PsiCallExpression) {
       PsiCallExpression expression = (PsiCallExpression)element;
       return getUnhandledExceptions(expression, null);
diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/JavaPsiEquivalenceUtil.java b/java/java-psi-impl/src/com/intellij/codeInsight/JavaPsiEquivalenceUtil.java
index 7308203..fca20e6 100644
--- a/java/java-psi-impl/src/com/intellij/codeInsight/JavaPsiEquivalenceUtil.java
+++ b/java/java-psi-impl/src/com/intellij/codeInsight/JavaPsiEquivalenceUtil.java
@@ -17,6 +17,7 @@
 
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.PsiDiamondTypeElementImpl;
+import com.intellij.psi.util.PsiTreeUtil;
 
 import java.util.Comparator;
 
@@ -25,8 +26,15 @@
     return PsiEquivalenceUtil.areElementsEquivalent(expr1, expr2, new Comparator<PsiElement>() {
       @Override
       public int compare(PsiElement o1, PsiElement o2) {
-        if (o1 instanceof PsiParameter && o2 instanceof PsiParameter && ((PsiParameter)o1).getDeclarationScope() instanceof PsiMethod) {
-          return ((PsiParameter)o1).getName().compareTo(((PsiParameter)o2).getName());
+        if (o1 instanceof PsiParameter && o2 instanceof PsiParameter) {
+          final PsiElement scope1 = ((PsiParameter)o1).getDeclarationScope();
+          final PsiElement scope2 = ((PsiParameter)o2).getDeclarationScope();
+          if (scope1 instanceof PsiMethod && scope2 instanceof PsiMethod ||
+              scope1 instanceof PsiLambdaExpression && scope2 instanceof PsiLambdaExpression) {
+            if (!scope1.getTextRange().intersects(scope2.getTextRange())) {
+              return ((PsiParameter)o1).getName().compareTo(((PsiParameter)o2).getName());
+            }
+          }
         }
         return 1;
       }
diff --git a/java/java-psi-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilderBase.java b/java/java-psi-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilderBase.java
index fe8804c..712bbad 100644
--- a/java/java-psi-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilderBase.java
+++ b/java/java-psi-impl/src/com/intellij/codeInsight/folding/impl/JavaFoldingBuilderBase.java
@@ -150,7 +150,7 @@
   }
 
   public static boolean hasErrorElementsNearby(final PsiFile file, int startOffset, int endOffset) {
-    endOffset = CharArrayUtil.shiftForward(file.getText(), endOffset, " \t\n");
+    endOffset = CharArrayUtil.shiftForward(file.getViewProvider().getContents(), endOffset, " \t\n");
     for (PsiElement element : CollectHighlightsUtil.getElementsInRange(file, startOffset, endOffset)) {
       if (element instanceof PsiErrorElement) {
         return true;
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 4a99129..5a1e137 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
@@ -30,6 +30,7 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.JavaConstantExpressionEvaluator;
+import com.intellij.psi.impl.source.javadoc.PsiInlineDocTagImpl;
 import com.intellij.psi.impl.source.tree.JavaDocElementType;
 import com.intellij.psi.javadoc.PsiDocComment;
 import com.intellij.psi.javadoc.PsiDocTag;
@@ -1039,7 +1040,7 @@
           generateLinkValue(tag, buffer, false);
         }
         else if (tagName.equals(LITERAL_TAG)) {
-          generateLiteralValue(tag, buffer);
+          generateLiteralValue(buffer, ((PsiInlineDocTagImpl)tag).getDataElementsIgnoreWhitespaces());
         }
         else if (tagName.equals(CODE_TAG)) {
           generateCodeValue(tag, buffer);
@@ -1073,14 +1074,12 @@
   @SuppressWarnings({"HardCodedStringLiteral"})
   private static void generateCodeValue(PsiInlineDocTag tag, StringBuilder buffer) {
     buffer.append("<code>");
-    generateLiteralValue(tag, buffer);
+    generateLiteralValue(buffer, tag.getDataElements());
     buffer.append("</code>");
   }
 
-  private static void generateLiteralValue(PsiInlineDocTag tag, StringBuilder buffer) {
-    PsiElement[] elements = tag.getDataElements();
-
-    for (PsiElement element : elements) {
+  private static void generateLiteralValue(StringBuilder buffer, final PsiElement[] dataElements) {
+    for (PsiElement element : dataElements) {
       appendPlainText(element.getText(), buffer);
     }
   }
@@ -1489,6 +1488,7 @@
         if (!isAbstract) continue;
       }
       PsiClass superClass = superMethod.getContainingClass();
+      if (superClass == null) continue;
       if (!headerGenerated) {
         buffer.append("<DD><DL>");
         buffer.append("<DT><b>");
diff --git a/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java b/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java
index ca25391..129be2e 100644
--- a/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/PsiDiamondTypeImpl.java
@@ -28,6 +28,7 @@
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtil;
 import com.intellij.util.Function;
+import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -136,7 +137,7 @@
         final PsiMethod constructor = findConstructor(psiClass, newExpression);
         PsiTypeParameter[] params = getAllTypeParams(constructor, psiClass);
 
-        final PsiMethod staticFactory = generateStaticFactory(constructor, psiClass, params);
+        final PsiMethod staticFactory = generateStaticFactory(constructor, psiClass, params, newExpression.getClassReference());
         if (staticFactory == null) {
           return null;
         }
@@ -210,7 +211,10 @@
   }
 
   @Nullable
-  private static PsiMethod generateStaticFactory(@Nullable PsiMethod constructor, PsiClass containingClass, PsiTypeParameter[] params) {
+  private static PsiMethod generateStaticFactory(@Nullable PsiMethod constructor,
+                                                 PsiClass containingClass,
+                                                 PsiTypeParameter[] params,
+                                                 PsiJavaCodeReferenceElement reference) {
     final StringBuilder buf = new StringBuilder();
     buf.append("public static ");
     buf.append("<");
@@ -223,7 +227,23 @@
     }, ", "));
     buf.append(">");
 
-    final String qualifiedName = containingClass.getQualifiedName();
+    final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(containingClass.getProject());
+
+    String qualifiedName = containingClass.getQualifiedName();
+
+    PsiElement qualifier = reference != null ? reference.getQualifier() : null;
+    if (qualifier instanceof PsiJavaCodeReferenceElement) {
+      final JavaResolveResult resolveResult = ((PsiJavaCodeReferenceElement)qualifier).advancedResolve(false);
+      final PsiElement element = resolveResult.getElement();
+      if (element instanceof PsiClass) {
+        final String outerClassSubstitutedQName =
+          elementFactory.createType((PsiClass)element, resolveResult.getSubstitutor()).getInternalCanonicalText();
+        qualifiedName = outerClassSubstitutedQName + "." + containingClass.getName();
+      }
+    } else if (reference != null && qualifier == null && containingClass.getContainingClass() != null) {
+      qualifiedName = null;
+    }
+    
     buf.append(qualifiedName != null ? qualifiedName : containingClass.getName());
     final PsiTypeParameter[] parameters = containingClass.getTypeParameters();
     buf.append("<");
@@ -253,7 +273,12 @@
     }
     buf.append("{}");
 
-    return JavaPsiFacade.getElementFactory(containingClass.getProject()).createMethodFromText(buf.toString(), constructor != null ? constructor : containingClass);
+    try {
+      return elementFactory.createMethodFromText(buf.toString(), constructor != null ? constructor : containingClass);
+    }
+    catch (IncorrectOperationException e) {
+      return null;
+    }
   }
 
   private static PsiTypeParameter[] getAllTypeParams(PsiTypeParameterListOwner listOwner, PsiClass containingClass) {
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java
index cf56986..b35a97e 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/compiled/ClsFileImpl.java
@@ -214,7 +214,8 @@
   @Override
   @NotNull
   public LanguageLevel getLanguageLevel() {
-    return LanguageLevel.HIGHEST;  // library classes should inherit language level from modules where they are referenced
+    List stubs = getStub().getChildrenStubs();
+    return !stubs.isEmpty() ? ((PsiClassStub<?>)stubs.get(0)).getLanguageLevel() : LanguageLevel.HIGHEST;
   }
 
   @Override
@@ -289,7 +290,7 @@
           String fileName = (classes.length > 0 ? classes[0].getName() : file.getNameWithoutExtension()) + "." + ext;
           PsiFileFactory factory = PsiFileFactory.getInstance(getManager().getProject());
           PsiFile mirror = factory.createFileFromText(fileName, JavaLanguage.INSTANCE, mirrorText, false, false);
-          mirror.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, getSourceLanguageLevel());
+          mirror.putUserData(PsiUtil.FILE_LANGUAGE_LEVEL_KEY, getLanguageLevel());
           mirrorTreeElement = SourceTreeToPsiMap.psiToTreeNotNull(mirror);
 
           // IMPORTANT: do not take lock too early - FileDocumentManager.saveToString() can run write action
@@ -311,12 +312,6 @@
     return mirrorTreeElement.getPsi();
   }
 
-  @NotNull
-  public LanguageLevel getSourceLanguageLevel() {
-    final List stubs = getStub().getChildrenStubs();
-    return !stubs.isEmpty() ? ((PsiClassStub<?>)stubs.get(0)).getLanguageLevel() : LanguageLevel.HIGHEST;
-  }
-
   @Override
   public PsiFile getDecompiledPsiFile() {
     for (ClsFileDecompiledPsiFileProvider provider : Extensions.getExtensions(ClsFileDecompiledPsiFileProvider.EP_NAME)) {
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java
index 1adf3a5..668453c 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/javadoc/PsiInlineDocTagImpl.java
@@ -35,10 +35,11 @@
 import org.jetbrains.annotations.NotNull;
 
 public class PsiInlineDocTagImpl extends CompositePsiElement implements PsiInlineDocTag, Constants {
-  private static final TokenSet TAG_VALUE_BIT_SET = TokenSet.create(
-    DOC_TAG_VALUE_ELEMENT, DOC_METHOD_OR_FIELD_REF);
-  private static final TokenSet VALUE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create(
+  private static final TokenSet TAG_VALUE_BIT_SET = TokenSet.create(DOC_TAG_VALUE_ELEMENT, DOC_METHOD_OR_FIELD_REF);
+  private static final TokenSet VALUE_NO_WHITESPACE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create(
     JAVA_CODE_REFERENCE, DOC_TAG_VALUE_TOKEN, DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER, DOC_COMMENT_BAD_CHARACTER));
+  private static final TokenSet VALUE_BIT_SET = TokenSet.orSet(TAG_VALUE_BIT_SET, TokenSet.create(
+    JAVA_CODE_REFERENCE, DOC_TAG_VALUE_TOKEN, WHITE_SPACE, DOC_COMMENT_DATA, DOC_INLINE_TAG, DOC_REFERENCE_HOLDER, DOC_COMMENT_BAD_CHARACTER));
 
   public PsiInlineDocTagImpl() {
     super(DOC_INLINE_TAG);
@@ -63,6 +64,10 @@
     return getChildrenAsPsiElements(VALUE_BIT_SET, PsiElement.ARRAY_FACTORY);
   }
 
+  public PsiElement[] getDataElementsIgnoreWhitespaces() {
+    return getChildrenAsPsiElements(VALUE_NO_WHITESPACE_BIT_SET, PsiElement.ARRAY_FACTORY);
+  }
+
   @Override
   public PsiDocTagValue getValueElement() {
     return (PsiDocTagValue)findPsiChildByType(TAG_VALUE_BIT_SET);
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 4110c82c..b404ab4 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
@@ -87,11 +87,16 @@
     initBounds(typeParams);
   }
 
-  public void initExpressionConstraints(PsiParameter[] parameters, PsiExpression[] args, PsiElement parent) {
-    final Pair<PsiMethod, PsiCallExpression> pair = getPair(parent);
+  public void initExpressionConstraints(PsiParameter[] parameters, PsiExpression[] args, PsiElement parent, PsiMethod method) {
+    if (method == null) {
+      final Pair<PsiMethod, PsiCallExpression> pair = getPair(parent);
+      if (pair != null) {
+        method = pair.first;
+      }
+    }
     if (parameters.length > 0) {
       for (int i = 0; i < args.length; i++) {
-        if (args[i] != null && (pair == null || isPertinentToApplicability(args[i], pair.first))) {
+        if (args[i] != null && isPertinentToApplicability(args[i], method)) {
           PsiType parameterType = getParameterType(parameters, args, i, mySiteSubstitutor);
           myConstraints.add(new ExpressionCompatibilityConstraint(args[i], parameterType));
         }
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java
index 6915b5f..8b36b35 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/PsiGraphInferenceHelper.java
@@ -39,7 +39,7 @@
                                                  @Nullable PsiElement parent,
                                                  @NotNull ParameterTypeInferencePolicy policy) {
     final InferenceSession inferenceSession = new InferenceSession(new PsiTypeParameter[]{typeParameter}, partialSubstitutor, myManager);
-    inferenceSession.initExpressionConstraints(parameters, arguments, parent);
+    inferenceSession.initExpressionConstraints(parameters, arguments, parent, null);
     return inferenceSession.infer(parameters, arguments, parent, policy).substitute(typeParameter);
   }
 
@@ -54,7 +54,7 @@
                                            @NotNull LanguageLevel languageLevel) {
     if (typeParameters.length == 0) return partialSubstitutor;
     final InferenceSession inferenceSession = new InferenceSession(typeParameters, partialSubstitutor, myManager);
-    inferenceSession.initExpressionConstraints(parameters, arguments, parent);
+    inferenceSession.initExpressionConstraints(parameters, arguments, parent, null);
     return inferenceSession.infer(parameters, arguments, parent, policy);
   }
 
@@ -86,6 +86,14 @@
                                                  boolean isContraVariantPosition,
                                                  LanguageLevel languageLevel) {
     if (arg == PsiType.VOID || param == PsiType.VOID) return PsiType.NULL;
+    if (param instanceof PsiArrayType && arg instanceof PsiArrayType) {
+      return getSubstitutionForTypeParameter(typeParam, ((PsiArrayType)param).getComponentType(), ((PsiArrayType)arg).getComponentType(), isContraVariantPosition, languageLevel);
+    } 
+
+    if (!(param instanceof PsiClassType)) return PsiType.NULL;
+    if (arg == null) {
+      return PsiType.NULL;
+    }
     final PsiType[] leftTypes;
     final PsiType[] rightTypes;
     if (isContraVariantPosition) {
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/CheckedExceptionCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/CheckedExceptionCompatibilityConstraint.java
index 68884aa..4fe5dfb 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/CheckedExceptionCompatibilityConstraint.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/CheckedExceptionCompatibilityConstraint.java
@@ -97,7 +97,9 @@
       final List<PsiType> thrownTypes = new ArrayList<PsiType>();
       if (myExpression instanceof PsiLambdaExpression) {
         PsiElement body = ((PsiLambdaExpression)myExpression).getBody();
-        thrownTypes.addAll(ExceptionUtil.getUnhandledExceptions(body));
+        if (body != null) {
+          thrownTypes.addAll(ExceptionUtil.getUnhandledExceptions(body));
+        }
       } else {
         if (((PsiMethodReferenceExpression)myExpression).isExact()) {
           final PsiElement resolve = ((PsiMethodReferenceExpression)myExpression).resolve();
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java
index 7fefdf5..b433c13 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/ExpressionCompatibilityConstraint.java
@@ -111,7 +111,7 @@
               InferenceSession callSession = new InferenceSession(typeParams, ((MethodCandidateInfo)resolveResult).getSiteSubstitutor(), myExpression.getManager());
               final PsiExpression[] args = argumentList.getExpressions();
               final PsiParameter[] parameters = method.getParameterList().getParameters();
-              callSession.initExpressionConstraints(parameters, args, myExpression);
+              callSession.initExpressionConstraints(parameters, args, myExpression, method);
               substitutor = callSession.infer(parameters, args, myExpression, LiftParameterTypeInferencePolicy.INSTANCE);
             }
           } else {
diff --git a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java
index 3c83655..555b53b 100644
--- a/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java
+++ b/java/java-psi-impl/src/com/intellij/psi/impl/source/resolve/graphInference/constraints/PsiMethodReferenceCompatibilityConstraint.java
@@ -115,8 +115,11 @@
           constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(returnType), psiSubstitutor.substitute(applicableMethodReturnType)));
         } else if (applicableMember instanceof PsiClass || applicableMember instanceof PsiMethod && ((PsiMethod)applicableMember).isConstructor()) {
           final PsiElementFactory elementFactory = JavaPsiFacade.getElementFactory(applicableMember.getProject());
-          final PsiClassType classType = elementFactory.createType(qualifierResolveResult.getContainingClass(), psiSubstitutor);
-          constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(returnType), classType));
+          final PsiClass containingClass = qualifierResolveResult.getContainingClass();
+          if (containingClass != null) {
+            final PsiClassType classType = elementFactory.createType(containingClass, psiSubstitutor);
+            constraints.add(new TypeCompatibilityConstraint(GenericsUtil.eliminateWildcards(returnType), classType));
+          }
         }
       }
       return true;
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 c6fb44b..a52efdf 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
@@ -606,8 +606,17 @@
       }
 
       @Override
-      protected boolean checkSameConflicts(CandidateInfo method, CandidateInfo conflict) {
-        return method == conflict;
+      protected boolean nonComparable(CandidateInfo method, CandidateInfo conflict) {
+        if (method == conflict) return true;
+        PsiElement psiElement = method.getElement();
+        PsiElement conflictElement = conflict.getElement();
+        if (psiElement instanceof PsiMethod && conflictElement instanceof PsiMethod) {
+          if (((PsiMethod)psiElement).getParameterList().getParametersCount() !=
+              ((PsiMethod)conflictElement).getParameterList().getParametersCount()) {
+            return true;
+          }
+        }
+        return false;
       }
     }
   }
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 94b4d45..22cc051 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
@@ -145,7 +145,7 @@
         for (int j = 0; j < i; j++) {
           ProgressManager.checkCanceled();
           final CandidateInfo conflict = newConflictsArray[j];
-          if (checkSameConflicts(method, conflict)) continue; 
+          if (nonComparable(method, conflict)) continue; 
           switch (isMoreSpecific(method, conflict, applicabilityLevel, languageLevel)) {
             case FIRST:
               conflicts.remove(conflict);
@@ -161,7 +161,7 @@
     }
   }
 
-  protected boolean checkSameConflicts(CandidateInfo method, CandidateInfo conflict) {
+  protected boolean nonComparable(CandidateInfo method, CandidateInfo conflict) {
     assert method != conflict;
     return false;
   }
@@ -509,8 +509,22 @@
       final PsiType[] types2AtSite = typesAtSite(types2, siteSubstitutor2);
       final PsiType[] types1AtSite = typesAtSite(types1, siteSubstitutor1);
 
-      final boolean applicable12 = isApplicableTo(types2AtSite, method1, typeParameters1, languageLevel, varargsPosition, types1, siteSubstitutor1);
-      final boolean applicable21 = isApplicableTo(types1AtSite, method2, typeParameters2, languageLevel, varargsPosition, types2, siteSubstitutor2);
+      final PsiSubstitutor methodSubstitutor1 = calculateMethodSubstitutor(typeParameters1, method1, siteSubstitutor1, types1, types2AtSite, languageLevel);
+      boolean applicable12 = isApplicableTo(types2AtSite, method1, languageLevel, varargsPosition, methodSubstitutor1);
+
+      final PsiSubstitutor methodSubstitutor2 = calculateMethodSubstitutor(typeParameters2, method2, siteSubstitutor2, types2, types1AtSite, languageLevel);
+      boolean applicable21 = isApplicableTo(types1AtSite, method2, languageLevel, varargsPosition, methodSubstitutor2);
+
+      final boolean typeArgsApplicable12 = GenericsUtil.isTypeArgumentsApplicable(typeParameters1, methodSubstitutor1, myArgumentsList, !applicable21);
+      final boolean typeArgsApplicable21 = GenericsUtil.isTypeArgumentsApplicable(typeParameters2, methodSubstitutor2, myArgumentsList, !applicable12);
+
+      if (!typeArgsApplicable12) {
+        applicable12 = false;
+      }
+
+      if (!typeArgsApplicable21) {
+        applicable21 = false;
+      }
 
       if (applicable12 || applicable21) {
 
@@ -538,8 +552,10 @@
         }
 
         if (toCompareFunctional) {
-          final boolean applicable12ignoreFunctionalType = isApplicableTo(types2AtSite, method1, typeParameters1, languageLevel, varargsPosition, types1, siteSubstitutor1);
-          final boolean applicable21ignoreFunctionalType = isApplicableTo(types1AtSite, method2, typeParameters2, languageLevel, varargsPosition, types2, siteSubstitutor2);
+          final boolean applicable12ignoreFunctionalType = isApplicableTo(types2AtSite, method1, languageLevel, varargsPosition,
+                                                                          calculateMethodSubstitutor(typeParameters1, method1, siteSubstitutor1, types1, types2AtSite, languageLevel));
+          final boolean applicable21ignoreFunctionalType = isApplicableTo(types1AtSite, method2, languageLevel, varargsPosition,
+                                                                          calculateMethodSubstitutor(typeParameters2, method2, siteSubstitutor2, types2, types1AtSite, languageLevel));
 
           if (applicable12ignoreFunctionalType || applicable21ignoreFunctionalType) {
             Specifics specifics = null;
@@ -616,18 +632,13 @@
     return Specifics.NEITHER;
   }
 
-  private boolean isApplicableTo(PsiType[] types2AtSite,
-                                 PsiMethod method1,
-                                 PsiTypeParameter[] typeParameters1,
-                                 LanguageLevel languageLevel,
-                                 boolean varargsPosition, PsiType[] types1, PsiSubstitutor siteSubstitutor1) {
-    final PsiSubstitutor methodSubstitutor1 = calculateMethodSubstitutor(typeParameters1, method1, siteSubstitutor1, types1, types2AtSite, languageLevel);
+  private static boolean isApplicableTo(PsiType[] types2AtSite,
+                                        PsiMethod method1,
+                                        LanguageLevel languageLevel,
+                                        boolean varargsPosition,
+                                        final PsiSubstitutor methodSubstitutor1) {
     final int applicabilityLevel = PsiUtil.getApplicabilityLevel(method1, methodSubstitutor1, types2AtSite, languageLevel, false, varargsPosition);
-    final boolean applicable = applicabilityLevel > MethodCandidateInfo.ApplicabilityLevel.NOT_APPLICABLE;
-    if (applicable && !GenericsUtil.isTypeArgumentsApplicable(typeParameters1, methodSubstitutor1, myArgumentsList, false)) {
-      return false;
-    }
-    return applicable;
+    return applicabilityLevel > MethodCandidateInfo.ApplicabilityLevel.NOT_APPLICABLE;
   }
 
   private static PsiType[] typesAtSite(PsiType[] types1, PsiSubstitutor siteSubstitutor1) {
@@ -650,7 +661,7 @@
       ProgressManager.checkCanceled();
       LOG.assertTrue(typeParameter != null);
       if (!substitutor.getSubstitutionMap().containsKey(typeParameter)) {
-        substitutor = substitutor.put(typeParameter, siteSubstitutor.substitute(typeParameter));
+        substitutor = substitutor.put(typeParameter, TypeConversionUtil.erasure(siteSubstitutor.substitute(typeParameter), substitutor));
       }
     }
     return substitutor;
diff --git a/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java b/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java
index 8556ee1..30f9084 100644
--- a/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java
+++ b/java/java-psi-impl/src/com/intellij/psi/scope/util/PsiScopesUtil.java
@@ -25,6 +25,7 @@
 
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicatorProvider;
+import com.intellij.openapi.util.Comparing;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.resolve.JavaResolveUtil;
@@ -318,7 +319,13 @@
               if (initializer instanceof PsiNewExpression) {
                 final PsiAnonymousClass anonymousClass = ((PsiNewExpression)initializer).getAnonymousClass();
                 if (anonymousClass != null && type.equals(anonymousClass.getBaseClassType())) {
-                  type = initializer.getType();
+                  final PsiMethod[] refMethods = anonymousClass.findMethodsByName(methodCall.getMethodExpression().getReferenceName(), false);
+                  if (refMethods.length > 0) {
+                    final PsiClass baseClass = PsiUtil.resolveClassInType(type);
+                    if (baseClass != null && !hasCovariantOverriding(baseClass, refMethods)) {
+                      type = initializer.getType();
+                    }
+                  }
                 }
               }
             }
@@ -381,6 +388,18 @@
     }
   }
 
+  private static boolean hasCovariantOverriding(PsiClass baseClass, PsiMethod[] refMethods) {
+    for (PsiMethod method : refMethods) {
+      final PsiType methodReturnType = method.getReturnType();
+      for (PsiMethod superMethod : method.findSuperMethods(baseClass)) {
+        if (!Comparing.equal(methodReturnType, superMethod.getReturnType())) {
+          return true;
+        }
+      }
+    }
+    return false;
+  }
+
   private static boolean processQualifierType(@NotNull final PsiType type,
                                               final MethodsProcessor processor,
                                               PsiManager manager,
diff --git a/java/java-tests/java-tests.iml b/java/java-tests/java-tests.iml
index cc0afca..01e606b 100644
--- a/java/java-tests/java-tests.iml
+++ b/java/java-tests/java-tests.iml
@@ -30,6 +30,7 @@
     <orderEntry type="module" module-name="java-indexing-api" scope="TEST" />
     <orderEntry type="module" module-name="external-system-impl" scope="RUNTIME" />
     <orderEntry type="module" module-name="junit_rt" scope="TEST" />
+    <orderEntry type="module" module-name="xml-psi-impl" scope="TEST" />
   </component>
 </module>
 
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/FilteredMethodReference-out.java b/java/java-tests/testData/codeInsight/completion/smartType/FilteredMethodReference-out.java
new file mode 100644
index 0000000..2086ad1
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/smartType/FilteredMethodReference-out.java
@@ -0,0 +1,13 @@
+class Test {
+  interface I {
+    int foo();
+  }
+
+  static int aa() {
+    return 0;
+  }
+
+  {
+    I i = Test::aa
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/FilteredMethodReference.java b/java/java-tests/testData/codeInsight/completion/smartType/FilteredMethodReference.java
new file mode 100644
index 0000000..f49bb50
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/smartType/FilteredMethodReference.java
@@ -0,0 +1,13 @@
+class Test {
+  interface I {
+    int foo();
+  }
+
+  static int aa() {
+    return 0;
+  }
+
+  {
+    I i = Test::<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/InferFromRawType.java b/java/java-tests/testData/codeInsight/completion/smartType/InferFromRawType.java
new file mode 100644
index 0000000..8a2ea29
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/smartType/InferFromRawType.java
@@ -0,0 +1,5 @@
+class A<T extends String> {
+  {
+    A a = new A<<caret>>();
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/completion/smartType/NotAvailableInLambdaPositionAfterQualifier.java b/java/java-tests/testData/codeInsight/completion/smartType/NotAvailableInLambdaPositionAfterQualifier.java
new file mode 100644
index 0000000..f7523c6
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/completion/smartType/NotAvailableInLambdaPositionAfterQualifier.java
@@ -0,0 +1,9 @@
+class Test {
+  interface I {
+    void foo();
+  }
+
+  {
+    I i = Unknown::<caret>
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/wrongPlace.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/wrongPlace.java
index ab1d2f0..581948e 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/wrongPlace.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/annotations/wrongPlace.java
@@ -27,4 +27,10 @@
 
 @interface Caller {
   Anno anno() default @Anno;
-}
\ No newline at end of file
+}
+
+@interface AnnoArray {
+  @interface Part { }
+
+  Part[] arrayValue() default {@Part, @Part};
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104160.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104160.java
index 92e5b57..32d2c84 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104160.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA104160.java
@@ -10,4 +10,9 @@
   class B extends ArrayList<T> {
       void foo(T r){}
   }
+  
+  static class C extends Test<<error descr="'Test.this' cannot be referenced from a static context">T</error>> {}
+  static class D extends Test {
+    <error descr="'Test.this' cannot be referenced from a static context">T</error> t;
+  }
 }
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA117827.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA117827.java
new file mode 100644
index 0000000..afa7d2a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA117827.java
@@ -0,0 +1,16 @@
+
+import java.util.Collection;
+import java.util.List;
+
+public class Testsss {
+
+  public <TA, CA extends Iterable<TA>> void that(Iterable<TA> target) {}
+
+  public <T, C extends Collection<T>> void that(Collection<T> target) {}
+
+  void foo(ImmutableList<String> l) {
+    that( l);
+  }
+
+  interface ImmutableList<T> extends List<T> {}
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA118037.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA118037.java
new file mode 100644
index 0000000..47ff27a
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/genericsHighlighting/IDEA118037.java
@@ -0,0 +1,14 @@
+final class Test
+{
+  class Foo
+  {
+    <T extends String> void foo(Class<T> clazz)
+    {
+      if (<error descr="Operator '==' cannot be applied to 'java.lang.Class<java.lang.Void>', 'java.lang.Class<T>'">Void.class == clazz</error>)
+      {
+        System.out.println("Yeah!");
+      }
+    }
+  }
+}
+
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/diamond/OuterClass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/diamond/OuterClass.java
new file mode 100644
index 0000000..d69d551
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/diamond/OuterClass.java
@@ -0,0 +1,23 @@
+import java.util.*;
+
+class HT<O> {
+    private Iterator<O> getIterator(int type, int count) {
+      return new Enumerator<>(type, true);
+    }
+
+    private class Enumerator<T> implements Iterator<T> {
+
+        public Enumerator(int type, boolean b) {
+        }
+
+        @Override
+        public boolean hasNext() {
+            return false;
+        }
+
+        @Override
+        public T next() {
+            return null;
+        }
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ResolveConflicts.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ResolveConflicts.java
index 681e207..919a623 100644
--- a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ResolveConflicts.java
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/methodRef/ResolveConflicts.java
@@ -6,7 +6,7 @@
 class Main {
 
     public static void main(final String[] args) {
-        Func<Integer, String> func =  Integer::toString;
+        <error descr="Incompatible types. Found: '<method reference>', required: 'Func<java.lang.Integer,java.lang.String>'">Func<Integer, String> func =  Integer::toString;</error>
         System.out.println(func.run(6));
     }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/ArgumentOfAnonymousClass.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/ArgumentOfAnonymousClass.java
new file mode 100644
index 0000000..dfd4563
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/ArgumentOfAnonymousClass.java
@@ -0,0 +1,19 @@
+interface I<T> {
+    void accept(T t);
+}
+
+class LamdbaTest<T> {
+
+    public void f() {
+        new A<T>(t -> g(t)) {};
+    }
+
+    private void g(T t) {
+    }
+
+    class A<T2> {
+        public A(I<T> editor) {
+        }
+    }
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/Ellipsis.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/Ellipsis.java
new file mode 100644
index 0000000..6342785
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/Ellipsis.java
@@ -0,0 +1,9 @@
+interface Var {
+    void var(int... ps);
+}
+
+class Abc {
+    void foo() {
+        Var var = (int[] ps) -> {};
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/OuterMethodPropagation.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/OuterMethodPropagation.java
new file mode 100644
index 0000000..b19ca63
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/lambda/newLambda/OuterMethodPropagation.java
@@ -0,0 +1,17 @@
+public class Tmp
+{
+  interface BiFunction<T, U, R> {
+    R apply(T t, U u);
+  }
+
+  interface Sequence<T>
+  {
+    <R> Sequence<R> scan(R init, BiFunction<R, T, R> func);
+  }
+
+  static <T> void foo(Sequence<T> sequence){}
+
+  void test(Sequence<String> strings) {
+    foo(strings.scan(1, (i, s) -> 1));
+  }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeArgumentsConditional/afterEliminateWildcards.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeArgumentsConditional/afterEliminateWildcards.java
new file mode 100644
index 0000000..a228257
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeArgumentsConditional/afterEliminateWildcards.java
@@ -0,0 +1,12 @@
+// "Add explicit type arguments" "true"
+import java.util.*;
+
+class Test {
+     static class A {}
+     static class B extends A {}
+ 
+ 
+     public Collection<? extends A> run(boolean flag) {
+         return flag ? Collections.singletonList(new B()) : Collections.<A>emptyList();
+     }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeArgumentsConditional/beforeEliminateWildcards.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeArgumentsConditional/beforeEliminateWildcards.java
new file mode 100644
index 0000000..8d4383c
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/addTypeArgumentsConditional/beforeEliminateWildcards.java
@@ -0,0 +1,12 @@
+// "Add explicit type arguments" "true"
+import java.util.*;
+
+class Test {
+     static class A {}
+     static class B extends A {}
+ 
+ 
+     public Collection<? extends A> run(boolean flag) {
+         return flag ? Collections.singletonList(new B()) : Collections.<caret>emptyList();
+     }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2methodReference/beforeSideEffects.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2methodReference/beforeSideEffects.java
new file mode 100644
index 0000000..754a9ea
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/anonymous2methodReference/beforeSideEffects.java
@@ -0,0 +1,13 @@
+// "Replace with method reference" "false"
+class Test {
+  public interface I {
+    String m();
+  }
+
+  public static void main(String[] args) {
+    I<String> supplier = () -> new Ob<caret>ject().toString();
+
+    System.out.println(supplier.get());
+    System.out.println(supplier.get());
+  }
+}
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/afterAmbiguousMethods.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/afterAmbiguousMethods.java
new file mode 100644
index 0000000..475f46e
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/afterAmbiguousMethods.java
@@ -0,0 +1,10 @@
+// "Replace lambda with method reference" "true"
+class Example {
+    interface I {
+      String foo(Integer i);
+    }
+  
+    {
+      I i = Object::toString;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeAmbiguousMethods.java b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeAmbiguousMethods.java
new file mode 100644
index 0000000..b731848
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/daemonCodeAnalyzer/quickFix/lambda2methodReference/beforeAmbiguousMethods.java
@@ -0,0 +1,10 @@
+// "Replace lambda with method reference" "true"
+class Example {
+    interface I {
+      String foo(Integer i);
+    }
+  
+    {
+      I i = (i1) -> i1.<caret>toString();
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/javadocIG/code.html b/java/java-tests/testData/codeInsight/javadocIG/code.html
new file mode 100644
index 0000000..e75e091
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/javadocIG/code.html
@@ -0,0 +1,10 @@
+<html><head>    <style type="text/css">        #error {            background-color: #eeeeee;            margin-bottom: 10px;        }        p {            margin: 5px 0;        }    </style></head><body><small><b><a href="psi_element://Foo"><code>Foo</code></a></b></small><PRE>int <b>foo</b></PRE>
+     <pre>
+     <code>
+      class Clazzz {
+        def f[U](u: U) {}
+   
+        val a = 1
+      }
+    </code>
+     </pre></body></html>
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/javadocIG/code.java b/java/java-tests/testData/codeInsight/javadocIG/code.java
new file mode 100644
index 0000000..f5cf2a7
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/javadocIG/code.java
@@ -0,0 +1,14 @@
+class Foo {
+  /**
+   * <pre>
+   * {@code
+   *   class Clazzz {
+   *     def f[U](u: U) {}
+   *
+   *     val a = 1
+   *   }
+   * }
+   * </pre>
+  */
+  int foo;
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/codeInsight/parameterInfo/SelectionWithGenerics.java b/java/java-tests/testData/codeInsight/parameterInfo/SelectionWithGenerics.java
new file mode 100644
index 0000000..cfafbdb
--- /dev/null
+++ b/java/java-tests/testData/codeInsight/parameterInfo/SelectionWithGenerics.java
@@ -0,0 +1,12 @@
+class Test {
+  {
+    refresh(<caret>false, false, null, "");
+  }
+
+  public final void refresh(boolean async, boolean recursive,  Runnable finishRunnable, String... files) {
+  }
+
+  public final void refresh(boolean async, boolean recursive, Runnable finishRunnable, Integer files) {
+  }
+
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass.log b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass.log
new file mode 100644
index 0000000..228bc41
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass.log
@@ -0,0 +1,11 @@
+Compiling files:
+src/package2/A.java
+End of files
+Cleaning output files:
+out/production/AddClassHidingImportedClass/package2/B.class
+out/production/AddClassHidingImportedClass/package3/C.class
+End of files
+Compiling files:
+src/package2/B.java
+src/package3/C.java
+End of files
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package1/A.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package1/A.java
new file mode 100644
index 0000000..a61ecd9
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package1/A.java
@@ -0,0 +1,7 @@
+package package1;
+
+public class A {
+    public static class D {
+       public final String s = new String("package1");
+    }
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/A.java.new b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/A.java.new
new file mode 100644
index 0000000..98b0fee
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/A.java.new
@@ -0,0 +1,7 @@
+package package2;
+
+public class A {
+    public static class D {
+        public final String s = new String("package2");
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/B.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/B.java
new file mode 100644
index 0000000..a32b694
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package2/B.java
@@ -0,0 +1,6 @@
+package package2;
+import package1.*;
+
+public class B extends A{
+
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package3/C.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package3/C.java
new file mode 100644
index 0000000..04d86d3
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass/src/package3/C.java
@@ -0,0 +1,14 @@
+package package3;
+
+import package2.B;
+
+public class C {
+
+    public B.D p;
+
+    public String get() {
+        p = new B.D();
+        return p.s;
+    }
+
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2.log b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2.log
new file mode 100644
index 0000000..8564c55fc9
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2.log
@@ -0,0 +1,15 @@
+Cleaning output files:
+out/production/AddClassHidingImportedClass2/package3/C.class
+End of files
+Compiling files:
+src/package2/A.java
+src/package3/C.java
+End of files
+Cleaning output files:
+out/production/AddClassHidingImportedClass2/package2/B.class
+out/production/AddClassHidingImportedClass2/package3/C.class
+End of files
+Compiling files:
+src/package2/B.java
+src/package3/C.java
+End of files
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package1/A.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package1/A.java
new file mode 100644
index 0000000..a61ecd9
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package1/A.java
@@ -0,0 +1,7 @@
+package package1;
+
+public class A {
+    public static class D {
+       public final String s = new String("package1");
+    }
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package2/A.java.new b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package2/A.java.new
new file mode 100644
index 0000000..98b0fee
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package2/A.java.new
@@ -0,0 +1,7 @@
+package package2;
+
+public class A {
+    public static class D {
+        public final String s = new String("package2");
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package2/B.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package2/B.java
new file mode 100644
index 0000000..a32b694
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package2/B.java
@@ -0,0 +1,6 @@
+package package2;
+import package1.*;
+
+public class B extends A{
+
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package3/C.java b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package3/C.java
new file mode 100644
index 0000000..6ba1003
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package3/C.java
@@ -0,0 +1,15 @@
+package package3;
+
+import package2.B;
+
+public class C {
+
+    public B.D p;
+
+    public String get() {
+        p = new B.D();
+        return p.s;
+    }
+
+   public void dummy() {}
+}
diff --git a/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package3/C.java.new b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package3/C.java.new
new file mode 100644
index 0000000..5074eb23
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/common/addClassHidingImportedClass2/src/package3/C.java.new
@@ -0,0 +1,16 @@
+package package3;
+
+import package2.B;
+
+public class C {
+
+    public B.D p;
+
+    public String get() {
+        p = new B.D();
+        return p.s;
+    }
+
+  // commenting dummy method => causing class change => compilation on the first round
+  // public void dummy() {}
+}
diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/constantChain.log b/java/java-tests/testData/compileServer/incremental/fieldProperties/constantChain.log
index 37245f2..278d40b 100644
--- a/java/java-tests/testData/compileServer/incremental/fieldProperties/constantChain.log
+++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/constantChain.log
@@ -12,3 +12,9 @@
 src/Client.java
 src/ServerClient.java
 End of files
+Cleaning output files:
+out/production/ConstantChain/Server.class
+End of files
+Compiling files:
+src/Server.java
+End of files
diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants.log b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants.log
new file mode 100644
index 0000000..e4b795d
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants.log
@@ -0,0 +1,16 @@
+Cleaning output files:
+out/production/MutualConstants/constants/B.class
+End of files
+Compiling files:
+src/constants/B.java
+End of files
+Cleaning output files:
+out/production/MutualConstants/constants/A.class
+out/production/MutualConstants/constants/B.class
+out/production/MutualConstants/constants/PrintConst.class
+End of files
+Compiling files:
+src/constants/A.java
+src/constants/B.java
+src/constants/PrintConst.java
+End of files
diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/A.java b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/A.java
new file mode 100644
index 0000000..b817093
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/A.java
@@ -0,0 +1,5 @@
+package constants;
+
+public class A {
+  public static final int CONST_A = B.CONST_B_1 + 1;
+}
diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/B.java b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/B.java
new file mode 100644
index 0000000..e3a2d4f
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/B.java
@@ -0,0 +1,5 @@
+package constants;
+public class B {
+  public static final int CONST_B_1 = 0;
+  public static final int CONST_B_2 = A.CONST_A + 1;
+}
diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/B.java.new b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/B.java.new
new file mode 100644
index 0000000..7ccf22f
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/B.java.new
@@ -0,0 +1,5 @@
+package constants;
+public class B {
+  public static final int CONST_B_1 = 1;
+  public static final int CONST_B_2 = A.CONST_A + 1;
+}
diff --git a/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/PrintConst.java b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/PrintConst.java
new file mode 100644
index 0000000..ccf17f8
--- /dev/null
+++ b/java/java-tests/testData/compileServer/incremental/fieldProperties/mutualConstants/src/constants/PrintConst.java
@@ -0,0 +1,7 @@
+package constants;
+
+public class PrintConst {
+  public static void main(String[] args) {
+    System.out.println(B.CONST_B_2);
+  }
+}
diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java b/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java
index 652f0dc..cfe0d0e 100644
--- a/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java
+++ b/java/java-tests/testData/inspection/dataFlow/fixture/PrimitiveCastMayChangeValue.java
@@ -10,6 +10,10 @@
     } else {
       System.out.println("4");
     }
+    
+    if (0 == (long)<error descr="Cannot resolve symbol 'i'">i</error>) {
+      System.out.println("0");
+    }
   }
 
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/ReturnNullInLambdaExpression.java b/java/java-tests/testData/inspection/dataFlow/fixture/ReturnNullInLambdaExpression.java
new file mode 100644
index 0000000..92d0f42
--- /dev/null
+++ b/java/java-tests/testData/inspection/dataFlow/fixture/ReturnNullInLambdaExpression.java
@@ -0,0 +1,12 @@
+import org.jetbrains.annotations.NotNull;
+
+class Test {
+  interface I {
+    @NotNull
+    String get();
+  }
+
+  {
+    I i = () -> <warning descr="'null' is returned by the method declared as @NotNull">null</warning>;
+  }
+}
diff --git a/java/java-tests/testData/inspection/dataFlow/fixture/ReturnNullInLambdaStatement.java b/java/java-tests/testData/inspection/dataFlow/fixture/ReturnNullInLambdaStatement.java
new file mode 100644
index 0000000..0566fce
--- /dev/null
+++ b/java/java-tests/testData/inspection/dataFlow/fixture/ReturnNullInLambdaStatement.java
@@ -0,0 +1,12 @@
+import org.jetbrains.annotations.NotNull;
+
+class Test {
+  interface I {
+    @NotNull
+    String get();
+  }
+
+  {
+    I i = () -> {return <warning descr="'null' is returned by the method declared as @NotNull">null</warning>;};
+  }
+}
diff --git a/java/java-tests/testData/inspection/localCanBeFinal/For/src/For.java b/java/java-tests/testData/inspection/localCanBeFinal/For/src/For.java
index 529844b..4a10521 100644
--- a/java/java-tests/testData/inspection/localCanBeFinal/For/src/For.java
+++ b/java/java-tests/testData/inspection/localCanBeFinal/For/src/For.java
@@ -1,7 +1,8 @@
 class For {
   void f(List<String> list) {
-    for (Iterator<String>  it = list.iterator(); it.hasNext();) { // 'it' can be final but not reported
+    for (Iterator<String>  it = list.iterator(); it.hasNext();) {
     }
     for (int i = 0; i < 10; i++) {}
+    for (int i = 0, length = 10; i < length; i++) {}
   }
 }
\ No newline at end of file
diff --git a/java/java-tests/testData/inspection/redundantCast/generics/SafeTempVarName/expected.xml b/java/java-tests/testData/inspection/redundantCast/generics/SafeTempVarName/expected.xml
new file mode 100644
index 0000000..4704d91
--- /dev/null
+++ b/java/java-tests/testData/inspection/redundantCast/generics/SafeTempVarName/expected.xml
@@ -0,0 +1,2 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<problems/>
\ No newline at end of file
diff --git a/java/java-tests/testData/inspection/redundantCast/generics/SafeTempVarName/src/Test.java b/java/java-tests/testData/inspection/redundantCast/generics/SafeTempVarName/src/Test.java
new file mode 100644
index 0000000..c7fa33b
--- /dev/null
+++ b/java/java-tests/testData/inspection/redundantCast/generics/SafeTempVarName/src/Test.java
@@ -0,0 +1,9 @@
+import java.util.*;
+
+public class RedundantCast{
+    <T> void foo2(List<Object[]> x) {
+        for (Object[] l : x) {
+           String[] s = (String[]) l;
+        }
+    }
+}
diff --git a/java/java-tests/testData/inspection/redundantTypeArgs/NestedCalls.java b/java/java-tests/testData/inspection/redundantTypeArgs/NestedCalls.java
new file mode 100644
index 0000000..9121bda
--- /dev/null
+++ b/java/java-tests/testData/inspection/redundantTypeArgs/NestedCalls.java
@@ -0,0 +1,18 @@
+import java.io.Serializable;
+
+final class Expected {
+  public static <P extends Serializable> Expected make(final P good) {
+    return null;
+  }
+}
+
+interface Serializer {
+  <T> T deserialize(final Class<T> type);
+}
+
+class FooBar {
+  <T extends Serializable> void invoke(final Class<T> rpc, final Serializer serializer) {
+    Expected.make(serializer.<warning descr="Explicit type arguments can be inferred"><T></warning>deserialize(rpc));
+  }
+}
+
diff --git a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java
index 93e69f1..e016830 100644
--- a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java
+++ b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags.java
@@ -17,8 +17,12 @@
              str3 = "Green",
               str4 = "Blue";
     // @formatter:on
+    if        (true)
+          System.out.println("True");
     Iterator iterator;
     // @formatter:off
+    if    (true)
+          System.out.println("True");
     collection.add(str1);
       collection.add(str2);
         collection.add(str3);
@@ -39,6 +43,9 @@
    *     And yet another one.
    */
   public void doSomething(String x, String y) {
+    if
+       (true)
+          System.out.println("True");
   }
   // @formatter:on
 
@@ -47,7 +54,10 @@
    *    @param   z
    *       Parameter Z.
    */
-  public void doSomethingElse(String z) {}
+  public void doSomethingElse(String z) {
+    if    (true)
+          System.out.println("True");
+  }
 
   // @formatter:off
   /**
@@ -57,6 +67,10 @@
    *   @param j
    *      Parameter J.
    */
-  public void evenMore(int i, int j) {}
+  public void evenMore(int i, int j) {
+    if
+       (true)
+          System.out.println("True");
+  }
   // @formatter:on
 }
diff --git a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java
index 01233b3a..e0102b6 100644
--- a/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java
+++ b/java/java-tests/testData/psi/formatter/java/FormatterOnOffTags_after.java
@@ -17,8 +17,13 @@
              str3 = "Green",
               str4 = "Blue";
     // @formatter:on
+        if (true) {
+            System.out.println("True");
+        }
         Iterator iterator;
         // @formatter:off
+    if    (true)
+          System.out.println("True");
     collection.add(str1);
       collection.add(str2);
         collection.add(str3);
@@ -39,6 +44,9 @@
    *     And yet another one.
    */
   public void doSomething(String x, String y) {
+    if
+       (true)
+          System.out.println("True");
   }
   // @formatter:on
 
@@ -48,6 +56,9 @@
      * @param z Parameter Z.
      */
     public void doSomethingElse(String z) {
+        if (true) {
+            System.out.println("True");
+        }
     }
 
     // @formatter:off
@@ -58,6 +69,10 @@
    *   @param j
    *      Parameter J.
    */
-  public void evenMore(int i, int j) {}
+  public void evenMore(int i, int j) {
+    if
+       (true)
+          System.out.println("True");
+  }
   // @formatter:on
 }
diff --git a/java/java-tests/testData/psi/resolve/method/generics/CovariantReturnTypeAnonymous.java b/java/java-tests/testData/psi/resolve/method/generics/CovariantReturnTypeAnonymous.java
new file mode 100644
index 0000000..b487a30
--- /dev/null
+++ b/java/java-tests/testData/psi/resolve/method/generics/CovariantReturnTypeAnonymous.java
@@ -0,0 +1,20 @@
+interface X {
+    A[] foo();
+}
+
+class A {}
+
+class B extends A {}
+
+class C {
+    final X x = new X() {
+        @Override
+        public B[] foo() {
+            return new B[0];
+        }
+    };
+
+    B[] bar() {
+        return x.f<ref>oo();
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineParameter/FromClassInitializer.java b/java/java-tests/testData/refactoring/inlineParameter/FromClassInitializer.java
new file mode 100644
index 0000000..ecb1a4a
--- /dev/null
+++ b/java/java-tests/testData/refactoring/inlineParameter/FromClassInitializer.java
@@ -0,0 +1,10 @@
+class X {
+    {
+        String str = "";
+        foo(str, str.substring(0));
+    }
+
+    void foo(String str, String st<caret>r1) {
+
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/inlineParameter/FromClassInitializer.java.after b/java/java-tests/testData/refactoring/inlineParameter/FromClassInitializer.java.after
new file mode 100644
index 0000000..167339b
--- /dev/null
+++ b/java/java-tests/testData/refactoring/inlineParameter/FromClassInitializer.java.after
@@ -0,0 +1,10 @@
+class X {
+    {
+        String str = "";
+        foo(str);
+    }
+
+    void foo(String str) {
+
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass3.after.java b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass3.after.java
new file mode 100644
index 0000000..e326017
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass3.after.java
@@ -0,0 +1,27 @@
+import java.io.PrintStream;
+class Foo {
+
+    public static void bazz(int i) {
+        Foo j = new Foo(new IBar() {
+            public void doSomething(PrintStream out) {
+                out.println("hello");
+            }
+        });
+        final Foo foo = i != 0 ? j : j;
+        foo.bla();
+    }
+
+    private final IBar bar;
+
+    public Foo(IBar bar) {
+        this.bar = bar;
+    }
+
+    public void bla() {
+        bar.doSomething(System.out);
+    }
+
+    public interface IBar {
+        void doSomething(PrintStream out);
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass3.java b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass3.java
new file mode 100644
index 0000000..b2f3688
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass3.java
@@ -0,0 +1,30 @@
+import java.io.PrintStream;
+class Foo {
+
+    public static void bazz(int i) {
+        final Foo foo = i != 0 ? <selection>new Foo(new IBar() {
+            public void doSomething(PrintStream out) {
+                out.println("hello");
+            }
+        })</selection> : new Foo(new IBar() {
+            public void doSomething(PrintStream out) {
+                out.println("hello");
+            }
+        });
+        foo.bla();
+    }
+
+    private final IBar bar;
+
+    public Foo(IBar bar) {
+        this.bar = bar;
+    }
+
+    public void bla() {
+        bar.doSomething(System.out);
+    }
+
+    public interface IBar {
+        void doSomething(PrintStream out);
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass4.after.java b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass4.after.java
new file mode 100644
index 0000000..4642ab3a
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass4.after.java
@@ -0,0 +1,22 @@
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ExtractVariableSample {
+
+    public static void main(String[] args) {
+        Collection<String> strings = new ArrayList<>();
+        new Object() {
+            public void foo(String s) {
+                System.out.println( s.hashCode());
+            }
+        };
+
+        for (String s : strings) {
+            int j = s.hashCode();
+            System.out.println(j);
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass4.java b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass4.java
new file mode 100644
index 0000000..1415fc9
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass4.java
@@ -0,0 +1,21 @@
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ExtractVariableSample {
+
+    public static void main(String[] args) {
+        Collection<String> strings = new ArrayList<>();
+        new Object() {
+            public void foo(String s) {
+                System.out.println( s.hashCode());
+            }
+        };
+
+        for (String s : strings) {
+            System.out.println(<selection>s.hashCode()</selection>);
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass5.after.java b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass5.after.java
new file mode 100644
index 0000000..9157c78
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass5.after.java
@@ -0,0 +1,20 @@
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ExtractVariableSample {
+
+    public static void main(String[] args, String s) {
+        Collection<String> strings = new ArrayList<>();
+        new Object() {
+            public void foo(String s) {
+                System.out.println( s.hashCode());
+            }
+        };
+
+        int j = s.hashCode();
+        System.out.println(j);
+    }
+
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass5.java b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass5.java
new file mode 100644
index 0000000..7e1bc3a
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/AnonymousClass5.java
@@ -0,0 +1,19 @@
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ExtractVariableSample {
+
+    public static void main(String[] args, String s) {
+        Collection<String> strings = new ArrayList<>();
+        new Object() {
+            public void foo(String s) {
+                System.out.println( s.hashCode());
+            }
+        };
+
+        System.out.println(<selection>s.hashCode()</selection>);
+    }
+
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/Lambda.after.java b/java/java-tests/testData/refactoring/introduceVariable/Lambda.after.java
new file mode 100644
index 0000000..3d95282
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/Lambda.after.java
@@ -0,0 +1,22 @@
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ExtractVariableSample {
+    interface I {
+      void foo(String s);
+    }
+
+    public static void main(String[] args) {
+        Collection<String> strings = new ArrayList<>();
+        I i = (s) -> {
+            int j = s.hashCode();
+            System.out.println(j); };
+
+        for (String s : strings) {
+            System.out.println(s.hashCode());
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/Lambda.java b/java/java-tests/testData/refactoring/introduceVariable/Lambda.java
new file mode 100644
index 0000000..e331f2b
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/Lambda.java
@@ -0,0 +1,20 @@
+
+import java.util.ArrayList;
+import java.util.Collection;
+
+public class ExtractVariableSample {
+    interface I {
+      void foo(String s);
+    }
+
+    public static void main(String[] args) {
+        Collection<String> strings = new ArrayList<>();
+        I i = (s) -> { System.out.println(<selection>s.hashCode()</selection>); };
+
+        for (String s : strings) {
+            System.out.println(s.hashCode());
+        }
+    }
+
+
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/introduceVariable/SubLiteralFailure.java b/java/java-tests/testData/refactoring/introduceVariable/SubLiteralFailure.java
new file mode 100644
index 0000000..8eb2a45
--- /dev/null
+++ b/java/java-tests/testData/refactoring/introduceVariable/SubLiteralFailure.java
@@ -0,0 +1,5 @@
+class A {
+    public void test() {
+        int i = <selection>1</selection>23 + 123;
+    }
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/pullUp/PublicMethodFromPrivateClassConflict.java b/java/java-tests/testData/refactoring/pullUp/PublicMethodFromPrivateClassConflict.java
new file mode 100644
index 0000000..a028329
--- /dev/null
+++ b/java/java-tests/testData/refactoring/pullUp/PublicMethodFromPrivateClassConflict.java
@@ -0,0 +1,9 @@
+import java.util.*;
+class A {}
+class B extends A {
+  void fo<caret>o() {
+    HM<String, String> hm = new HM<>();
+    for (Map.Entry<String, String> stringStringEntry : hm.entrySet()) {}
+  }
+  private static class HM<K, V> extends HashMap<K, V>{}
+}
\ No newline at end of file
diff --git a/java/java-tests/testData/refactoring/pullUp/PublicMethodFromPrivateClassConflict_after.java b/java/java-tests/testData/refactoring/pullUp/PublicMethodFromPrivateClassConflict_after.java
new file mode 100644
index 0000000..96932a3
--- /dev/null
+++ b/java/java-tests/testData/refactoring/pullUp/PublicMethodFromPrivateClassConflict_after.java
@@ -0,0 +1,11 @@
+import java.util.*;
+class A {
+    void foo() {
+      HM<String, String> hm = new HM<>();
+      for (Map.Entry<String, String> stringStringEntry : hm.entrySet()) {}
+    }
+
+    private static class HM<K, V> extends HashMap<K, V>{}
+}
+class B extends A {
+}
\ No newline at end of file
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/ParameterInfoTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/ParameterInfoTest.java
index b31fb16..2c757c1 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/ParameterInfoTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/ParameterInfoTest.java
@@ -10,6 +10,9 @@
 import com.intellij.psi.infos.MethodCandidateInfo;
 import com.intellij.testFramework.LightCodeInsightTestCase;
 import com.intellij.testFramework.utils.parameterInfo.MockCreateParameterInfoContext;
+import com.intellij.testFramework.utils.parameterInfo.MockUpdateParameterInfoContext;
+import com.intellij.util.ArrayUtil;
+import com.intellij.util.ArrayUtilRt;
 import com.intellij.util.Function;
 import junit.framework.Assert;
 
@@ -54,6 +57,35 @@
     doTestPresentation("<html>List&lt;String&gt; param</html>");
   }
 
+  public void testSelectionWithGenerics() throws Exception {
+    configureByFile(BASE_PATH + getTestName(false) + ".java");
+
+    final MethodParameterInfoHandler handler = new MethodParameterInfoHandler();
+    final CreateParameterInfoContext context = new MockCreateParameterInfoContext(myEditor, myFile);
+    final PsiExpressionList list = handler.findElementForParameterInfo(context);
+    assertNotNull(list);
+    final Object[] itemsToShow = context.getItemsToShow();
+    assertNotNull(itemsToShow);
+    assertTrue(itemsToShow.length == 2);
+    assertTrue(itemsToShow[0] instanceof MethodCandidateInfo);
+    final ParameterInfoUIContextEx parameterContext = ParameterInfoComponent.createContext(itemsToShow, myEditor, handler, -1);
+    final Boolean [] enabled = new Boolean[itemsToShow.length];
+    final MockUpdateParameterInfoContext updateParameterInfoContext = new MockUpdateParameterInfoContext(myEditor, myFile){
+      @Override
+      public Object[] getObjectsToView() {
+        return itemsToShow;
+      }
+
+      @Override
+      public void setUIComponentEnabled(int index, boolean b) {
+        enabled[index] = b;
+      }
+    };
+    updateParameterInfoContext.setParameterOwner(list);
+    handler.updateParameterInfo(list, updateParameterInfoContext);
+    assertTrue(ArrayUtilRt.find(enabled, Boolean.TRUE) > -1);
+  }
+
   public void testAfterGenericsInsideCall() throws Exception {
     configureByFile(BASE_PATH + getTestName(false) + ".java");
 
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy b/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy
index ab9ea13..669f0f5 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/HippieCompletionTest.groovy
@@ -36,16 +36,29 @@
 
   public void testFromAnotherFile() {
     myFixture.configureByText "b.txt", '''
-$some_long_variable_name = Obj::instance();
+$some_local = 1;
 '''
     myFixture.configureByText "a.txt", '''
-$some_lon<caret>
+$some_long_variable_name = Obj::instance();
+$some_lo<caret>
 '''
 
     complete()
     myFixture.checkResult '''
+$some_long_variable_name = Obj::instance();
 $some_long_variable_name<caret>
 '''
+    complete()
+    myFixture.checkResult '''
+$some_long_variable_name = Obj::instance();
+$some_local<caret>
+'''
+    backComplete()
+    myFixture.checkResult '''
+$some_long_variable_name = Obj::instance();
+$some_long_variable_name<caret>
+'''
+
   }
 
   public void "test no middle matching"() {
@@ -128,7 +141,24 @@
 
   }
 
+  public void "test file start"() {
+    myFixture.configureByText "a.java", '''<caret>
+class Xoo {
+}
+'''
+    complete()
+    myFixture.checkResult '''class<caret>
+class Xoo {
+}
+'''
+
+  }
+
   private void complete() {
     myFixture.performEditorAction(IdeActions.ACTION_HIPPIE_COMPLETION)
   }
+
+  private void backComplete() {
+    myFixture.performEditorAction(IdeActions.ACTION_HIPPIE_BACKWARD_COMPLETION)
+  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartType18CompletionTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartType18CompletionTest.java
index c386bd3..7284025 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartType18CompletionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/completion/SmartType18CompletionTest.java
@@ -17,6 +17,9 @@
 
 import com.intellij.JavaTestUtil;
 import com.intellij.codeInsight.lookup.Lookup;
+import com.intellij.psi.JavaPsiFacade;
+import com.intellij.psi.impl.source.resolve.PsiResolveHelperImpl;
+import com.intellij.psi.impl.source.resolve.graphInference.PsiGraphInferenceHelper;
 import com.intellij.testFramework.LightProjectDescriptor;
 import org.jetbrains.annotations.NotNull;
 
@@ -70,6 +73,29 @@
     doTest();
   }
 
+  public void testFilteredMethodReference() throws Exception {
+    doTest();
+  }
+
+  public void testNotAvailableInLambdaPositionAfterQualifier() throws Exception {
+    configureByFile("/" + getTestName(false) + ".java");
+    assertNotNull(myItems);
+    assertTrue(myItems.length == 0);
+  }
+
+  public void testInferFromRawType() throws Exception {
+    final PsiResolveHelperImpl helper = (PsiResolveHelperImpl)JavaPsiFacade.getInstance(getProject()).getResolveHelper();
+    helper.setTestHelper(new PsiGraphInferenceHelper(getPsiManager()));
+    try {
+      configureByFile("/" + getTestName(false) + ".java");
+      assertNotNull(myItems);
+      assertTrue(myItems.length == 0);
+    }
+    finally {
+      helper.setTestHelper(null);
+    }
+  }
+
   private void doTest() {
     configureByFile("/" + getTestName(false) + ".java");
     assertNotNull(myItems);
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 9d7673d..64798f4 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/GenericsHighlightingTest.java
@@ -332,6 +332,8 @@
   public void testIDEA65377() { doTest5(false); }
   public void testIDEA113526() { doTest5(true); }
   public void testIDEA116493() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
+  public void testIDEA117827() { doTest(LanguageLevel.JDK_1_7, JavaSdkVersion.JDK_1_7, false); }
+  public void testIDEA118037() { 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/Diamond8HighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Diamond8HighlightingTest.java
index 99c7c27..ca4133b 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Diamond8HighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/Diamond8HighlightingTest.java
@@ -16,6 +16,8 @@
 package com.intellij.codeInsight.daemon.lambda;
 
 import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
+import com.intellij.openapi.projectRoots.Sdk;
+import com.intellij.testFramework.IdeaTestUtil;
 import org.jetbrains.annotations.NonNls;
 
 public class Diamond8HighlightingTest extends LightDaemonAnalyzerTestCase {
@@ -25,7 +27,16 @@
     doTest();
   }
 
+  public void testOuterClass() throws Exception {
+    doTest();
+  }
+
   private void doTest() throws Exception {
     doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", false, false);
   }
+
+  @Override
+  protected Sdk getProjectJDK() {
+    return IdeaTestUtil.getMockJdk18();
+  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java
index 964dca8..34ae397 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GenericsHighlighting8Test.java
@@ -44,7 +44,7 @@
 
   @Override
   protected Sdk getProjectJDK() {
-    return getTestName(false).contains("Jdk14") ? IdeaTestUtil.getMockJdk14() : super.getProjectJDK();
+    return IdeaTestUtil.getMockJdk18();
   }
 
   public void testReferenceTypeParams() {
@@ -762,19 +762,4 @@
     doTest();
   }
 
-  public void testJavaUtilCollections_NoVerify() throws Exception {
-    PsiClass collectionsClass = getJavaFacade().findClass("java.util.Collections", GlobalSearchScope.moduleWithLibrariesScope(getModule()));
-    assertNotNull(collectionsClass);
-    collectionsClass = (PsiClass)collectionsClass.getNavigationElement();
-    final String text = collectionsClass.getContainingFile().getText();
-    configureFromFileText("Collections.java", text.replaceAll("\r", "\n"));
-    final PsiResolveHelperImpl helper = (PsiResolveHelperImpl)JavaPsiFacade.getInstance(getProject()).getResolveHelper();
-    helper.setTestHelper(new PsiGraphInferenceHelper(getPsiManager()));
-    try {
-      doTestConfiguredFile(false, false, null);
-    }
-    finally {
-      helper.setTestHelper(null);
-    }
-  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GraphInferenceHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GraphInferenceHighlightingTest.java
index dee9137..d0048b7 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GraphInferenceHighlightingTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/GraphInferenceHighlightingTest.java
@@ -17,6 +17,7 @@
 
 import com.intellij.codeInsight.daemon.LightDaemonAnalyzerTestCase;
 import com.intellij.openapi.projectRoots.JavaSdkVersion;
+import com.intellij.openapi.projectRoots.Sdk;
 import com.intellij.testFramework.IdeaTestUtil;
 import org.jetbrains.annotations.NonNls;
 
@@ -115,4 +116,9 @@
     IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
     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 4a0851a..8e43934 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
@@ -18,6 +18,8 @@
 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;
 
@@ -103,4 +105,9 @@
   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/MethodRefHighlightingTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/daemon/lambda/MethodRefHighlightingTest.java
index c0fed3d..7c25d3b 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
@@ -19,6 +19,7 @@
 import com.intellij.codeInspection.LocalInspectionTool;
 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;
@@ -101,4 +102,9 @@
     IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
     doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", warnings, false);
   }
+
+  @Override
+  protected Sdk getProjectJDK() {
+    return IdeaTestUtil.getMockJdk18();
+  }
 }
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 34a45ee..35b91ef 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
@@ -19,6 +19,7 @@
 import com.intellij.codeInspection.LocalInspectionTool;
 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;
@@ -82,6 +83,18 @@
     doTest();
   }
 
+  public void testArgumentOfAnonymousClass() throws Exception {
+    doTest();
+  }
+
+  public void testEllipsis() throws Exception {
+    doTest();
+  }
+
+  public void testOuterMethodPropagation() throws Exception {
+    doTest();
+  }
+
   private void doTest() {
     doTest(false);
   }
@@ -90,4 +103,9 @@
     IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_8, getModule(), getTestRootDisposable());
     doTestNewInference(BASE_PATH + "/" + getTestName(false) + ".java", warnings, false);
   }
+
+  @Override
+  protected Sdk getProjectJDK() {
+    return IdeaTestUtil.getMockJdk18();
+  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java b/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java
index ae3df00..80d2e4a 100644
--- a/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInsight/javadoc/JavaDocInfoGeneratorTest.java
@@ -72,6 +72,10 @@
     doTestField();
   }
 
+  public void testCode() throws Exception {
+    doTestField();
+  }
+
   public void testEnumConstantOrdinal() throws Exception {
     PsiClass psiClass = getTestClass();
     PsiField field = psiClass.getFields() [0];
diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspection8Test.java b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspection8Test.java
index 0e7d620..0a7b46a 100644
--- a/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspection8Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInspection/DataFlowInspection8Test.java
@@ -45,6 +45,14 @@
     doTest();
   }
 
+  public void testReturnNullInLambdaExpression() throws Exception {
+    doTest();
+  }
+
+  public void testReturnNullInLambdaStatement() throws Exception {
+    doTest();
+  }
+
   private void setupCustomAnnotations() {
     myFixture.addClass("package foo;\n\nimport java.lang.annotation.*;\n\n@Target({ElementType.TYPE_USE}) public @interface Nullable { }");
     myFixture.addClass("package foo;\n\nimport java.lang.annotation.*;\n\n@Target({ElementType.TYPE_USE}) public @interface NotNull { }");
diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/LocalCanBeFinalTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/LocalCanBeFinalTest.java
index e29b65c..61895f6 100644
--- a/java/java-tests/testSrc/com/intellij/codeInspection/LocalCanBeFinalTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInspection/LocalCanBeFinalTest.java
@@ -127,12 +127,14 @@
   public void testForeachNotReported() throws Exception {
     myTool.REPORT_PARAMETERS = true;
     myTool.REPORT_VARIABLES = false;
+    myTool.REPORT_FOREACH_PARAMETERS = false;
     doTest();
   }
 
   public void testNestedForeach() throws Exception {
     myTool.REPORT_PARAMETERS = false;
     myTool.REPORT_VARIABLES = true;
+    myTool.REPORT_FOREACH_PARAMETERS = true;
     doTest();
   }
 
diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java
index 91afe58..ca3065d 100644
--- a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java
+++ b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantCast15Test.java
@@ -50,6 +50,7 @@
   public void testInstanceOfChecks() throws Exception { doTest();}
   public void testForEachValue() throws Exception { doTest();}
   public void testCaseThrowable() throws Exception { doTest();}
+  public void testSafeTempVarName() throws Exception { doTest();}
 
   public void testTypeParameterAccessChecksJava7() throws Exception {
     IdeaTestUtil.setTestVersion(JavaSdkVersion.JDK_1_7, getModule(), getTestRootDisposable());
diff --git a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantTypeArgsInspectionTest.java b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantTypeArgsInspectionTest.java
index 53aba55..c3c092c 100644
--- a/java/java-tests/testSrc/com/intellij/codeInspection/RedundantTypeArgsInspectionTest.java
+++ b/java/java-tests/testSrc/com/intellij/codeInspection/RedundantTypeArgsInspectionTest.java
@@ -37,4 +37,8 @@
   public void testBoundInference() throws Throwable {
     doTest();
   }
+
+  public void testNestedCalls() throws Throwable {
+    doTest();
+  }
 }
\ No newline at end of file
diff --git a/java/java-tests/testSrc/com/intellij/ide/hierarchy/JavaCallHierarchyTest.java b/java/java-tests/testSrc/com/intellij/ide/hierarchy/JavaCallHierarchyTest.java
index aebc9e0..fcdad69 100644
--- a/java/java-tests/testSrc/com/intellij/ide/hierarchy/JavaCallHierarchyTest.java
+++ b/java/java-tests/testSrc/com/intellij/ide/hierarchy/JavaCallHierarchyTest.java
@@ -1,12 +1,15 @@
 package com.intellij.ide.hierarchy;
 
 import com.intellij.JavaTestUtil;
+import com.intellij.ide.hierarchy.actions.BrowseTypeHierarchyAction;
 import com.intellij.ide.hierarchy.call.CallerMethodsTreeStructure;
+import com.intellij.ide.highlighter.XmlFileType;
 import com.intellij.openapi.util.Computable;
 import com.intellij.psi.JavaPsiFacade;
 import com.intellij.psi.PsiClass;
 import com.intellij.psi.PsiMethod;
 import com.intellij.psi.search.ProjectScope;
+import com.intellij.testFramework.TestActionEvent;
 import com.intellij.testFramework.codeInsight.hierarchy.HierarchyViewTestBase;
 
 /**
@@ -53,4 +56,12 @@
   public void testIdeaDev41232() throws Exception {
     doJavaCallTypeHierarchyTest("A", "main", "B.java", "A.java");
   }
+
+  public void testActionAvailableInXml() throws Exception {
+    configureByText(XmlFileType.INSTANCE, "<foo>java.lang.Str<caret>ing</foo>");
+    BrowseTypeHierarchyAction action = new BrowseTypeHierarchyAction();
+    TestActionEvent e = new TestActionEvent(action);
+    action.beforeActionPerformedUpdate(e);
+    assertTrue(e.getPresentation().isEnabled() && e.getPresentation().isVisible());
+  }
 }
diff --git a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerBlankLinesTest.groovy b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerBlankLinesTest.groovy
index b456d41..8f64026 100644
--- a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerBlankLinesTest.groovy
+++ b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerBlankLinesTest.groovy
@@ -24,6 +24,14 @@
  */
 public class JavaRearrangerBlankLinesTest extends AbstractJavaRearrangerTest {
 
+  def classic = [rule(INTERFACE),
+                 rule(CLASS),
+                 rule(FIELD, STATIC),
+                 rule(FIELD, PUBLIC),
+                 rule(FIELD),
+                 rule(METHOD, PUBLIC),
+                 rule(METHOD)]
+
   void testPreserveRelativeBlankLines() {
     commonSettings.BLANK_LINES_AROUND_CLASS = 2
     commonSettings.BLANK_LINES_AROUND_FIELD = 1
@@ -78,13 +86,7 @@
 
   private void method1() {}
 }''',
-      rules: [rule(INTERFACE),
-              rule(CLASS),
-              rule(FIELD, STATIC),
-              rule(FIELD, PUBLIC),
-              rule(FIELD),
-              rule(METHOD, PUBLIC),
-              rule(METHOD)]
+      rules: classic
     )
   }
 
@@ -143,4 +145,64 @@
     doTest(initial: before, expected: before)
   }
 
+
+
+  void "test keep blank lines between fields"() {
+    def text = '''\
+public class Test {
+  private static final Logger LOGGER = LoggerFactory.getLogger(AddCurrentUser.class);
+
+
+  private GlobalQueryService globalQueryService;
+  private EventCoordinationService eventCoordinationService;
+}
+'''
+    doTest(
+      initial: text,
+      expected: text,
+      rules: classic
+    )
+  }
+
+  void "test keep blank lines between fields more fair test"() {
+    doTest(
+      initial: '''\
+public class Test {
+    private static final int t = 12;
+
+
+    public int q = 2;
+    private int e = 3;
+    public int t11 = 23;
+
+    private void test() {
+    }
+
+    public void main() {
+    }
+
+}
+''',
+      expected: '''\
+public class Test {
+    private static final int t = 12;
+
+
+    public int q = 2;
+    public int t11 = 23;
+    private int e = 3;
+
+    public void main() {
+    }
+
+    private void test() {
+    }
+
+}
+''',
+      rules: classic
+    )
+  }
+
+
 }
diff --git a/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerFieldReferenceTest.groovy b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerFieldReferenceTest.groovy
new file mode 100644
index 0000000..a2a996a
--- /dev/null
+++ b/java/java-tests/testSrc/com/intellij/psi/codeStyle/arrangement/JavaRearrangerFieldReferenceTest.groovy
@@ -0,0 +1,256 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.psi.codeStyle.arrangement
+
+import com.intellij.psi.codeStyle.arrangement.match.StdArrangementMatchRule
+
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.EntryType.*;
+import static com.intellij.psi.codeStyle.arrangement.std.StdArrangementTokens.Modifier.*;
+
+class JavaRearrangerFieldReferenceTest extends AbstractJavaRearrangerTest {
+
+  private List<StdArrangementMatchRule> defaultFieldsArrangement = [
+    rule(CLASS),
+    rule(FIELD, PUBLIC),
+    rule(FIELD, PROTECTED),
+    rule(FIELD, PACKAGE_PRIVATE),
+    rule(FIELD, PRIVATE)
+  ]
+
+
+  void "test keep referenced package private field before public one which has reference through binary expression"() {
+    doTest(initial: '''\
+public class TestRunnable {
+    int i = 1;
+    public int j = i + 1;
+    public int k = 3;
+    public int m = 23;
+}
+''',
+           expected: '''\
+public class TestRunnable {
+    public int k = 3;
+    public int m = 23;
+    int i = 1;
+    public int j = i + 1;
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+  void "test keep referenced fields before those who has reference through binary expression"() {
+    doTest(initial: '''\
+public class javaTest {
+    int i1 = 1;
+    protected int i2 = i1 + 4;
+}
+''',
+           expected: '''\
+public class javaTest {
+    int i1 = 1;
+    protected int i2 = i1 + 4;
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+  void "test keep referenced static fields before those who has reference through binary expression"() {
+    doTest(initial: '''\
+public class CodeFormatTest {
+        private static String PREFIX = "prefix.";
+        public static String NAME = PREFIX + "name";
+        private static String PRIVATE_NAME = PREFIX + "private name";
+        public static String TEST = "OK!";
+        public static String BOOK = "ATLAS";
+}
+''',
+            expected: '''\
+public class CodeFormatTest {
+        public static String TEST = "OK!";
+        public static String BOOK = "ATLAS";
+        private static String PREFIX = "prefix.";
+        private static String PRIVATE_NAME = PREFIX + "private name";
+        public static String NAME = PREFIX + "name";
+}
+''',
+            rules: defaultFieldsArrangement
+    );
+  }
+
+  void "test keep referenced static fields before those who has direct reference"() {
+    doTest(initial: '''\
+public class CodeFormatTest {
+        private static String PREFIX = "prefix.";
+        public static String NAME = PREFIX;
+}
+''',
+            expected: '''\
+public class CodeFormatTest {
+        private static String PREFIX = "prefix.";
+        public static String NAME = PREFIX;
+}
+''',
+            rules: defaultFieldsArrangement
+    );
+  }
+
+  void "test keep referenced fields before those who has direct reference"() {
+    doTest(initial: '''\
+public class CodeFormatTest {
+        private String PREFIX = "prefix.";
+        public String NAME = PREFIX;
+}
+''',
+           expected: '''\
+public class CodeFormatTest {
+        private String PREFIX = "prefix.";
+        public String NAME = PREFIX;
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+  void "test keep referenced fields before those who has reference through polyadic expression"() {
+    doTest(initial: '''\
+public class CodeFormatTest {
+        private String PREFIX = "prefix.";
+        public String NAME = "ololo" + "bobob" + "line" + PREFIX + "ququ";
+}
+''',
+           expected: '''\
+public class CodeFormatTest {
+        private String PREFIX = "prefix.";
+        public String NAME = "ololo" + "bobob" + "line" + PREFIX + "ququ";
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+  void "test keep referenced field before who has reference through parenthesized nested binary expression"() {
+    doTest(initial: '''\
+public class TestRunnable {
+    int i = 3;
+    public int j = (1 + i);
+}
+''',
+           expected: '''\
+public class TestRunnable {
+    int i = 3;
+    public int j = (1 + i);
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+
+
+  void "test keep referenced fields before those who has reference through nested binary expression"() {
+    doTest(initial: '''\
+public class TestRunnable {
+    int i = 3;
+    public int j = (1 + 2 + (5 + (5 + (5 + i))) + (1 + (i + 1)) + (3 + i) + 5) + 4;
+}
+''',
+           expected: '''\
+public class TestRunnable {
+    int i = 3;
+    public int j = (1 + 2 + (5 + (5 + (5 + i))) + (1 + (i + 1)) + (3 + i) + 5) + 4;
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+
+  void "test multiple references on instance fields"() {
+    doTest(initial: '''\
+public class TestRunnable {
+    int i = 3;
+    int k = 12;
+    public int j = (1 + 2 + (5 + (5 + (5 + i))) + (1 + (i + 1 + k)) + (3 + i) + 5) + 4;
+    public int q = 64;
+}
+''',
+           expected: '''\
+public class TestRunnable {
+    public int q = 64;
+    int i = 3;
+    int k = 12;
+    public int j = (1 + 2 + (5 + (5 + (5 + i))) + (1 + (i + 1 + k)) + (3 + i) + 5) + 4;
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+
+  void "test field initializer has reference to method"() {
+    doTest(initial: '''\
+public class TestRunnable {
+    public int foo() {
+        return 15;
+    }
+
+    public int q = 64 + foo();
+    int i = 3;
+    int k = 12;
+}
+''',
+           expected: '''\
+public class TestRunnable {
+    public int q = 64 + foo();
+    int i = 3;
+    int k = 12;
+
+    public int foo() {
+        return 15;
+    }
+}
+''',
+           rules: [rule(CLASS),
+                   rule(FIELD, PUBLIC),
+                   rule(FIELD, PACKAGE_PRIVATE),
+                   rule(METHOD, PUBLIC)]
+    )
+  }
+
+  void "test illegal field reference arranged to legal"() {
+    doTest(initial: '''\
+public class Alfa {
+    int i = 3;
+    public int j = i + 1 + q;
+    int q = 2 + 3;
+    public int r = 3;
+}
+''',
+           expected: '''\
+public class Alfa {
+    public int r = 3;
+    int i = 3;
+    int q = 2 + 3;
+    public int j = i + 1 + q;
+}
+''',
+           rules: defaultFieldsArrangement
+    );
+  }
+
+}
diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java
index 7355feb..ed79f2f 100644
--- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java
+++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterInEditorTest.java
@@ -97,6 +97,39 @@
     doTest(before, after);
   }
 
+  public void testCaretLineAndPositionPreserved_WhenBracketOnNextLineWillBeFormatted() throws IOException {
+    String before = "public class Test {\n" +
+                    "        int a;\n" +
+                    "    \n" +
+                    "    public static void main(String[] args) {\n" +
+                    "                     <caret>\n" +
+                    "            }\n" +
+                    "\n" +
+                    "    static final long j = 2;\n" +
+                    "}";
+    String after = "public class Test {\n" +
+                   "    int a;\n" +
+                   "\n" +
+                   "    public static void main(String[] args) {\n" +
+                   "                     <caret>\n" +
+                   "    }\n" +
+                   "\n" +
+                   "    static final long j = 2;\n" +
+                   "}";
+    doTest(before, after);
+
+    before = "public class Test {\n" +
+             "        int a;\n" +
+             "    \n" +
+             "    public static void main(String[] args) {\n" +
+             "                     <caret>           \n" +
+             "                }\n" +
+             "\n" +
+             "    static final long j = 2;\n" +
+             "}";
+    doTest(before, after);
+  }
+
   public void doTest(@NotNull String before, @NotNull String after) throws IOException {
     configureFromFileText(getTestName(false) + ".java", before);
     CodeStyleManager.getInstance(getProject()).reformatText(getFile(), 0, getEditor().getDocument().getTextLength());
diff --git a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java
index 4cedbc3..8adb06b 100644
--- a/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java
+++ b/java/java-tests/testSrc/com/intellij/psi/formatter/java/JavaFormatterTest.java
@@ -3004,6 +3004,7 @@
 
   public void testFormatterOnOffTags() throws Exception {
     getSettings().getRootSettings().FORMATTER_TAGS_ENABLED = true;
+    getSettings().IF_BRACE_FORCE = CommonCodeStyleSettings.FORCE_BRACES_ALWAYS;
     doTest();
   }
 
diff --git a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java
index 36b1c4c..788febf 100644
--- a/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java
+++ b/java/java-tests/testSrc/com/intellij/psi/resolve/ResolveMethod15Test.java
@@ -7,7 +7,6 @@
 import org.jetbrains.annotations.NonNls;
 import static org.junit.Assert.assertThat;
 import static org.hamcrest.core.IsInstanceOf.instanceOf;
-import static org.junit.Assert.assertTrue;
 
 /**
  * @author dsl
@@ -129,6 +128,16 @@
     assertTrue(containingClass != null ? containingClass.getName() : null, containingClass instanceof PsiAnonymousClass);
   }
 
+  public void testCovariantReturnTypeAnonymous() throws Exception {
+    final PsiReference ref = configureByFile();
+    assertThat(ref, instanceOf(PsiReferenceExpression.class));
+    final PsiReferenceExpression refExpr = (PsiReferenceExpression)ref;
+    final PsiElement resolve = refExpr.resolve();
+    assertTrue(resolve != null ? resolve.toString() : null, resolve instanceof PsiMethod);
+    final PsiClass containingClass = ((PsiMethod)resolve).getContainingClass();
+    assertTrue(containingClass != null ? containingClass.getName() : null, !(containingClass instanceof PsiAnonymousClass));
+  }
+
   public void testFilterFixedVsVarargs1() throws Exception {
     final PsiReference ref = configureByFile();
     assertThat(ref, instanceOf(PsiReferenceExpression.class));
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java
index 07f3a61..35560bf 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/IntroduceVariableTest.java
@@ -78,6 +78,22 @@
     doTest(new MockIntroduceVariableHandler("j", true, false, false, "int"));
   }
 
+  public void testAnonymousClass3() throws Exception {
+    doTest(new MockIntroduceVariableHandler("j", true, false, false, "Foo"));
+  }
+
+  public void testAnonymousClass4() throws Exception {
+    doTest(new MockIntroduceVariableHandler("j", true, false, false, "int"));
+  }
+
+  public void testAnonymousClass5() throws Exception {
+    doTest(new MockIntroduceVariableHandler("j", true, false, false, "int"));
+  }
+
+  public void testLambda() throws Exception {
+    doTest(new MockIntroduceVariableHandler("j", true, false, false, "int"));
+  }
+
   public void testParenthized() throws Exception {
     doTest(new MockIntroduceVariableHandler("temp", true, false, false, "int"));
   }
@@ -208,6 +224,18 @@
     doTest(new MockIntroduceVariableHandler("str", false, false, false, "java.lang.String"));
   }
 
+  public void testSubLiteralFailure() throws Exception {
+    try {
+      doTest(new MockIntroduceVariableHandler("str", false, false, false, "int"));
+    }
+    catch (Exception e) {
+      assertEquals(e.getMessage(), "Error message:Cannot perform refactoring.\n" +
+                                   "Selected block should represent an expression");
+      return;
+    }
+    fail("Should not be able to perform refactoring");
+  }
+
   public void testSubLiteralFromExpression() throws Exception {
     doTest(new MockIntroduceVariableHandler("str", false, false, false, "java.lang.String"));
   }
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java
index aa539bd..cbf0955 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/PullUpTest.java
@@ -147,6 +147,10 @@
     doTest(false, new RefactoringTestUtil.MemberDescriptor("foo", PsiMethod.class));
   }
 
+  public void testPublicMethodFromPrivateClassConflict() {
+    doTest(false, new RefactoringTestUtil.MemberDescriptor("HM", PsiClass.class), new RefactoringTestUtil.MemberDescriptor("foo", PsiMethod.class));
+  }
+
   private void doTest(RefactoringTestUtil.MemberDescriptor... membersToFind) {
     doTest(true, membersToFind);
   }
diff --git a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineParameterTest.java b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineParameterTest.java
index 29d85f1..b49a306 100644
--- a/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineParameterTest.java
+++ b/java/java-tests/testSrc/com/intellij/refactoring/inline/InlineParameterTest.java
@@ -134,6 +134,10 @@
     doTest(true);
   }
 
+  public void testFromClassInitializer() throws Exception {
+    doTest(false);
+  }
+
   public void testParameterWithWriteAccess() throws Exception {
     try {
       doTest(false);
diff --git a/java/mockJDK-1.7/jre/lib/rt.jar b/java/mockJDK-1.7/jre/lib/rt.jar
index 3a3995e..83d8440 100644
--- a/java/mockJDK-1.7/jre/lib/rt.jar
+++ b/java/mockJDK-1.7/jre/lib/rt.jar
Binary files differ
diff --git a/java/mockJDK-1.8/jre/lib/rt.jar b/java/mockJDK-1.8/jre/lib/rt.jar
new file mode 100644
index 0000000..db566fc
--- /dev/null
+++ b/java/mockJDK-1.8/jre/lib/rt.jar
Binary files differ
diff --git a/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java b/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java
index eb378f1..e0a2806 100644
--- a/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java
+++ b/java/testFramework/src/com/intellij/testFramework/IdeaTestUtil.java
@@ -77,6 +77,10 @@
     return JavaSdk.getInstance().createJdk(name, getMockJdk17Path().getPath(), false);
   }
 
+  public static Sdk getMockJdk18() {
+    return JavaSdk.getInstance().createJdk("java 1.8", getMockJdk18Path().getPath(), false);
+  }
+
   public static Sdk getMockJdk14() {
     return JavaSdk.getInstance().createJdk("java 1.4", getMockJdk14Path().getPath(), false);
   }
@@ -89,6 +93,10 @@
     return getPathForJdkNamed("mockJDK-1.7");
   }
 
+  public static File getMockJdk18Path() {
+    return getPathForJdkNamed("mockJDK-1.8");
+  }
+
   private static File getPathForJdkNamed(String name) {
     File mockJdkCEPath = new File(PathManager.getHomePath(), "java/" + name);
     return mockJdkCEPath.exists() ? mockJdkCEPath : new File(PathManager.getHomePath(), "community/java/" + name);
@@ -130,4 +138,6 @@
       }
     });
   }
+
+  
 }
diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java b/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java
index 078e1fb..0ec56d9 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/builders/impl/BuildRootIndexImpl.java
@@ -19,7 +19,6 @@
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.io.FileUtilRt;
 import com.intellij.util.SmartList;
-import com.intellij.util.containers.ConcurrentHashMap;
 import gnu.trove.THashMap;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -37,6 +36,7 @@
 import java.io.File;
 import java.io.FileFilter;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
 /**
@@ -55,7 +55,7 @@
     myIgnoredFileIndex = ignoredFileIndex;
     myRootsByTarget = new HashMap<BuildTarget<?>, List<? extends BuildRootDescriptor>>();
     myRootToDescriptors = new THashMap<File, List<BuildRootDescriptor>>(FileUtil.FILE_HASHING_STRATEGY);
-    myFileFilters = new ConcurrentHashMap<BuildRootDescriptor, FileFilter>();
+    myFileFilters = new ConcurrentHashMap<BuildRootDescriptor, FileFilter>(16, 0.75f, 1);
     final Iterable<AdditionalRootsProviderService> rootsProviders = JpsServiceManager.getInstance().getExtensions(AdditionalRootsProviderService.class);
     for (BuildTargetType<?> targetType : TargetTypeRegistry.getInstance().getTargetTypes()) {
       for (BuildTarget<?> target : targetIndex.getAllTargets(targetType)) {
diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/java/JavaBuilderUtil.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/JavaBuilderUtil.java
index b6c282c..24ef26e 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/builders/java/JavaBuilderUtil.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/JavaBuilderUtil.java
@@ -114,7 +114,6 @@
           if (incremental) {
             final Set<File> newlyAffectedFiles = new HashSet<File>(allAffectedFiles);
             newlyAffectedFiles.removeAll(affectedBeforeDif);
-            newlyAffectedFiles.removeAll(allCompiledFiles); // the diff operation may have affected the class already compiled in thic compilation round
 
             final String infoMessage = "Dependency analysis found " + newlyAffectedFiles.size() + " affected files";
             LOG.info(infoMessage);
diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java
index fdc84ab..154d5da 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/ClassRepr.java
@@ -321,15 +321,17 @@
   }
 
   public String getPackageName() {
-    return getPackageName(name);
+    final String strValue = myContext.getValue(name);
+    return strValue != null? getPackageName(strValue) : null;
   }
 
-  public String getPackageName(final int s) {
-    return getPackageName(myContext.getValue(s));
+  public String getShortName() {
+    final String strValue = myContext.getValue(name);
+    return strValue != null? getShortName(strValue) : null;
   }
 
   @NotNull
-  public static String getPackageName(final String raw) {
+  public static String getPackageName(@NotNull final String raw) {
     final int index = raw.lastIndexOf('/');
 
     if (index == -1) {
@@ -339,6 +341,17 @@
     return raw.substring(0, index);
   }
 
+  @NotNull
+  public static String getShortName(@NotNull final String fqName) {
+    final int index = fqName.lastIndexOf('/');
+
+    if (index == -1) {
+      return fqName;
+    }
+
+    return fqName.substring(index + 1);
+  }
+
   @Nullable
   public FieldRepr findField(final int name) {
     for (FieldRepr f : myFields) {
diff --git a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java
index 29c92aa..553c60f 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/builders/java/dependencyView/Mappings.java
@@ -45,6 +45,7 @@
 
   private final static String CLASS_TO_SUBCLASSES = "classToSubclasses.tab";
   private final static String CLASS_TO_CLASS = "classToClass.tab";
+  private final static String SHORT_NAMES = "shortNames.tab";
   private final static String SOURCE_TO_CLASS = "sourceToClass.tab";
   private final static String CLASS_TO_SOURCE = "classToSource.tab";
   private static final IntInlineKeyDescriptor INT_KEY_DESCRIPTOR = new IntInlineKeyDescriptor();
@@ -65,6 +66,7 @@
   private final TIntHashSet myChangedClasses;
   private final THashSet<File> myChangedFiles;
   private final Set<ClassRepr> myDeletedClasses;
+  private final Set<ClassRepr> myAddedClasses;
   private final Object myLock;
   private final File myRootDir;
 
@@ -83,6 +85,10 @@
   private IntIntMultiMaplet myClassToClassDependency;
   private ObjectObjectMultiMaplet<File, ClassRepr> mySourceFileToClasses;
   private IntObjectMaplet<File> myClassToSourceFile;
+  /**
+   * [short className] -> list of FQ names
+   */
+  private IntIntMultiMaplet myShortClassNameIndex;
 
   private IntIntTransientMultiMaplet myRemovedSuperClasses;
   private IntIntTransientMultiMaplet myAddedSuperClasses;
@@ -96,6 +102,7 @@
     myChangedClasses = new TIntHashSet(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
     myChangedFiles = new THashSet(FileUtil.FILE_HASHING_STRATEGY);
     myDeletedClasses = new HashSet<ClassRepr>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
+    myAddedClasses = new HashSet<ClassRepr>(DEFAULT_SET_CAPACITY, DEFAULT_SET_LOAD_FACTOR);
     myDeltaIsTransient = base.myDeltaIsTransient;
     myRootDir = new File(FileUtil.toSystemIndependentName(base.myRootDir.getAbsolutePath()) + File.separatorChar + "myDelta");
     myContext = base.myContext;
@@ -112,6 +119,7 @@
     myChangedClasses = null;
     myChangedFiles = null;
     myDeletedClasses = null;
+    myAddedClasses = null;
     myDeltaIsTransient = transientDelta;
     myRootDir = rootDir;
     createImplementation();
@@ -132,6 +140,7 @@
     if (myIsDelta && myDeltaIsTransient) {
       myClassToSubclasses = new IntIntTransientMultiMaplet();
       myClassToClassDependency = new IntIntTransientMultiMaplet();
+      myShortClassNameIndex = null;
       mySourceFileToClasses = new ObjectObjectTransientMultiMaplet<File, ClassRepr>(FileUtil.FILE_HASHING_STRATEGY, ourClassSetConstructor);
       myClassToSourceFile = new IntObjectTransientMaplet<File>();
     }
@@ -141,6 +150,7 @@
       }
       myClassToSubclasses = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_SUBCLASSES), INT_KEY_DESCRIPTOR);
       myClassToClassDependency = new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, CLASS_TO_CLASS), INT_KEY_DESCRIPTOR);
+      myShortClassNameIndex = myIsDelta? null : new IntIntPersistentMultiMaplet(DependencyContext.getTableFile(myRootDir, SHORT_NAMES), INT_KEY_DESCRIPTOR);
       mySourceFileToClasses = new ObjectObjectPersistentMultiMaplet<File, ClassRepr>(
         DependencyContext.getTableFile(myRootDir, SOURCE_TO_CLASS), new FileKeyDescriptor(), ClassRepr.externalizer(myContext),
         ourClassSetConstructor
@@ -534,7 +544,7 @@
       }
     }
 
-    void affectSubclasses(final int className, final Collection<File> affectedFiles, final Collection<UsageRepr.Usage> affectedUsages, final TIntHashSet dependants, final boolean usages) {
+    void affectSubclasses(final int className, final Collection<File> affectedFiles, final Collection<UsageRepr.Usage> affectedUsages, final TIntHashSet dependants, final boolean usages, final Collection<File> alreadyCompiledFiles) {
       debug("Affecting subclasses of class: ", className);
 
       final File fileName = myClassToSourceFile.get(className);
@@ -560,14 +570,16 @@
       if (depClasses != null) {
         addAll(dependants, depClasses);
       }
-      affectedFiles.add(fileName);
+      if (!alreadyCompiledFiles.contains(fileName)) {
+        affectedFiles.add(fileName);
+      }
 
       final TIntHashSet directSubclasses = myClassToSubclasses.get(className);
       if (directSubclasses != null) {
         directSubclasses.forEach(new TIntProcedure() {
           @Override
           public boolean execute(int subClass) {
-            affectSubclasses(subClass, affectedFiles, affectedUsages, dependants, usages);
+            affectSubclasses(subClass, affectedFiles, affectedUsages, dependants, usages, alreadyCompiledFiles);
             return true;
           }
         });
@@ -729,7 +741,7 @@
     return acc;
   }
 
-  private boolean incrementalDecision(final int owner, final Proto member, final Collection<File> affectedFiles, @Nullable final DependentFilesFilter filter) {
+  private boolean incrementalDecision(final int owner, final Proto member, final Collection<File> affectedFiles, final Collection<File> currentlyCompiled, @Nullable final DependentFilesFilter filter) {
     final boolean isField = member instanceof FieldRepr;
     final Util self = new Util();
 
@@ -749,7 +761,7 @@
         @Override
         public boolean execute(int className) {
           final File fileName = myClassToSourceFile.get(className);
-          if (fileName != null) {
+          if (fileName != null && !currentlyCompiled.contains(fileName)) {
             debug("Adding ", fileName);
             affectedFiles.add(fileName);
           }
@@ -768,7 +780,7 @@
       @Override
       public boolean execute(int className, File fileName) {
         if (ClassRepr.getPackageName(myContext.getValue(className)).equals(packageName)) {
-          if (filter == null || filter.accept(fileName)) {
+          if ((filter == null || filter.accept(fileName)) && !currentlyCompiled.contains(fileName)) {
             debug("Adding: ", fileName);
             affectedFiles.add(fileName);
           }
@@ -871,7 +883,7 @@
                 debug("Constant search service not available.");
               }
               debug("Trying to soften non-incremental decision.");
-              if (!incrementalDecision(t.owner, t.field, affectedFiles, myFilter)) {
+              if (!incrementalDecision(t.owner, t.field, affectedFiles, myFilesToCompile, myFilter)) {
                 debug("No luck.");
                 debug("End of delayed work, returning false.");
                 return false;
@@ -1018,7 +1030,7 @@
         debug("Method: ", m.name);
         if (it.isInterface() || it.isAbstract() || m.isAbstract()) {
           debug("Class is abstract, or is interface, or added method in abstract => affecting all subclasses");
-          myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false);
+          myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles);
         }
 
         TIntHashSet propagated = null;
@@ -1105,26 +1117,23 @@
           }
 
           final TIntHashSet subClasses = getAllSubclasses(it.name);
-
-          if (subClasses != null) {
-            subClasses.forEach(new TIntProcedure() {
-              @Override
-              public boolean execute(int subClass) {
-                final ClassRepr r = myFuture.reprByName(subClass);
-                if (r != null) {
-                  final File sourceFileName = myClassToSourceFile.get(subClass);
-                  if (sourceFileName != null) {
-                    final int outerClass = r.getOuterClassName();
-                    if (!isEmpty(outerClass) && myFuture.isMethodVisible(outerClass, m)) {
-                      myAffectedFiles.add(sourceFileName);
-                      debug("Affecting file due to local overriding: ", sourceFileName);
-                    }
+          subClasses.forEach(new TIntProcedure() {
+            @Override
+            public boolean execute(int subClass) {
+              final ClassRepr r = myFuture.reprByName(subClass);
+              if (r != null) {
+                final File sourceFileName = myClassToSourceFile.get(subClass);
+                if (sourceFileName != null && !myCompiledFiles.contains(sourceFileName)) {
+                  final int outerClass = r.getOuterClassName();
+                  if (!isEmpty(outerClass) && myFuture.isMethodVisible(outerClass, m)) {
+                    myAffectedFiles.add(sourceFileName);
+                    debug("Affecting file due to local overriding: ", sourceFileName);
                   }
                 }
-                return true;
               }
-            });
-          }
+              return true;
+            }
+          });
         }
       }
       debug("End of added methods processing");
@@ -1215,9 +1224,9 @@
                   if (allAbstract && visited) {
                     final File source = myClassToSourceFile.get(p);
 
-                    if (source != null) {
+                    if (source != null && !myCompiledFiles.contains(source)) {
                       myAffectedFiles.add(source);
-                      debug("Removed method is not abstract & overrides some abstract method which is not then over-overriden in subclass ", p);
+                      debug("Removed method is not abstract & overrides some abstract method which is not then over-overridden in subclass ", p);
                       debug("Affecting subclass source file ", source);
                     }
                   }
@@ -1310,7 +1319,7 @@
 
               if ((d.addedModifiers() & Opcodes.ACC_STATIC) > 0) {
                 debug("Added static specifier --- affecting subclasses");
-                myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false);
+                myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles);
               }
             }
             else {
@@ -1318,7 +1327,7 @@
                   (d.addedModifiers() & Opcodes.ACC_PUBLIC) > 0 ||
                   (d.addedModifiers() & Opcodes.ACC_ABSTRACT) > 0) {
                 debug("Added final, public or abstract specifier --- affecting subclasses");
-                myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false);
+                myFuture.affectSubclasses(it.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, false, myCompiledFiles);
               }
 
               if ((d.addedModifiers() & Opcodes.ACC_PROTECTED) > 0 && !((d.removedModifiers() & Opcodes.ACC_PRIVATE) > 0)) {
@@ -1359,7 +1368,7 @@
               final ClassRepr r = myFuture.reprByName(subClass);
               if (r != null) {
                 final File sourceFileName = myClassToSourceFile.get(subClass);
-                if (sourceFileName != null) {
+                if (sourceFileName != null && !myCompiledFiles.contains(sourceFileName)) {
                   if (r.isLocal()) {
                     debug("Affecting local subclass (introduced field can potentially hide surrounding method parameters/local variables): ", sourceFileName);
                     myAffectedFiles.add(sourceFileName);
@@ -1451,7 +1460,7 @@
             myDelayedWorks.addConstantWork(it.name, f, true, false);
           }
           else {
-            if (!incrementalDecision(it.name, f, myAffectedFiles, myFilter)) {
+            if (!incrementalDecision(it.name, f, myAffectedFiles, myFilesToCompile, myFilter)) {
               debug("End of Differentiate, returning false");
               return false;
             }
@@ -1491,7 +1500,7 @@
               myDelayedWorks.addConstantWork(it.name, field, false, accessChanged);
             }
             else {
-              if (!incrementalDecision(it.name, field, myAffectedFiles, myFilter)) {
+              if (!incrementalDecision(it.name, field, myAffectedFiles, myFilesToCompile, myFilter)) {
                 debug("End of Differentiate, returning false");
                 return false;
               }
@@ -1608,7 +1617,7 @@
             debug("Extends changed: ", extendsChanged);
             debug("Interfaces removed: ", interfacesRemoved);
 
-            myFuture.affectSubclasses(changedClass.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, extendsChanged || interfacesRemoved || signatureChanged);
+            myFuture.affectSubclasses(changedClass.name, myAffectedFiles, state.myAffectedUsages, state.myDependants, extendsChanged || interfacesRemoved || signatureChanged, myCompiledFiles);
 
             if (!changedClass.isAnonymous()) {
               final TIntHashSet parents = new TIntHashSet();
@@ -1642,7 +1651,7 @@
 
           if (changedClass.isAnnotation() && changedClass.getRetentionPolicy() == RetentionPolicy.SOURCE) {
             debug("Annotation, retention policy = SOURCE => a switch to non-incremental mode requested");
-            if (!incrementalDecision(changedClass.getOuterClassName(), changedClass, myAffectedFiles, myFilter)) {
+            if (!incrementalDecision(changedClass.getOuterClassName(), changedClass, myAffectedFiles, myFilesToCompile, myFilter)) {
               debug("End of Differentiate, returning false");
               return false;
             }
@@ -1686,7 +1695,7 @@
 
               if (removedtargets.contains(ElemType.LOCAL_VARIABLE)) {
                 debug("Removed target contains LOCAL_VARIABLE => a switch to non-incremental mode requested");
-                if (!incrementalDecision(changedClass.getOuterClassName(), changedClass, myAffectedFiles, myFilter)) {
+                if (!incrementalDecision(changedClass.getOuterClassName(), changedClass, myAffectedFiles, myFilesToCompile, myFilter)) {
                   debug("End of Differentiate, returning false");
                   return false;
                 }
@@ -1778,7 +1787,6 @@
               debug("Scheduling for recompilation duplicated sources: ", currentlyMappedTo.getPath() + "; " + srcFile.getPath());
               myAffectedFiles.add(currentlyMappedTo);
               myAffectedFiles.add(srcFile);
-              myCompiledFiles.remove(srcFile); // this will force sending the file to compilation again
               return; // do not process this file because it should not be integrated
             }
             break;
@@ -1788,36 +1796,51 @@
 
       for (final ClassRepr c : addedClasses) {
         debug("Class name: ", c.name);
-        myDelta.addChangedClass(c.name);
+        myDelta.addAddedClass(c);
 
         for (final int sup : c.getSupers()) {
           myDelta.registerAddedSuperClass(c.name, sup);
         }
 
-        if (!myEasyMode) {
-          final TIntHashSet depClasses = myClassToClassDependency.get(c.name);
-
-          if (depClasses != null) {
-            depClasses.forEach(new TIntProcedure() {
-              @Override
-              public boolean execute(int depClass) {
-                final File fName = myClassToSourceFile.get(depClass);
-                if (fName != null) {
-                  if (myFilter == null || myFilter.accept(fName)) {
-                    debug("Adding dependent file ", fName);
-                    myAffectedFiles.add(fName);
-                  }
-                }
-                return true;
-              }
-            });
+        if (!myEasyMode && !c.isAnonymous() && !c.isLocal()) {
+          final TIntHashSet toAffect = new TIntHashSet();
+          toAffect.add(c.name);
+          final TIntHashSet classes = myShortClassNameIndex.get(myContext.get(c.getShortName()));
+          if (classes != null) {
+            // affecting dependencies on all other classes with the same short name
+            toAffect.addAll(classes.toArray());
           }
+          toAffect.forEach(new TIntProcedure() {
+            public boolean execute(int qName) {
+              final TIntHashSet depClasses = myClassToClassDependency.get(qName);
+              if (depClasses != null) {
+                affectCorrespondingSourceFiles(depClasses);
+              }
+              return true;
+            }
+          });
         }
       }
 
       debug("End of added classes processing.");
     }
 
+    private void affectCorrespondingSourceFiles(TIntHashSet toAffect) {
+      toAffect.forEach(new TIntProcedure() {
+        @Override
+        public boolean execute(int depClass) {
+          final File fName = myClassToSourceFile.get(depClass);
+          if (fName != null) {
+            if (myFilter == null || myFilter.accept(fName)) {
+              debug("Adding dependent file ", fName);
+              myAffectedFiles.add(fName);
+            }
+          }
+          return true;
+        }
+      });
+    }
+
     private void calculateAffectedFiles(final DiffState state) {
       debug("Checking dependent classes:");
 
@@ -1979,10 +2002,7 @@
     }
   }
 
-  private void cleanupRemovedClass(final Mappings delta,
-                                   @NotNull final ClassRepr cr,
-                                   final Set<UsageRepr.Usage> usages,
-                                   final IntIntMultiMaplet dependenciesTrashBin) {
+  private void cleanupRemovedClass(final Mappings delta, @NotNull final ClassRepr cr, final Set<UsageRepr.Usage> usages, final IntIntMultiMaplet dependenciesTrashBin) {
     final int className = cr.name;
 
     for (final int superSomething : cr.getSupers()) {
@@ -1994,6 +2014,9 @@
     myClassToClassDependency.remove(className);
     myClassToSubclasses.remove(className);
     myClassToSourceFile.remove(className);
+    if (!cr.isLocal() && !cr.isAnonymous()) {
+      myShortClassNameIndex.removeFrom(myContext.get(cr.getShortName()), className);
+    }
   }
 
   public void integrate(final Mappings delta) {
@@ -2025,6 +2048,11 @@
           for (final ClassRepr repr : delta.getDeletedClasses()) {
             cleanupRemovedClass(delta, repr, repr.getUsages(), dependenciesTrashBin);
           }
+          for (ClassRepr repr : delta.getAddedClasses()) {
+            if (!repr.isAnonymous() && !repr.isLocal()) {
+              myShortClassNameIndex.put(myContext.get(repr.getShortName()), repr.name);
+            }
+          }
 
           final TIntHashSet superClasses = new TIntHashSet();
           final IntIntTransientMultiMaplet addedSuperClasses = delta.getAddedSuperClasses();
@@ -2090,6 +2118,16 @@
           myClassToSubclasses.putAll(delta.myClassToSubclasses);
           myClassToSourceFile.putAll(delta.myClassToSourceFile);
           mySourceFileToClasses.replaceAll(delta.mySourceFileToClasses);
+          delta.mySourceFileToClasses.forEachEntry(new TObjectObjectProcedure<File, Collection<ClassRepr>>() {
+            public boolean execute(File src, Collection<ClassRepr> classes) {
+              for (ClassRepr repr : classes) {
+                if (!repr.isAnonymous() && !repr.isLocal()) {
+                  myShortClassNameIndex.put(myContext.get(repr.getShortName()), repr.name);
+                }
+              }
+              return true;
+            }
+          });
         }
 
         // updating classToClass dependencies
@@ -2224,6 +2262,7 @@
       myClassToSourceFile.close();
 
       if (!myIsDelta) {
+        myShortClassNameIndex.close();
         // only close if you own the context
         final DependencyContext context = myContext;
         if (context != null) {
@@ -2247,6 +2286,7 @@
       myClassToSourceFile.flush(memoryCachesOnly);
 
       if (!myIsDelta) {
+        myShortClassNameIndex.flush(memoryCachesOnly);
         // flush if you own the context
         final DependencyContext context = myContext;
         if (context != null) {
@@ -2312,6 +2352,14 @@
     addChangedClass(cr.name);
   }
 
+  private void addAddedClass(final ClassRepr cr) {
+    assert (myAddedClasses != null);
+
+    myAddedClasses.add(cr);
+
+    addChangedClass(cr.name);
+  }
+
   private void addChangedClass(final int it) {
     assert (myChangedClasses != null && myChangedFiles != null);
     myChangedClasses.add(it);
@@ -2328,6 +2376,11 @@
     return myDeletedClasses == null ? Collections.<ClassRepr>emptySet() : Collections.unmodifiableSet(myDeletedClasses);
   }
 
+  @NotNull
+  private Set<ClassRepr> getAddedClasses() {
+    return myAddedClasses == null ? Collections.<ClassRepr>emptySet() : Collections.unmodifiableSet(myAddedClasses);
+  }
+
   private TIntHashSet getChangedClasses() {
     return myChangedClasses;
   }
@@ -2390,6 +2443,7 @@
       myClassToClassDependency,
       mySourceFileToClasses,
       myClassToSourceFile,
+      myShortClassNameIndex
     };
 
     final String[] info = {
@@ -2397,6 +2451,7 @@
       "ClassToClassDependency",
       "SourceFileToClasses",
       "ClassToSourceFile",
+      "ShortClassNameIndex"
     };
 
     for (int i = 0; i < data.length; i++) {
diff --git a/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java b/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java
index d6b428d..0d5f03f 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/client/ProtobufClientMessageHandler.java
@@ -34,7 +34,7 @@
 */
 @ChannelHandler.Sharable
 final class ProtobufClientMessageHandler<T extends ProtobufResponseHandler> extends SimpleChannelInboundHandler<MessageLite> {
-  private final ConcurrentHashMap<UUID, RequestFuture<T>> myHandlers = new ConcurrentHashMap<UUID, RequestFuture<T>>();
+  private final ConcurrentHashMap<UUID, RequestFuture<T>> myHandlers = new ConcurrentHashMap<UUID, RequestFuture<T>>(16, 0.75f, 1);
   @NotNull
   private final UUIDGetter myUuidGetter;
   private final SimpleProtobufClient myClient;
diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
index 24cbd84..522e1c5 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/IncProjectBuilder.java
@@ -85,9 +85,10 @@
   static {
     int maxThreads = Math.min(6, Runtime.getRuntime().availableProcessors() - 1);
     try {
-      maxThreads = Math.max(2, Integer.parseInt(System.getProperty(GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION, Integer.toString(maxThreads))));
+      maxThreads = Math.max(1, Integer.parseInt(System.getProperty(GlobalOptions.COMPILE_PARALLEL_MAX_THREADS_OPTION, Integer.toString(maxThreads))));
     }
     catch (NumberFormatException ignored) {
+      maxThreads = Math.max(1, maxThreads);
     }
     MAX_BUILDER_THREADS = maxThreads;
   }
@@ -568,7 +569,7 @@
 
   private void buildChunks(final CompileContextImpl context) throws ProjectBuildException {
     try {
-      if (BuildRunner.PARALLEL_BUILD_ENABLED) {
+      if (BuildRunner.PARALLEL_BUILD_ENABLED && MAX_BUILDER_THREADS > 1) {
         new BuildParallelizer(context).buildInParallel();
       }
       else {
@@ -632,9 +633,7 @@
   }
 
   private class BuildParallelizer {
-    private final BoundedTaskExecutor myParallelBuildExecutor =
-      new BoundedTaskExecutor(SharedThreadPool.getInstance(),
-                              Math.min(MAX_BUILDER_THREADS, Math.max(2, Runtime.getRuntime().availableProcessors())));
+    private final BoundedTaskExecutor myParallelBuildExecutor = new BoundedTaskExecutor(SharedThreadPool.getInstance(), MAX_BUILDER_THREADS);
     private final CompileContext myContext;
     private final AtomicReference<Throwable> myException = new AtomicReference<Throwable>();
     private final Object myQueueLock = new Object();
diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java
index 3cb2117..6aa91c2 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/java/JavaBuilder.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.SystemProperties;
 import com.intellij.util.concurrency.SequentialTaskExecutor;
+import com.intellij.util.io.PersistentEnumeratorBase;
 import gnu.trove.THashMap;
 import gnu.trove.THashSet;
 import org.jetbrains.annotations.NotNull;
@@ -193,6 +194,9 @@
     catch (ProjectBuildException e) {
       throw e;
     }
+    catch (PersistentEnumeratorBase.CorruptedException e) {
+      throw e;
+    }
     catch (Exception e) {
       LOG.info(e);
       String message = e.getMessage();
diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java
index 1a0ce3b..c8fb9b9 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildDataManager.java
@@ -41,7 +41,7 @@
  *         Date: 10/7/11
  */
 public class BuildDataManager implements StorageOwner {
-  private static final int VERSION = 20;
+  private static final int VERSION = 22;
   private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildDataManager");
   private static final String SRC_TO_FORM_STORAGE = "src-form";
   private static final String MAPPINGS_STORAGE = "mappings";
diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java
index e9e2291..d7053cb 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetTypeState.java
@@ -17,7 +17,6 @@
 
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.util.containers.ConcurrentHashMap;
 import com.intellij.util.io.IOUtil;
 import org.jetbrains.jps.builders.BuildTarget;
 import org.jetbrains.jps.builders.BuildTargetLoader;
@@ -26,6 +25,7 @@
 import java.io.*;
 import java.util.HashMap;
 import java.util.Map;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 
 /**
@@ -43,7 +43,7 @@
     myTargetType = targetType;
     myTargetsState = state;
     myTargetsFile = new File(state.getDataPaths().getTargetTypeDataRoot(targetType), "targets.dat");
-    myConfigurations = new ConcurrentHashMap<BuildTarget<?>, BuildTargetConfiguration>();
+    myConfigurations = new ConcurrentHashMap<BuildTarget<?>, BuildTargetConfiguration>(16, 0.75f, 1);
     myTargetIds = new HashMap<BuildTarget<?>, Integer>();
     load();
   }
diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java
index b429429..ad0f85d 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/BuildTargetsState.java
@@ -17,7 +17,6 @@
 
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.util.containers.ConcurrentHashMap;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.jps.builders.BuildTarget;
 import org.jetbrains.jps.builders.BuildTargetType;
@@ -27,6 +26,7 @@
 import org.jetbrains.jps.model.JpsModel;
 
 import java.io.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.ConcurrentMap;
 import java.util.concurrent.atomic.AtomicInteger;
 
@@ -37,7 +37,7 @@
   private static final Logger LOG = Logger.getInstance("#org.jetbrains.jps.incremental.storage.BuildTargetsState");
   private final BuildDataPaths myDataPaths;
   private AtomicInteger myMaxTargetId = new AtomicInteger(0);
-  private ConcurrentMap<BuildTargetType<?>, BuildTargetTypeState> myTypeStates = new ConcurrentHashMap<BuildTargetType<?>, BuildTargetTypeState>();
+  private ConcurrentMap<BuildTargetType<?>, BuildTargetTypeState> myTypeStates = new ConcurrentHashMap<BuildTargetType<?>, BuildTargetTypeState>(16, 0.75f, 1);
   private JpsModel myModel;
   private final BuildRootIndexImpl myBuildRootIndex;
 
@@ -99,9 +99,11 @@
   private BuildTargetTypeState getTypeState(BuildTargetType<?> type) {
     BuildTargetTypeState state = myTypeStates.get(type);
     if (state == null) {
-      state = new BuildTargetTypeState(type, this);
-      myTypeStates.putIfAbsent(type, state);
-      state = myTypeStates.get(type);
+      final BuildTargetTypeState newState = new BuildTargetTypeState(type, this);
+      state = myTypeStates.putIfAbsent(type, newState);
+      if (state == null) {
+        state = newState;
+      }
     }
     return state;
   }
diff --git a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/OneToManyPathsMapping.java b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/OneToManyPathsMapping.java
index 5271f03..2c05163 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/OneToManyPathsMapping.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/incremental/storage/OneToManyPathsMapping.java
@@ -82,9 +82,10 @@
   }
 
   private static class PathCollectionExternalizer implements DataExternalizer<Collection<String>> {
+    private final byte[] myBuffer = IOUtil.allocReadWriteUTFBuffer();
     public void save(DataOutput out, Collection<String> value) throws IOException {
       for (String str : value) {
-        IOUtil.writeString(str, out);
+        IOUtil.writeUTFFast(myBuffer, out, str);
       }
     }
 
@@ -92,7 +93,7 @@
       final Set<String> result = new THashSet<String>(FileUtil.PATH_HASHING_STRATEGY);
       final DataInputStream stream = (DataInputStream)in;
       while (stream.available() > 0) {
-        final String str = IOUtil.readString(stream);
+        final String str = IOUtil.readUTFFast(myBuffer, stream);
         result.add(str);
       }
       return result;
diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/JavacMain.java b/jps/jps-builders/src/org/jetbrains/jps/javac/JavacMain.java
index d294c19..d9c5832 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/javac/JavacMain.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/javac/JavacMain.java
@@ -32,6 +32,7 @@
 import java.lang.reflect.Field;
 import java.lang.reflect.Method;
 import java.util.*;
+import java.util.concurrent.atomic.AtomicBoolean;
 
 /**
  * @author Eugene Zhuravlev
@@ -334,6 +335,7 @@
     private final DiagnosticOutputConsumer myOutConsumer;
     private final OutputFileConsumer myOutputFileSink;
     private final CanceledStatus myCanceledStatus;
+    private static final AtomicBoolean ourOptimizedManagerMissingReported = new AtomicBoolean(false);
 
     public ContextImpl(@NotNull JavaCompiler compiler,
                        @NotNull DiagnosticOutputConsumer outConsumer,
@@ -357,16 +359,12 @@
           }
           catch (Throwable e) {
             if (SystemInfo.isWindows) {
-              outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.OTHER, "JPS build failed to load optimized file manager for javac: " + e.getMessage()));
+              reportMissingOptimizedManager(outConsumer, e.getMessage());
             }
           }
         }
         else {
-          String error = ClasspathBootstrap.getOptimizedFileManagerLoadError();
-          if (error == null) {
-            error = "";
-          }
-          outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.OTHER, "JPS build failed to load optimized file manager for javac:\n" + error));
+          reportMissingOptimizedManager(outConsumer, null);
         }
       }
       myCacheClearMethod = cacheClearMethod;
@@ -378,6 +376,18 @@
       }
     }
 
+    private static void reportMissingOptimizedManager(DiagnosticOutputConsumer outConsumer, String message) {
+      if (!ourOptimizedManagerMissingReported.getAndSet(true)) {
+        if (message == null) {
+          message = ClasspathBootstrap.getOptimizedFileManagerLoadError();
+          if (message == null) {
+            message = "";
+          }
+        }
+        outConsumer.report(new PlainMessageDiagnostic(Diagnostic.Kind.OTHER, "JPS build failed to load optimized file manager for javac:\n" + message));
+      }
+    }
+
     public boolean isCanceled() {
       return myCanceledStatus.isCanceled();
     }
diff --git a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java
index c63614e..c52d2c6 100644
--- a/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java
+++ b/jps/jps-builders/src/org/jetbrains/jps/javac/OptimizedFileManager.java
@@ -530,6 +530,8 @@
   private final ByteBufferCache myByteBufferCache = new ByteBufferCache();
 
 
+  private static volatile boolean ourPathCacheClearProblem = false;
+
   public void close() {
     try {
       super.close();
@@ -542,6 +544,14 @@
       myDirectoryCache.clear();
       myByteBufferCache.clear();
       myIsFile.clear();
+      if (!ourPathCacheClearProblem) {
+        try {
+          Paths.clearPathExistanceCache();
+        }
+        catch (Throwable ignored) {
+          ourPathCacheClearProblem = true;
+        }
+      }
     }
   }
 }
diff --git a/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java b/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java
index 8f97b86..aeb6fde 100644
--- a/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java
+++ b/jps/jps-builders/testSrc/org/jetbrains/ether/CommonTest.java
@@ -113,4 +113,13 @@
   public void testAddDuplicateClass() throws Exception {
     doTest();
   }
+
+  public void testAddClassHidingImportedClass() throws Exception {
+    doTest();
+  }
+
+  public void testAddClassHidingImportedClass2() throws Exception {
+    doTest();
+  }
+
 }
diff --git a/jps/jps-builders/testSrc/org/jetbrains/ether/FieldPropertyTest.java b/jps/jps-builders/testSrc/org/jetbrains/ether/FieldPropertyTest.java
index aa99a68..eee8193 100644
--- a/jps/jps-builders/testSrc/org/jetbrains/ether/FieldPropertyTest.java
+++ b/jps/jps-builders/testSrc/org/jetbrains/ether/FieldPropertyTest.java
@@ -104,6 +104,10 @@
   //  }
 
   public void testNonIncremental4() throws Exception {
-      doTest();
-    }
+    doTest();
+  }
+
+  public void testMutualConstants() throws Exception {
+    doTest();
+  }
 }
diff --git a/jps/lib/optimizedFileManager.jar b/jps/lib/optimizedFileManager.jar
index 55b4e61..cff0c64 100644
--- a/jps/lib/optimizedFileManager.jar
+++ b/jps/lib/optimizedFileManager.jar
Binary files differ
diff --git a/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java b/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java
index 7504690..3a33747 100644
--- a/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java
+++ b/jps/model-impl/src/org/jetbrains/jps/service/impl/JpsServiceManagerImpl.java
@@ -24,8 +24,8 @@
  * @author nik
  */
 public class JpsServiceManagerImpl extends JpsServiceManager {
-  private final ConcurrentHashMap<Class, Object> myServices = new ConcurrentHashMap<Class, Object>();
-  private final ConcurrentHashMap<Class, List<?>> myExtensions = new ConcurrentHashMap<Class, List<?>>();
+  private final ConcurrentHashMap<Class, Object> myServices = new ConcurrentHashMap<Class, Object>(16, 0.75f, 1);
+  private final ConcurrentHashMap<Class, List<?>> myExtensions = new ConcurrentHashMap<Class, List<?>>(16, 0.75f, 1);
 
   @Override
   public <T> T getService(Class<T> serviceClass) {
@@ -36,14 +36,16 @@
       if (!iterator.hasNext()) {
         throw new ServiceConfigurationError("Implementation for " + serviceClass + " not found");
       }
-      service = iterator.next();
+      final T loadedService = iterator.next();
       if (iterator.hasNext()) {
         throw new ServiceConfigurationError(
-          "More than one implementation for " + serviceClass + " found: " + service.getClass() + " and " + iterator.next().getClass());
+          "More than one implementation for " + serviceClass + " found: " + loadedService.getClass() + " and " + iterator.next().getClass());
       }
-      myServices.putIfAbsent(serviceClass, service);
       //noinspection unchecked
-      service = (T)myServices.get(serviceClass);
+      service = (T)myServices.putIfAbsent(serviceClass, loadedService);
+      if (service == null) {
+        service = loadedService;
+      }
     }
     return service;
   }
@@ -53,12 +55,14 @@
     List<?> cached = myExtensions.get(extensionClass);
     if (cached == null) {
       final ServiceLoader<T> loader = ServiceLoader.load(extensionClass, extensionClass.getClassLoader());
-      List<T> extensions = new ArrayList<T>();
+      final List<T> extensions = new ArrayList<T>();
       for (T t : loader) {
         extensions.add(t);
       }
-      myExtensions.putIfAbsent(extensionClass, extensions);
-      cached = myExtensions.get(extensionClass);
+      cached = myExtensions.putIfAbsent(extensionClass, extensions);
+      if (cached == null) {
+        cached = extensions;
+      }
     }
     //noinspection unchecked
     return (List<T>)cached;
diff --git a/lib/pty4j-0.3.jar b/lib/pty4j-0.3.jar
index 9868cdd..8ffcc9c 100644
--- a/lib/pty4j-0.3.jar
+++ b/lib/pty4j-0.3.jar
Binary files differ
diff --git a/native/MacLauncher/Launcher.m b/native/MacLauncher/Launcher.m
index 514fd96..e16e6b5 100644
--- a/native/MacLauncher/Launcher.m
+++ b/native/MacLauncher/Launcher.m
@@ -14,6 +14,8 @@
 typedef jint (JNICALL *fun_ptr_t_CreateJavaVM)(JavaVM **pvm, void **env, void *args);
 
 
+static NSString *const JVMOptions = @"JVMOptions";
+
 @interface NSString (CustomReplacements)
 - (NSString *)replaceAll:(NSString *)pattern to:(NSString *)replacement;
 
@@ -112,7 +114,7 @@
 }
 
 NSString *requiredJvmVersion() {
-    return [[NSBundle mainBundle].infoDictionary valueForKey:@"JVMVersion" inDictionary:@"Java" defaultObject:@"1.7*"];
+    return [[NSBundle mainBundle].infoDictionary valueForKey:@"JVMVersion" inDictionary: JVMOptions defaultObject:@"1.7*"];
 }
 
 BOOL satisfies(NSString *vmVersion, NSString *requiredVersion) {
@@ -170,7 +172,7 @@
 }
 
 - (NSMutableString *)buildClasspath:(NSBundle *)jvm {
-    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Java"];
+    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:JVMOptions];
     NSMutableString *classpathOption = [NSMutableString stringWithString:@"-Djava.class.path="];
     [classpathOption appendString:[jvmInfo objectForKey:@"ClassPath"]];
 
@@ -184,7 +186,7 @@
 
 
 NSString *getSelector() {
-    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Java"];
+    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:JVMOptions];
     NSDictionary *properties = [jvmInfo dictionaryForKey:@"Properties"];
     if (properties != nil) {
         return [properties objectForKey:@"idea.paths.selector"];
@@ -235,7 +237,7 @@
 - (JavaVMInitArgs)buildArgsFor:(NSBundle *)jvm {
     NSMutableString *classpathOption = [self buildClasspath:jvm];
 
-    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Java"];
+    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:JVMOptions];
     NSMutableArray *args_array = [NSMutableArray array];
 
     [args_array addObject:classpathOption];
@@ -260,7 +262,7 @@
 }
 
 - (const char *)mainClassName {
-    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Java"];
+    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:JVMOptions];
     char *answer = strdup([[jvmInfo objectForKey:@"MainClass"] UTF8String]);
     
     char *cur = answer;
@@ -275,7 +277,7 @@
 }
 
 - (void)process_cwd {
-    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:@"Java"];
+    NSDictionary *jvmInfo = [[NSBundle mainBundle] objectForInfoDictionaryKey:JVMOptions];
     NSString *cwd = [jvmInfo objectForKey:@"WorkingDirectory"];
     if (cwd != nil) {
         cwd = [self expandMacros:cwd];
diff --git a/native/MacLauncher/MacLauncher.xcodeproj/project.pbxproj b/native/MacLauncher/MacLauncher.xcodeproj/project.pbxproj
index 2e2d7d9..a9bd2b6 100644
--- a/native/MacLauncher/MacLauncher.xcodeproj/project.pbxproj
+++ b/native/MacLauncher/MacLauncher.xcodeproj/project.pbxproj
@@ -11,7 +11,6 @@
 		1A564BCFE66693BF0B2DD4A9 /* VMOptionsReader.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A564EDDE28564EF1AEBCD13 /* VMOptionsReader.m */; };
 		1A564C27F0BA05F900F34907 /* utils.m in Sources */ = {isa = PBXBuildFile; fileRef = 1A564EEF77B93DBD7FD23161 /* utils.m */; };
 		50E17738155444B900E97451 /* Cocoa.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 50E17737155444B900E97451 /* Cocoa.framework */; };
-		50E1775715552D2900E97451 /* JavaVM.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = C0B58A123544A15DA59B13E3 /* JavaVM.framework */; settings = {ATTRIBUTES = (Weak, ); }; };
 		C0B58A123544A15DA59B13E4 /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = C0B58A123544A15DA59B13DC /* main.m */; };
 		C0B58A123544A15DA59B13E5 /* Launcher.m in Sources */ = {isa = PBXBuildFile; fileRef = C0B58A123544A15DA59B13E0 /* Launcher.m */; };
 /* End PBXBuildFile section */
@@ -31,7 +30,6 @@
 		C0B58A123544A15DA59B13DE /* Foundation.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = Foundation.framework; path = System/Library/Frameworks/Foundation.framework; sourceTree = SDKROOT; };
 		C0B58A123544A15DA59B13E0 /* Launcher.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = Launcher.m; sourceTree = "<group>"; };
 		C0B58A123544A15DA59B13E2 /* Launcher.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = Launcher.h; sourceTree = "<group>"; };
-		C0B58A123544A15DA59B13E3 /* JavaVM.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; name = JavaVM.framework; path = System/Library/Frameworks/JavaVM.framework; sourceTree = SDKROOT; };
 /* End PBXFileReference section */
 
 /* Begin PBXFrameworksBuildPhase section */
@@ -39,7 +37,6 @@
 			isa = PBXFrameworksBuildPhase;
 			buildActionMask = 2147483647;
 			files = (
-				50E1775715552D2900E97451 /* JavaVM.framework in Frameworks */,
 				50E17738155444B900E97451 /* Cocoa.framework in Frameworks */,
 			);
 			runOnlyForDeploymentPostprocessing = 0;
@@ -77,7 +74,6 @@
 		C0B58A123544A15DA59B13D6 /* Frameworks */ = {
 			isa = PBXGroup;
 			children = (
-				C0B58A123544A15DA59B13E3 /* JavaVM.framework */,
 				C0B58A123544A15DA59B13DE /* Foundation.framework */,
 				50E17737155444B900E97451 /* Cocoa.framework */,
 			);
@@ -110,7 +106,7 @@
 		C0B58A123544A15DA59B13C8 /* Project object */ = {
 			isa = PBXProject;
 			attributes = {
-				LastUpgradeCheck = 0450;
+				LastUpgradeCheck = 0500;
 			};
 			buildConfigurationList = C0B58A123544A15DA59B13C9 /* Build configuration list for PBXProject "MacLauncher" */;
 			compatibilityVersion = "Xcode 3.2";
@@ -159,15 +155,16 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				CLANG_ENABLE_OBJC_ARC = NO;
 				COMBINE_HIDPI_IMAGES = YES;
 				GCC_PRECOMPILE_PREFIX_HEADER = YES;
 				GCC_PREFIX_HEADER = Launcher.pch;
-				GCC_VERSION = com.apple.compilers.llvmgcc42;
+				GCC_VERSION = "";
 				INFOPLIST_FILE = Info.plist;
 				MACOSX_DEPLOYMENT_TARGET = 10.5;
 				ONLY_ACTIVE_ARCH = NO;
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SDKROOT = macosx10.7;
+				SDKROOT = macosx;
 				WRAPPER_EXTENSION = app;
 			};
 			name = Release;
@@ -176,15 +173,16 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
+				CLANG_ENABLE_OBJC_ARC = NO;
 				COMBINE_HIDPI_IMAGES = YES;
 				GCC_PRECOMPILE_PREFIX_HEADER = YES;
 				GCC_PREFIX_HEADER = Launcher.pch;
-				GCC_VERSION = com.apple.compilers.llvmgcc42;
+				GCC_VERSION = "";
 				INFOPLIST_FILE = Info.plist;
 				MACOSX_DEPLOYMENT_TARGET = 10.5;
 				ONLY_ACTIVE_ARCH = NO;
 				PRODUCT_NAME = "$(TARGET_NAME)";
-				SDKROOT = macosx10.7;
+				SDKROOT = macosx;
 				WRAPPER_EXTENSION = app;
 			};
 			name = Debug;
@@ -193,7 +191,7 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ALWAYS_SEARCH_USER_PATHS = NO;
-				ARCHS = "$(ARCHS_STANDARD_64_BIT)";
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
 				CLANG_ENABLE_OBJC_ARC = YES;
 				COPY_PHASE_STRIP = YES;
 				DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
@@ -213,7 +211,7 @@
 			isa = XCBuildConfiguration;
 			buildSettings = {
 				ALWAYS_SEARCH_USER_PATHS = NO;
-				ARCHS = "$(ARCHS_STANDARD_64_BIT)";
+				ARCHS = "$(ARCHS_STANDARD_32_64_BIT)";
 				CLANG_ENABLE_OBJC_ARC = YES;
 				COPY_PHASE_STRIP = NO;
 				GCC_C_LANGUAGE_STANDARD = gnu99;
diff --git a/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java b/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java
index 381ecf9..e976b4e 100644
--- a/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java
+++ b/platform/analysis-api/src/com/intellij/analysis/AnalysisScope.java
@@ -282,8 +282,12 @@
         @Override
         public void run() {
           final PsiElement[] psiElements = ((LocalSearchScope)myScope).getScope();
+          final Set<PsiFile> files = new LinkedHashSet<PsiFile>();
           for (PsiElement element : psiElements) {
-            element.accept(visitor);
+            final PsiFile file = element.getContainingFile();
+            if (file != null && files.add(file)) {
+              file.accept(visitor);
+            }
           }
         }
       });
diff --git a/platform/analysis-api/src/com/intellij/psi/search/scope/packageSet/FilePatternPackageSet.java b/platform/analysis-api/src/com/intellij/psi/search/scope/packageSet/FilePatternPackageSet.java
index f936e50..7f01ead 100644
--- a/platform/analysis-api/src/com/intellij/psi/search/scope/packageSet/FilePatternPackageSet.java
+++ b/platform/analysis-api/src/com/intellij/psi/search/scope/packageSet/FilePatternPackageSet.java
@@ -81,7 +81,9 @@
 
   private boolean fileMatcher(VirtualFile virtualFile, ProjectFileIndex fileIndex, VirtualFile projectBaseDir){
     final String relativePath = getRelativePath(virtualFile, fileIndex, true, projectBaseDir);
-    LOG.assertTrue(relativePath != null, "vFile: " + virtualFile + "; projectBaseDir: " + projectBaseDir + "; content File: "+fileIndex.getContentRootForFile(virtualFile));
+    if (relativePath == null) {
+      LOG.error("vFile: " + virtualFile + "; projectBaseDir: " + projectBaseDir + "; content File: "+fileIndex.getContentRootForFile(virtualFile));
+    }
     return myFilePattern.matcher(relativePath).matches();
   }
 
diff --git a/platform/bootstrap/src/com/intellij/idea/Main.java b/platform/bootstrap/src/com/intellij/idea/Main.java
index c9a3f8e..835fa4d 100644
--- a/platform/bootstrap/src/com/intellij/idea/Main.java
+++ b/platform/bootstrap/src/com/intellij/idea/Main.java
@@ -123,8 +123,9 @@
   private static void installPatch() throws IOException {
     String platform = System.getProperty(PLATFORM_PREFIX_PROPERTY, "idea");
     String patchFileName = ("jetbrains.patch.jar." + platform).toLowerCase();
-    File originalPatchFile = new File(System.getProperty("java.io.tmpdir"), patchFileName);
-    File copyPatchFile = new File(System.getProperty("java.io.tmpdir"), patchFileName + "_copy");
+    String tempDir = System.getProperty("java.io.tmpdir");
+    File originalPatchFile = new File(tempDir, patchFileName);
+    File copyPatchFile = new File(tempDir, patchFileName + "_copy");
 
     // always delete previous patch copy
     if (!FileUtilRt.delete(copyPatchFile)) {
@@ -153,6 +154,7 @@
                          "-Xmx500m",
                          "-classpath",
                          copyPatchFile.getPath(),
+                         "-Djava.io.tmpdir=" + tempDir,
                          "com.intellij.updater.Runner",
                          "install",
                          PathManager.getHomePath());
diff --git a/platform/core-api/src/com/intellij/lang/PsiBuilder.java b/platform/core-api/src/com/intellij/lang/PsiBuilder.java
index 73c76f4..c569385 100644
--- a/platform/core-api/src/com/intellij/lang/PsiBuilder.java
+++ b/platform/core-api/src/com/intellij/lang/PsiBuilder.java
@@ -104,7 +104,7 @@
   int rawTokenTypeStart(int steps);
 
   /**
-   * Returns the index of the current token index in the original sequence.
+   * Returns the index of the current token in the original sequence.
    *
    * @return token index
    */
diff --git a/platform/core-api/src/com/intellij/openapi/project/DumbService.java b/platform/core-api/src/com/intellij/openapi/project/DumbService.java
index 825e101..4bced97 100644
--- a/platform/core-api/src/com/intellij/openapi/project/DumbService.java
+++ b/platform/core-api/src/com/intellij/openapi/project/DumbService.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.util.Ref;
 import com.intellij.util.messages.Topic;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.util.ArrayList;
@@ -85,6 +86,22 @@
     return result.get();
   }
 
+  @Nullable
+  public <T> T tryRunReadActionInSmartMode(@NotNull Computable<T> task, @NotNull String notification) {
+    if (ApplicationManager.getApplication().isReadAccessAllowed()) {
+      try {
+        return task.compute();
+      }
+      catch (IndexNotReadyException e) {
+        showDumbModeNotification(notification);
+        return null;
+      }
+    }
+    else {
+      return runReadActionInSmartMode(task);
+    }
+  }
+
   /**
    * Pause the current thread until dumb mode ends, and then run the read action. Index is guaranteed to be available inside that read action.
    */
diff --git a/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java b/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java
index 02d535e..613fadc 100644
--- a/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java
+++ b/platform/core-api/src/com/intellij/openapi/util/AsyncResult.java
@@ -25,6 +25,8 @@
 public class AsyncResult<T> extends ActionCallback {
   private static final Logger LOG = Logger.getInstance(AsyncResult.class);
 
+  private static final AsyncResult REJECTED = new Rejected();
+
   protected T myResult;
 
   @NotNull
@@ -153,6 +155,11 @@
     }
   }
 
+  public static <R> AsyncResult<R> rejected() {
+    //noinspection unchecked
+    return REJECTED;
+  }
+
   // we don't use inner class, avoid memory leak, we don't want to hold this result while dependent is computing
   private static class SubResultDoneCallback<Result, SubResult, AsyncSubResult extends AsyncResult<SubResult>> implements Consumer<Result> {
     private final AsyncSubResult subResult;
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 d594b7d..539e1f2 100644
--- a/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java
+++ b/platform/core-api/src/com/intellij/openapi/vfs/VfsUtilCore.java
@@ -387,7 +387,7 @@
       String suffix = url.substring(index + 2);
 
       if (SystemInfoRt.isWindows) {
-        return prefix + "://" + suffix;
+        return prefix + URLUtil.SCHEME_SEPARATOR + suffix;
       }
       else if (removeLocalhostPrefix && prefix.equals(StandardFileSystems.FILE_PROTOCOL) && suffix.startsWith(LOCALHOST_URI_PATH_PREFIX)) {
         // sometimes (e.g. in Google Chrome for Mac) local file url is prefixed with 'localhost' so we need to remove it
diff --git a/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java b/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java
index c31c464..48d7c43 100644
--- a/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java
+++ b/platform/core-impl/src/com/intellij/lang/impl/PsiBuilderImpl.java
@@ -282,6 +282,14 @@
     public void remapTokenType(IElementType type) {
       throw new UnsupportedOperationException("Shall not be called on this kind of markers");
     }
+
+    public int getStartIndex() {
+      return myLexemeIndex;
+    }
+
+    public int getEndIndex() {
+      throw new UnsupportedOperationException("Shall not be called on this kind of markers");
+    }
   }
 
   private static class StartMarker extends ProductionMarker implements Marker {
@@ -352,6 +360,11 @@
       return myBuilder.myLexStarts[myDoneMarker.myLexemeIndex];
     }
 
+    @Override
+    public int getEndIndex() {
+      return myDoneMarker.myLexemeIndex;
+    }
+
     public void addChild(ProductionMarker node) {
       if (myFirstChild == null) {
         myFirstChild = node;
@@ -738,6 +751,10 @@
     return myCurrentLexeme;
   }
 
+  public int rawTokenOffset(int tokenIndex) {
+    return myLexStarts[tokenIndex];
+  }
+
   @Override
   public void setWhitespaceSkippedCallback(@Nullable final WhitespaceSkippedCallback callback) {
     myWhitespaceSkippedCallback = callback;
diff --git a/platform/platform-impl/src/com/intellij/openapi/application/ex/ApplicationEx.java b/platform/core-impl/src/com/intellij/openapi/application/ex/ApplicationEx.java
similarity index 100%
rename from platform/platform-impl/src/com/intellij/openapi/application/ex/ApplicationEx.java
rename to platform/core-impl/src/com/intellij/openapi/application/ex/ApplicationEx.java
diff --git a/platform/core-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfo.java b/platform/core-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfo.java
index 9f4ef3e..9f517bb 100644
--- a/platform/core-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfo.java
+++ b/platform/core-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfo.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.openapi.vfs.impl.http;
 
+import com.intellij.openapi.util.AsyncResult;
 import com.intellij.openapi.vfs.VirtualFile;
 import org.jetbrains.annotations.NotNull;
 
@@ -34,4 +35,7 @@
   RemoteFileState getState();
 
   void cancelDownloading();
+
+  @NotNull
+  AsyncResult<VirtualFile> download();
 }
diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/CharTableImpl.java b/platform/core-impl/src/com/intellij/psi/impl/source/CharTableImpl.java
index 5253ea8..6b10354 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/source/CharTableImpl.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/source/CharTableImpl.java
@@ -49,7 +49,7 @@
 
   @NotNull
   public CharSequence doIntern(@NotNull CharSequence text) {
-    CharSequence interned = getStaticInterned(text.toString());
+    CharSequence interned = getStaticInterned(text);
     if (interned != null) {
       return interned;
     }
@@ -85,7 +85,7 @@
   }
 
   @Nullable
-  public static CharSequence getStaticInterned(@NotNull String text) {
+  public static CharSequence getStaticInterned(@NotNull CharSequence text) {
     return STATIC_ENTRIES.get(text);
   }
 
diff --git a/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java b/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java
index 3c45de1..621ba27 100644
--- a/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java
+++ b/platform/core-impl/src/com/intellij/psi/impl/source/PsiFileImpl.java
@@ -1008,6 +1008,10 @@
         }
 
         StubElement currentStubTree = ((IStubFileElementType)contentElementType).getBuilder().buildStubTree(this);
+        if (currentStubTree == null) {
+          throw new AssertionError("Stub tree wasn't built for " + contentElementType + "; file: " + this);
+        }
+
         tree = new StubTree((PsiFileStub)currentStubTree);
         tree.setDebugInfo("created in calcStubTree");
         try {
diff --git a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties
index 17078c0..9872721 100644
--- a/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties
+++ b/platform/external-system-api/resources/i18n/ExternalSystemBundle.properties
@@ -11,6 +11,7 @@
 setting.type.location.explicit.incorrect={0} location is incorrect
 settings.label.select.project={0} project:
 settings.label.use.auto.import=Use auto-import
+settings.label.create.empty.content.root.directories=Create directories for empty content roots automatically
 settings.title.linked.projects=Linked {0} projects
 settings.title.project.settings=Project-level settings
 settings.title.system.settings=Global {0} settings
@@ -27,6 +28,7 @@
 error.cannot.parse.project=Can not parse {0} project
 error.resolve.with.reason={0}\n\nConsult IDE log for more details (Help | Show Log)
 error.resolve.generic=Resolve error
+error.resolve.already.running=Another 'refresh project' task is currently running for the project:  {0}
 
 # Tool window
 tool.window.title.tasks=tasks
@@ -58,7 +60,9 @@
 run.configuration.settings.label.project={0} project:
 run.configuration.settings.label.tasks=Tasks:
 run.configuration.settings.label.vmoptions=VM options:
-run.configuration.settings.caption.vmoptions=VM options:
-run.text.starting.multiple.task=Executing external tasks ''{0}''...\n
-run.text.starting.single.task=Executing external task ''{0}''...\n
+run.configuration.settings.label.script.parameters=Script parameters:
+run.text.starting.multiple.task={0}: Executing external tasks ''{1}''...\n
+run.text.starting.single.task={0}: Executing external task ''{1}''...\n
+run.text.ended.multiple.task={0}: External tasks execution finished ''{1}''.\n
+run.text.ended.single.task={0}: External task execution finished ''{1}''.\n
 run.error.undefined.task=No task to execute is specified
\ No newline at end of file
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/execution/ExternalSystemTaskExecutionSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/execution/ExternalSystemTaskExecutionSettings.java
index 70dd816..a9dacf9 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/execution/ExternalSystemTaskExecutionSettings.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/execution/ExternalSystemTaskExecutionSettings.java
@@ -42,6 +42,7 @@
   private String myExternalSystemIdString;
   private String myExternalProjectPath;
   private String myVmOptions;
+  private String myScriptParameters;
 
   public String getExternalSystemIdString() {
     return myExternalSystemIdString;
@@ -71,6 +72,14 @@
     myVmOptions = vmOptions;
   }
 
+  public String getScriptParameters() {
+    return myScriptParameters;
+  }
+
+  public void setScriptParameters(String scriptParameters) {
+    myScriptParameters = scriptParameters;
+  }
+
   public List<String> getTaskNames() {
     return myTaskNames;
   }
@@ -93,6 +102,7 @@
     result.setExternalSystemIdString(getExternalSystemIdString());
     result.setExternalProjectPath(getExternalProjectPath());
     result.setVmOptions(getVmOptions());
+    result.setScriptParameters(getScriptParameters());
     result.setTaskNames(ContainerUtilRt.newArrayList(getTaskNames()));
     result.setTaskDescriptions(ContainerUtilRt.newArrayList(getTaskDescriptions()));
     return result;
@@ -104,6 +114,7 @@
     result = 31 * result + (myExternalSystemIdString != null ? myExternalSystemIdString.hashCode() : 0);
     result = 31 * result + (myExternalProjectPath != null ? myExternalProjectPath.hashCode() : 0);
     result = 31 * result + (myVmOptions != null ? myVmOptions.hashCode() : 0);
+    result = 31 * result + (myScriptParameters != null ? myScriptParameters.hashCode() : 0);
     return result;
   }
 
@@ -128,6 +139,7 @@
     }
     if (myTaskNames != null ? !myTaskNames.equals(settings.myTaskNames) : settings.myTaskNames != null) return false;
     if (StringUtil.isEmpty(myVmOptions) ^ StringUtil.isEmpty(settings.myVmOptions)) return false;
+    if (StringUtil.isEmpty(myScriptParameters) ^ StringUtil.isEmpty(settings.myScriptParameters)) return false;
 
     return true;
   }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java
index a765ef5..0b4078d 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractDependencyData.java
@@ -58,17 +58,48 @@
     myExported = exported;
   }
 
+  /**
+   * please use {@link #getExternalName()} or {@link #getInternalName()} instead
+   */
   @NotNull
+  @Deprecated
   @Override
   public String getName() {
     return myTarget.getName();
   }
-  
+
+  /**
+   * please use {@link #setExternalName(String)} or {@link #setInternalName(String)} instead
+   */
+  @Deprecated
   @Override
   public void setName(@NotNull String name) {
     myTarget.setName(name);
   }
 
+  @NotNull
+  @Override
+  public String getExternalName() {
+    return myTarget.getExternalName();
+  }
+
+  @Override
+  public void setExternalName(@NotNull String name) {
+    myTarget.setExternalName(name);
+  }
+
+  @NotNull
+  @Override
+  public String getInternalName() {
+    return myTarget.getInternalName();
+  }
+
+  @Override
+  public void setInternalName(@NotNull String name) {
+    myTarget.setInternalName(name);
+  }
+
+
   @SuppressWarnings("MethodOverridesPrivateMethodOfSuperclass")
   private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
     in.defaultReadObject();
@@ -77,6 +108,7 @@
   @Override
   public int hashCode() {
     int result = super.hashCode();
+    result = 31 * result + myScope.hashCode();
     result = 31 * result + myOwnerModule.hashCode();
     result = 31 * result + myTarget.hashCode();
     return result;
@@ -88,7 +120,7 @@
       return false;
     }
     AbstractDependencyData<?> that = (AbstractDependencyData<?>)o;
-    return myOwnerModule.equals(that.myOwnerModule) && myTarget.equals(that.myTarget);
+    return  myScope.equals(that.myScope) && myOwnerModule.equals(that.myOwnerModule) && myTarget.equals(that.myTarget);
   }
 
   @Override
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractNamedData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractNamedData.java
index 36a8761..99d9d7c 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractNamedData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/AbstractNamedData.java
@@ -10,29 +10,68 @@
 public abstract class AbstractNamedData extends AbstractExternalEntityData implements Named {
 
   private static final long serialVersionUID = 1L;
-  
-  private String myName;
 
-  public AbstractNamedData(@NotNull ProjectSystemId owner, @NotNull String name) {
+  @NotNull
+  private String myExternalName;
+  @NotNull
+  private String myInternalName;
+
+  public AbstractNamedData(@NotNull ProjectSystemId owner, @NotNull String externalName) {
+    this(owner, externalName, externalName);
+  }
+
+  public AbstractNamedData(@NotNull ProjectSystemId owner, @NotNull String externalName, @NotNull String internalName) {
     super(owner);
-    myName = name;
+    myExternalName = externalName;
+    myInternalName = internalName;
+  }
+
+  /**
+   * please use {@link #getExternalName()} or {@link #getInternalName()} instead
+   */
+  @NotNull
+  @Deprecated
+  @Override
+  public String getName() {
+    return getExternalName();
+  }
+
+  /**
+   * please use {@link #setExternalName(String)} or {@link #setInternalName(String)} instead
+   */
+  @Deprecated
+  @Override
+  public void setName(@NotNull String name) {
+    setExternalName(name);
   }
 
   @NotNull
   @Override
-  public String getName() {
-    return myName;
+  public String getExternalName() {
+    return myExternalName;
   }
 
   @Override
-  public void setName(@NotNull String name) {
-    myName = name;
+  public void setExternalName(@NotNull String name) {
+    myExternalName = name;
+  }
+
+  @NotNull
+  @Override
+  public String getInternalName() {
+    return myInternalName;
+  }
+
+  @Override
+  public void setInternalName(@NotNull String name) {
+    myInternalName = name;
   }
 
   @Override
   public int hashCode() {
     int result = super.hashCode();
-    result = 31 * result + myName.hashCode();
+    result = 31 * result + myExternalName.hashCode();
+    result = 31 * result + myInternalName.hashCode();
     return result;
   }
 
@@ -40,7 +79,10 @@
   public boolean equals(Object o) {
     if (!super.equals(o)) return false;
 
-    AbstractNamedData that = (AbstractNamedData)o;
-    return myName.equals(that.myName);
+    AbstractNamedData data = (AbstractNamedData)o;
+
+    if (!myExternalName.equals(data.myExternalName)) return false;
+    if (!myInternalName.equals(data.myInternalName)) return false;
+    return true;
   }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ExternalProjectPojo.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ExternalProjectPojo.java
index 9f90872..af46467 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ExternalProjectPojo.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ExternalProjectPojo.java
@@ -15,14 +15,15 @@
  */
 package com.intellij.openapi.externalSystem.model.project;
 
+import com.intellij.openapi.util.text.StringUtil;
 import org.jetbrains.annotations.NotNull;
 
 /**
-* @author Denis Zhdanov
-* @since 5/18/13 10:51 PM
-*/
+ * @author Denis Zhdanov
+ * @since 5/18/13 10:51 PM
+ */
 public class ExternalProjectPojo implements Comparable<ExternalProjectPojo> {
-  
+
   @NotNull private String myName;
   @NotNull private String myPath;
 
@@ -38,10 +39,11 @@
   }
 
   @NotNull
-  public static <T extends Named & ExternalConfigPathAware> ExternalProjectPojo from(@NotNull T data) {
-    return new ExternalProjectPojo(data.getName(), data.getLinkedExternalProjectPath());
+  public static <T extends Named & ExternalConfigPathAware & Identifiable> ExternalProjectPojo from(@NotNull T data) {
+    String projectUniqueName = StringUtil.isEmpty(data.getId()) ? data.getExternalName() : data.getId();
+    return new ExternalProjectPojo(projectUniqueName, data.getLinkedExternalProjectPath());
   }
-  
+
   @NotNull
   public String getName() {
     return myName;
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Identifiable.java
similarity index 64%
rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
rename to platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Identifiable.java
index fec7c97..3d18144 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Identifiable.java
@@ -13,22 +13,16 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model.impl;
+package com.intellij.openapi.externalSystem.model.project;
 
-import org.gradle.tooling.model.Dependency;
-
-import java.io.Serializable;
+import org.jetbrains.annotations.NotNull;
 
 /**
  * @author Vladislav.Soroka
- * @since 11/8/13
+ * @since 11/27/13
  */
-public interface GradleDependency extends Dependency, Serializable {
-  String getConfigurationName();
+public interface Identifiable {
 
-  String getDependencyName();
-
-  String getDependencyGroup();
-
-  String getDependencyVersion();
+  @NotNull
+  String getId();
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/LibraryData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/LibraryData.java
index 695e35c..9e51ae5 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/LibraryData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/LibraryData.java
@@ -29,7 +29,7 @@
   }
 
   public LibraryData(@NotNull ProjectSystemId owner, @NotNull String name, boolean unresolved) {
-    super(owner, name);
+    super(owner, name, String.format("%s: %s", owner.getReadableName(), name));
     myUnresolved = unresolved;
   }
 
@@ -73,6 +73,6 @@
 
   @Override
   public String toString() {
-    return String.format("library %s%s", getName(), myUnresolved ? "(unresolved)" : "");
+    return String.format("library %s%s", getExternalName(), myUnresolved ? "(unresolved)" : "");
   }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java
index d9f1f9d..212396c 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleData.java
@@ -4,7 +4,6 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
 import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.containers.ContainerUtilRt;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -17,12 +16,12 @@
  * @author Denis Zhdanov
  * @since 8/8/11 12:11 PM
  */
-public class ModuleData extends AbstractNamedData implements Named, ExternalConfigPathAware {
+public class ModuleData extends AbstractNamedData implements Named, ExternalConfigPathAware, Identifiable {
 
   private static final long serialVersionUID = 1L;
 
-  @NotNull private final Map<ExternalSystemSourceType, String> myCompileOutputPaths = ContainerUtilRt.newHashMap();
-
+  @NotNull private final Map<ExternalSystemSourceType, String> myCompileOutputPaths = ContainerUtil.newHashMap();
+  @NotNull private final String myId;
   @NotNull private final String myModuleTypeId;
   @NotNull private final String myExternalConfigPath;
   @NotNull private String myModuleFilePath;
@@ -32,12 +31,23 @@
 
   private boolean myInheritProjectCompileOutputPath = true;
 
+  @Deprecated
   public ModuleData(@NotNull ProjectSystemId owner,
                     @NotNull String typeId,
                     @NotNull String name,
                     @NotNull String moduleFileDirectoryPath,
                     @NotNull String externalConfigPath) {
-    super(owner, name);
+    this("", owner, typeId, name, moduleFileDirectoryPath, externalConfigPath);
+  }
+
+  public ModuleData(@NotNull String id,
+                    @NotNull ProjectSystemId owner,
+                    @NotNull String typeId,
+                    @NotNull String name,
+                    @NotNull String moduleFileDirectoryPath,
+                    @NotNull String externalConfigPath) {
+    super(owner, name, name.replaceAll("(/|\\\\)", "_"));
+    myId = id;
     myModuleTypeId = typeId;
     myExternalConfigPath = externalConfigPath;
     myArtifacts = Collections.emptyList();
@@ -45,6 +55,12 @@
   }
 
   @NotNull
+  @Override
+  public String getId() {
+    return myId;
+  }
+
+  @NotNull
   public String getModuleTypeId() {
     return myModuleTypeId;
   }
@@ -61,7 +77,7 @@
   }
 
   public void setModuleFileDirectoryPath(@NotNull String path) {
-    myModuleFilePath = ExternalSystemApiUtil.toCanonicalPath(path + "/" + getName() + ModuleFileType.DOT_DEFAULT_EXTENSION);
+    myModuleFilePath = ExternalSystemApiUtil.toCanonicalPath(path + "/" + getInternalName() + ModuleFileType.DOT_DEFAULT_EXTENSION);
   }
 
   public boolean isInheritProjectCompileOutputPath() {
@@ -147,7 +163,7 @@
   public String toString() {
     return String.format("module '%s:%s:%s'",
                          group == null ? "" : group,
-                         getName(),
+                         getExternalName(),
                          version == null ? "" : version);
   }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleDependencyData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleDependencyData.java
index 3da5e8d..7aed9c0 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleDependencyData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ModuleDependencyData.java
@@ -10,13 +10,6 @@
  */
 public class ModuleDependencyData extends AbstractDependencyData<ModuleData> {
 
-  public static final Comparator<ModuleDependencyData> COMPARATOR = new Comparator<ModuleDependencyData>() {
-    @Override
-    public int compare(ModuleDependencyData o1, ModuleDependencyData o2) {
-      return Named.COMPARATOR.compare(o1.getTarget(), o2.getTarget());
-    }
-  };
-
   private static final long serialVersionUID = 1L;
 
   public ModuleDependencyData(@NotNull ModuleData ownerModule, @NotNull ModuleData module) {
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Named.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Named.java
index bf7eab9..d598f31 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Named.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/Named.java
@@ -12,18 +12,24 @@
  */
 public interface Named {
 
-  /** Key of the {@link #getName() name} property to use with {@link PropertyChangeListener#propertyChange(PropertyChangeEvent)}. */
-  String NAME_PROPERTY = "Name";
-  
-  Comparator<Named> COMPARATOR = new Comparator<Named>() {
-    @Override
-    public int compare(Named o1, Named o2) {
-      return o1.getName().compareTo(o2.getName());
-    }
-  };
-  
+  /**
+   * please use {@link #getExternalName()} or {@link #getInternalName()} instead
+   */
   @NotNull
+  @Deprecated
   String getName();
 
+  /**
+   * please use {@link #setExternalName(String)} or {@link #setInternalName(String)} instead
+   */
+  @Deprecated
   void setName(@NotNull String name);
+
+  @NotNull
+  String getExternalName();
+  void setExternalName(@NotNull String name);
+
+  @NotNull
+  String getInternalName();
+  void setInternalName(@NotNull String name);
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java
index 3850434..10d332b 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/project/ProjectData.java
@@ -6,11 +6,11 @@
 
 /**
  * Not thread-safe.
- * 
+ *
  * @author Denis Zhdanov
  * @since 8/1/11 1:30 PM
  */
-public class ProjectData extends AbstractNamedData implements ExternalConfigPathAware {
+public class ProjectData extends AbstractNamedData implements ExternalConfigPathAware, Identifiable {
 
   private static final long serialVersionUID = 1L;
 
@@ -18,15 +18,31 @@
 
   @NotNull private String myIdeProjectFileDirectoryPath;
 
+  @Deprecated
   public ProjectData(@NotNull ProjectSystemId owner,
                      @NotNull String ideProjectFileDirectoryPath,
-                     @NotNull String linkedExternalProjectPath)
-  {
+                     @NotNull String linkedExternalProjectPath) {
     super(owner, "unnamed");
     myLinkedExternalProjectPath = ExternalSystemApiUtil.toCanonicalPath(linkedExternalProjectPath);
     myIdeProjectFileDirectoryPath = ExternalSystemApiUtil.toCanonicalPath(ideProjectFileDirectoryPath);
   }
 
+  public ProjectData(@NotNull ProjectSystemId owner,
+                     @NotNull String externalName,
+                     @NotNull String ideProjectFileDirectoryPath,
+                     @NotNull String linkedExternalProjectPath) {
+    super(owner, externalName);
+    myLinkedExternalProjectPath = ExternalSystemApiUtil.toCanonicalPath(linkedExternalProjectPath);
+    myIdeProjectFileDirectoryPath = ExternalSystemApiUtil.toCanonicalPath(ideProjectFileDirectoryPath);
+  }
+
+  @Deprecated
+  @Override
+  public void setName(@NotNull String name) {
+    super.setExternalName(name);
+    super.setInternalName(name);
+  }
+
   @NotNull
   public String getIdeProjectFileDirectoryPath() {
     return myIdeProjectFileDirectoryPath;
@@ -63,6 +79,12 @@
 
   @Override
   public String toString() {
-    return String.format("%s project '%s'", getOwner().toString().toLowerCase(), getName());
+    return String.format("%s project '%s'", getOwner().toString().toLowerCase(), getExternalName());
+  }
+
+  @NotNull
+  @Override
+  public String getId() {
+    return "";
   }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTask.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTask.java
index 2329fd3..f0ebb53 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTask.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTask.java
@@ -43,14 +43,14 @@
    * @param indicator  target progress indicator
    * @param listeners  callbacks to be notified on task execution update
    */
-  void cancel(@NotNull ProgressIndicator indicator, @NotNull ExternalSystemTaskNotificationListener... listeners);
+  boolean cancel(@NotNull ProgressIndicator indicator, @NotNull ExternalSystemTaskNotificationListener... listeners);
 
   /**
    * Cancels current task at the calling thread, i.e. the call to this method blocks.
    *
    * @param listeners  callbacks to be notified about the task execution update
    */
-  void cancel(@NotNull ExternalSystemTaskNotificationListener... listeners);
+  boolean cancel(@NotNull ExternalSystemTaskNotificationListener... listeners);
 
   /**
    * Forces current task to refresh {@link #getState() its state}.
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTaskState.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTaskState.java
index 2df96af..09c6a72 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTaskState.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/model/task/ExternalSystemTaskState.java
@@ -21,5 +21,9 @@
  */
 public enum ExternalSystemTaskState {
   
-  NOT_STARTED, IN_PROGRESS, FINISHED, FAILED, CANCELING, CANCELED
+  NOT_STARTED, IN_PROGRESS, FINISHED, FAILED, CANCELING, CANCELED, CANCELLATION_FAILED;
+
+  public boolean isStopped() {
+    return this == FINISHED || this == FAILED || this == CANCELED;
+  }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemProjectResolver.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemProjectResolver.java
index db186ca..4edc4a9 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemProjectResolver.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/service/project/ExternalSystemProjectResolver.java
@@ -35,17 +35,17 @@
   /**
    * Builds object-level representation of the external system config file contained at the given path.
    *
-   * @param id                id of the current 'resolve project info' task
-   * @param projectPath       absolute path to the target external system config file
-   * @param isPreviewMode     Indicates, that an implementation can not provide/resolve any external dependencies.
-   *                          Only project dependencies and local file dependencies may included on the modules' classpath.
-   *                          And should not include any 'heavy' tasks like not trivial code generations.
-   *                          It is supposed to be fast.
-   * @param settings          settings to use for the project resolving;
-   *                          <code>null</code> as indication that no specific settings are required
-   * @param listener          callback to be notified about the execution
+   * @param id            id of the current 'resolve project info' task
+   * @param projectPath   absolute path to the target external system config file
+   * @param isPreviewMode Indicates, that an implementation can not provide/resolve any external dependencies.
+   *                      Only project dependencies and local file dependencies may included on the modules' classpath.
+   *                      And should not include any 'heavy' tasks like not trivial code generations.
+   *                      It is supposed to be fast.
+   * @param settings      settings to use for the project resolving;
+   *                      <code>null</code> as indication that no specific settings are required
+   * @param listener      callback to be notified about the execution
    * @return object-level representation of the target external system project;
-   *         <code>null</code> if it's not possible to resolve the project due to the objective reasons
+   * <code>null</code> if it's not possible to resolve the project due to the objective reasons
    * @throws ExternalSystemException  in case when unexpected exception occurs during project info construction
    * @throws IllegalArgumentException if given path is invalid
    * @throws IllegalStateException    if it's not possible to resolve target project info
@@ -57,5 +57,12 @@
                                            @Nullable S settings,
                                            @NotNull ExternalSystemTaskNotificationListener listener)
     throws ExternalSystemException, IllegalArgumentException, IllegalStateException;
+
+  /**
+   * @param taskId   id of the 'resolve project info' task
+   * @param listener callback to be notified about the cancellation
+   * @return true if the task execution was successfully stopped, false otherwise or if target external system does not support the task cancellation
+   */
+  boolean cancelTask(@NotNull ExternalSystemTaskId taskId, @NotNull ExternalSystemTaskNotificationListener listener);
 }
 
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
index 308750d..6e1740c 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/AbstractExternalSystemSettings.java
@@ -99,7 +99,15 @@
 
   @Nullable
   public PS getLinkedProjectSettings(@NotNull String linkedProjectPath) {
-    return myLinkedProjectsSettings.get(linkedProjectPath);
+    PS ps = myLinkedProjectsSettings.get(linkedProjectPath);
+    if(ps == null) {
+      for (PS ps1 : myLinkedProjectsSettings.values()) {
+        for (String modulePath : ps1.getModules()) {
+          if(linkedProjectPath.equals(modulePath)) return ps1;
+        }
+      }
+    }
+    return ps;
   }
 
   public void linkProject(@NotNull PS settings) throws IllegalArgumentException {
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java
index c7a6ecb..c06d5fc 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/settings/ExternalProjectSettings.java
@@ -16,7 +16,13 @@
 package com.intellij.openapi.externalSystem.settings;
 
 import com.intellij.openapi.util.Comparing;
+import com.intellij.util.xmlb.annotations.AbstractCollection;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.Collections;
+import java.util.HashSet;
+import java.util.Set;
 
 /**
  * Holds settings specific to a particular project imported from an external system.
@@ -27,7 +33,20 @@
 public abstract class ExternalProjectSettings implements Comparable<ExternalProjectSettings>, Cloneable {
 
   private String  myExternalProjectPath;
+  @AbstractCollection(surroundWithTag = true)
+  @Nullable private Set<String> myModules = new HashSet<String>();
+
+  @NotNull
+  public Set<String> getModules() {
+    return myModules == null ? Collections.<String>emptySet() : myModules;
+  }
+
+  public void setModules(@Nullable Set<String> modules) {
+    this.myModules = modules;
+  }
+
   private boolean myUseAutoImport;
+  private boolean myCreateEmptyContentRootDirectories;
 
   public String getExternalProjectPath() {
     return myExternalProjectPath;
@@ -45,6 +64,14 @@
     myUseAutoImport = useAutoImport;
   }
 
+  public boolean isCreateEmptyContentRootDirectories() {
+    return myCreateEmptyContentRootDirectories;
+  }
+
+  public void setCreateEmptyContentRootDirectories(boolean createEmptyContentRootDirectories) {
+    myCreateEmptyContentRootDirectories = createEmptyContentRootDirectories;
+  }
+
   @Override
   public int compareTo(@NotNull ExternalProjectSettings that) {
     return Comparing.compare(myExternalProjectPath, that.myExternalProjectPath);
@@ -75,6 +102,8 @@
 
   protected void copyTo(@NotNull ExternalProjectSettings receiver) {
     receiver.myExternalProjectPath = myExternalProjectPath;
+    receiver.myModules = new HashSet<String>(myModules);
     receiver.myUseAutoImport = myUseAutoImport;
+    receiver.myCreateEmptyContentRootDirectories = myCreateEmptyContentRootDirectories;
   }
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/AbstractExternalSystemTaskManager.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/AbstractExternalSystemTaskManager.java
new file mode 100644
index 0000000..0bb5a87
--- /dev/null
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/AbstractExternalSystemTaskManager.java
@@ -0,0 +1,41 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.externalSystem.task;
+
+import com.intellij.openapi.externalSystem.model.ExternalSystemException;
+import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 12/19/13
+ */
+public abstract class AbstractExternalSystemTaskManager<S extends ExternalSystemExecutionSettings> implements ExternalSystemTaskManager<S> {
+
+  public abstract void executeTasks(@NotNull ExternalSystemTaskId id,
+                                    @NotNull List<String> taskNames,
+                                    @NotNull String projectPath,
+                                    @Nullable S settings,
+                                    @NotNull final List<String> vmOptions,
+                                    @NotNull List<String> scriptParameters,
+                                    @Nullable String debuggerSetup,
+                                    @NotNull ExternalSystemTaskNotificationListener listener) throws ExternalSystemException;
+}
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/ExternalSystemTaskManager.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/ExternalSystemTaskManager.java
index df27cdb..c65c7a4 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/ExternalSystemTaskManager.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/task/ExternalSystemTaskManager.java
@@ -32,6 +32,11 @@
  */
 public interface ExternalSystemTaskManager<S extends ExternalSystemExecutionSettings> {
 
+  /**
+   *
+   * @deprecated will be removed in 13.1
+   */
+  @Deprecated
   void executeTasks(@NotNull ExternalSystemTaskId id,
                     @NotNull List<String> taskNames,
                     @NotNull String projectPath,
@@ -41,7 +46,7 @@
                     @NotNull ExternalSystemTaskNotificationListener listener)
     throws ExternalSystemException;
 
-  void cancelTask(@NotNull ExternalSystemTaskId id,
+  boolean cancelTask(@NotNull ExternalSystemTaskId id,
                   @NotNull ExternalSystemTaskNotificationListener listener)
     throws ExternalSystemException;
 }
diff --git a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java
index b846199..7b078c7 100644
--- a/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java
+++ b/platform/external-system-api/src/com/intellij/openapi/externalSystem/util/ExternalSystemApiUtil.java
@@ -167,18 +167,8 @@
     return "unknown-lib";
   }
 
-  @NotNull
-  public static String getLibraryName(@NotNull LibraryData libraryData) {
-    return String.format("%s: %s", libraryData.getOwner().getReadableName(), libraryData.getName());
-  }
-
-  @NotNull
-  public static String getLibraryName(@NotNull LibraryDependencyData libraryDependencyData) {
-    return String.format("%s: %s", libraryDependencyData.getOwner().getReadableName(), libraryDependencyData.getName());
-  }
-
   public static boolean isRelated(@NotNull Library library, @NotNull LibraryData libraryData) {
-    return getLibraryName(library).equals(getLibraryName(libraryData));
+    return getLibraryName(library).equals(libraryData.getInternalName());
   }
 
   public static boolean isExternalSystemLibrary(@NotNull Library library, @NotNull ProjectSystemId externalSystemId) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/AbstractExternalSystemFacadeImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/AbstractExternalSystemFacadeImpl.java
index d709464..0dc2875a5 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/AbstractExternalSystemFacadeImpl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/AbstractExternalSystemFacadeImpl.java
@@ -1,7 +1,6 @@
 package com.intellij.openapi.externalSystem.service;
 
 import com.intellij.execution.rmi.RemoteServer;
-import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
 import com.intellij.openapi.externalSystem.model.task.*;
 import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver;
@@ -190,11 +189,11 @@
   }
 
   @Override
-  public void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
+  public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
     if(id.getType() == ExternalSystemTaskType.RESOLVE_PROJECT) {
-      myProjectResolver.cancelTask(id);
+      return myProjectResolver.cancelTask(id);
     } else{
-      myTaskManager.cancelTask(id);
+      return myTaskManager.cancelTask(id);
     }
   }
 
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemCommunicationManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemCommunicationManager.java
index 3b74bcf..9a09340 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemCommunicationManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/ExternalSystemCommunicationManager.java
@@ -35,7 +35,7 @@
  * <p/>
  * That's why that stuff is covered by the current interface, i.e. different implementations are supposed to provide
  * different 'in process' modes.
- * 
+ *
  * @author Denis Zhdanov
  * @since 8/9/13 3:21 PM
  */
@@ -43,18 +43,27 @@
 
   /**
    * Creates new external system facade for the given arguments.
-   * 
-   * @param id                   if for which new facade is to be created
-   * @param externalSystemId     target external system id
-   * @return                     newly created facade for the given arguments (if it was possible to create one)
-   * @throws Exception           in case something goes wrong
+   *
+   * @param id               if for which new facade is to be created
+   * @param externalSystemId target external system id
+   * @return newly created facade for the given arguments (if it was possible to create one)
+   * @throws Exception in case something goes wrong
    */
   @Nullable
   RemoteExternalSystemFacade acquire(@NotNull String id, @NotNull ProjectSystemId externalSystemId)
     throws Exception;
 
+  /**
+   * Release resource acquired by the current manager
+   *
+   * @param id               resource id
+   * @param externalSystemId target external system id
+   * @throws Exception in case something goes wrong
+   */
+  void release(@NotNull String id, @NotNull ProjectSystemId externalSystemId) throws Exception;
+
   boolean isAlive(@NotNull RemoteExternalSystemFacade facade);
-  
+
   /**
    * Disposes all resources acquired by the current manager.
    */
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/InProcessExternalSystemCommunicationManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/InProcessExternalSystemCommunicationManager.java
index 40b0163..74f8995 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/InProcessExternalSystemCommunicationManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/InProcessExternalSystemCommunicationManager.java
@@ -49,6 +49,10 @@
   }
 
   @Override
+  public void release(@NotNull String id, @NotNull ProjectSystemId externalSystemId) throws Exception {
+  }
+
+  @Override
   public boolean isAlive(@NotNull RemoteExternalSystemFacade facade) {
     RemoteExternalSystemFacade toCheck = facade;
     if (facade instanceof ExternalSystemFacadeWrapper) {
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 ea9af5a..47ae760 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
@@ -232,6 +232,11 @@
   }
 
   @Override
+  public void release(@NotNull String id, @NotNull ProjectSystemId externalSystemId) throws Exception {
+    mySupport.release(this, id);
+  }
+
+  @Override
   public boolean isAlive(@NotNull RemoteExternalSystemFacade facade) {
     RemoteExternalSystemFacade toCheck = facade;
     if (facade instanceof ExternalSystemFacadeWrapper) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemFacade.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemFacade.java
index 5a095f7..350fec6 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemFacade.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/RemoteExternalSystemFacade.java
@@ -57,7 +57,8 @@
     }
 
     @Override
-    public void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
+    public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
+      return false;
     }
 
     @NotNull
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java
index 60c05b7..71fc6e4 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemRunConfiguration.java
@@ -26,13 +26,16 @@
 import com.intellij.openapi.externalSystem.service.internal.ExternalSystemExecuteTaskTask;
 import com.intellij.openapi.externalSystem.util.ExternalSystemBundle;
 import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
+import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.options.SettingsEditor;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.InvalidDataException;
 import com.intellij.openapi.util.WriteExternalException;
 import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.ExceptionUtil;
 import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.net.NetUtils;
+import com.intellij.util.text.DateFormatUtil;
 import com.intellij.util.xmlb.XmlSerializer;
 import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
@@ -106,10 +109,10 @@
   }
 
   public static class MyRunnableState implements RunProfileState {
-    
+
     @NotNull private final ExternalSystemTaskExecutionSettings mySettings;
     @NotNull private final Project myProject;
-    
+
     private final int myDebugPort;
 
     public MyRunnableState(@NotNull ExternalSystemTaskExecutionSettings settings, @NotNull Project project, boolean debug) {
@@ -153,11 +156,15 @@
       if (myDebugPort > 0) {
         debuggerSetup = "-agentlib:jdwp=transport=dt_socket,server=n,suspend=y,address=" + myDebugPort;
       }
-      
+
+      ApplicationManager.getApplication().assertIsDispatchThread();
+      FileDocumentManager.getInstance().saveAllDocuments();
+
       final ExternalSystemExecuteTaskTask task = new ExternalSystemExecuteTaskTask(mySettings.getExternalSystemId(),
                                                                                    myProject,
                                                                                    tasks,
                                                                                    mySettings.getVmOptions(),
+                                                                                   mySettings.getScriptParameters(),
                                                                                    debuggerSetup);
 
       final MyProcessHandler processHandler = new MyProcessHandler(task);
@@ -166,12 +173,13 @@
       ApplicationManager.getApplication().executeOnPooledThread(new Runnable() {
         @Override
         public void run() {
+          final String startDateTime = DateFormatUtil.formatTimeWithSeconds(System.currentTimeMillis());
           final String greeting;
           if (mySettings.getTaskNames().size() > 1) {
-            greeting = ExternalSystemBundle.message("run.text.starting.multiple.task", StringUtil.join(mySettings.getTaskNames(), " "));
+            greeting = ExternalSystemBundle.message("run.text.starting.multiple.task", startDateTime, StringUtil.join(mySettings.getTaskNames(), " "));
           }
           else {
-            greeting = ExternalSystemBundle.message("run.text.starting.single.task", StringUtil.join(mySettings.getTaskNames(), " "));
+            greeting = ExternalSystemBundle.message("run.text.starting.single.task", startDateTime, StringUtil.join(mySettings.getTaskNames(), " "));
           }
           processHandler.notifyTextAvailable(greeting, ProcessOutputTypes.SYSTEM);
           task.execute(new ExternalSystemTaskNotificationListenerAdapter() {
@@ -188,7 +196,24 @@
             }
 
             @Override
+            public void onFailure(@NotNull ExternalSystemTaskId id, @NotNull Exception e) {
+              String exceptionMessage = ExceptionUtil.getMessage(e);
+              String text = exceptionMessage == null ? e.toString() : exceptionMessage;
+              processHandler.notifyTextAvailable(text + '\n', ProcessOutputTypes.STDERR);
+              processHandler.notifyProcessTerminated(0);
+            }
+
+            @Override
             public void onEnd(@NotNull ExternalSystemTaskId id) {
+              final String endDateTime = DateFormatUtil.formatTimeWithSeconds(System.currentTimeMillis());
+              final String farewell;
+              if (mySettings.getTaskNames().size() > 1) {
+                farewell = ExternalSystemBundle.message("run.text.ended.multiple.task", endDateTime, StringUtil.join(mySettings.getTaskNames(), " "));
+              }
+              else {
+                farewell = ExternalSystemBundle.message("run.text.ended.single.task", endDateTime, StringUtil.join(mySettings.getTaskNames(), " "));
+              }
+              processHandler.notifyTextAvailable(farewell, ProcessOutputTypes.SYSTEM);
               processHandler.notifyProcessTerminated(0);
             }
           });
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemTaskSettingsControl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemTaskSettingsControl.java
index 14c80e7..4e7a87e 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemTaskSettingsControl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/execution/ExternalSystemTaskSettingsControl.java
@@ -45,17 +45,20 @@
 public class ExternalSystemTaskSettingsControl implements ExternalSystemSettingsControl<ExternalSystemTaskExecutionSettings> {
 
   @NotNull private final ProjectSystemId myExternalSystemId;
-  @NotNull private final Project         myProject;
+  @NotNull private final Project myProject;
 
   @SuppressWarnings("FieldCanBeLocal") // Used via reflection at showUi() and disposeResources()
-  private JBLabel                  myProjectPathLabel;
+  private JBLabel myProjectPathLabel;
   private ExternalProjectPathField myProjectPathField;
   @SuppressWarnings("FieldCanBeLocal") // Used via reflection at showUi() and disposeResources()
-  private JBLabel                  myTasksLabel;
-  private JBTextField              myTasksTextField;
+  private JBLabel myTasksLabel;
+  private JBTextField myTasksTextField;
   @SuppressWarnings("FieldCanBeLocal") // Used via reflection at showUi() and disposeResources()
-  private JBLabel                  myVmOptionsLabel;
-  private RawCommandLineEditor     myVmOptionsEditor;
+  private JBLabel myVmOptionsLabel;
+  private RawCommandLineEditor myVmOptionsEditor;
+  @SuppressWarnings("FieldCanBeLocal") // Used via reflection at showUi() and disposeResources()
+  private JBLabel myScriptParametersLabel;
+  private RawCommandLineEditor myScriptParametersEditor;
 
   @Nullable private ExternalSystemTaskExecutionSettings myOriginalSettings;
 
@@ -100,9 +103,14 @@
 
     myVmOptionsLabel = new JBLabel(ExternalSystemBundle.message("run.configuration.settings.label.vmoptions"));
     myVmOptionsEditor = new RawCommandLineEditor();
-    myVmOptionsEditor.setDialogCaption(ExternalSystemBundle.message("run.configuration.settings.caption.vmoptions"));
+    myVmOptionsEditor.setDialogCaption(ExternalSystemBundle.message("run.configuration.settings.label.vmoptions"));
     canvas.add(myVmOptionsLabel, ExternalSystemUiUtil.getLabelConstraints(0));
     canvas.add(myVmOptionsEditor, ExternalSystemUiUtil.getFillLineConstraints(0));
+    myScriptParametersLabel = new JBLabel(ExternalSystemBundle.message("run.configuration.settings.label.script.parameters"));
+    myScriptParametersEditor = new RawCommandLineEditor();
+    myScriptParametersEditor.setDialogCaption(ExternalSystemBundle.message("run.configuration.settings.label.script.parameters"));
+    canvas.add(myScriptParametersLabel, ExternalSystemUiUtil.getLabelConstraints(0));
+    canvas.add(myScriptParametersEditor, ExternalSystemUiUtil.getFillLineConstraints(0));
   }
 
   @Override
@@ -110,6 +118,7 @@
     myProjectPathField.setText("");
     myTasksTextField.setText("");
     myVmOptionsEditor.setText("");
+    myScriptParametersEditor.setText("");
     showUi(true);
 
     if (myOriginalSettings == null) {
@@ -123,6 +132,7 @@
     myProjectPathField.setText(path);
     myTasksTextField.setText(StringUtil.join(myOriginalSettings.getTaskNames(), " "));
     myVmOptionsEditor.setText(myOriginalSettings.getVmOptions());
+    myScriptParametersEditor.setText(myOriginalSettings.getScriptParameters());
   }
 
   @Override
@@ -136,7 +146,9 @@
            || !Comparing.equal(normalizePath(myTasksTextField.getText()),
                                normalizePath(StringUtil.join(myOriginalSettings.getTaskNames(), " ")))
            || !Comparing.equal(normalizePath(myVmOptionsEditor.getText()),
-                               normalizePath(myOriginalSettings.getVmOptions()));
+                               normalizePath(myOriginalSettings.getVmOptions()))
+           || !Comparing.equal(normalizePath(myScriptParametersEditor.getText()),
+                               normalizePath(myOriginalSettings.getScriptParameters()));
   }
 
   @Override
@@ -145,15 +157,17 @@
     settings.setExternalProjectPath(projectPath);
     settings.setTaskNames(StringUtil.split(myTasksTextField.getText(), " "));
     settings.setVmOptions(myVmOptionsEditor.getText());
+    settings.setScriptParameters(myScriptParametersEditor.getText());
   }
 
   @Override
   public boolean validate(@NotNull ExternalSystemTaskExecutionSettings settings) throws ConfigurationException {
     String projectPath = myProjectPathField.getText();
     if (myOriginalSettings == null) {
-      throw  new ConfigurationException(String.format(
+      throw new ConfigurationException(String.format(
         "Can't store external task settings into run configuration. Reason: target run configuration is undefined. Tasks: '%s', " +
-        "external project: '%s', vm options: '%s'", myTasksTextField.getText(), projectPath, myVmOptionsEditor.getText()
+        "external project: '%s', vm options: '%s', script parameters: '%s'",
+        myTasksTextField.getText(), projectPath, myVmOptionsEditor.getText(), myScriptParametersEditor.getText()
       ));
     }
     return true;
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/AbstractExternalSystemTask.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/AbstractExternalSystemTask.java
index dae938e..305114c 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/AbstractExternalSystemTask.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/AbstractExternalSystemTask.java
@@ -29,19 +29,18 @@
 
   private final AtomicReference<ExternalSystemTaskState> myState =
     new AtomicReference<ExternalSystemTaskState>(ExternalSystemTaskState.NOT_STARTED);
-  private final AtomicReference<Throwable>               myError = new AtomicReference<Throwable>();
+  private final AtomicReference<Throwable> myError = new AtomicReference<Throwable>();
 
   @NotNull private final transient Project myIdeProject;
 
   @NotNull private final ExternalSystemTaskId myId;
-  @NotNull private final ProjectSystemId      myExternalSystemId;
-  @NotNull private final String               myExternalProjectPath;
+  @NotNull private final ProjectSystemId myExternalSystemId;
+  @NotNull private final String myExternalProjectPath;
 
   protected AbstractExternalSystemTask(@NotNull ProjectSystemId id,
                                        @NotNull ExternalSystemTaskType type,
                                        @NotNull Project project,
-                                       @NotNull String externalProjectPath)
-  {
+                                       @NotNull String externalProjectPath) {
     myExternalSystemId = id;
     myIdeProject = project;
     myId = ExternalSystemTaskId.create(id, type, myIdeProject);
@@ -67,6 +66,10 @@
     myState.set(state);
   }
 
+  protected boolean compareAndSetState(@NotNull ExternalSystemTaskState expect, @NotNull ExternalSystemTaskState update) {
+    return myState.compareAndSet(expect, update);
+  }
+
   @Override
   public Throwable getError() {
     return myError.get();
@@ -114,7 +117,7 @@
       ls = ArrayUtil.append(listeners, adapter);
     }
     else {
-      ls = new ExternalSystemTaskNotificationListener[] { adapter };
+      ls = new ExternalSystemTaskNotificationListener[]{adapter};
     }
 
     execute(ls);
@@ -122,30 +125,35 @@
 
   @Override
   public void execute(@NotNull ExternalSystemTaskNotificationListener... listeners) {
+    if (!compareAndSetState(ExternalSystemTaskState.NOT_STARTED, ExternalSystemTaskState.IN_PROGRESS)) return;
+
     ExternalSystemProgressNotificationManager progressManager = ServiceManager.getService(ExternalSystemProgressNotificationManager.class);
     for (ExternalSystemTaskNotificationListener listener : listeners) {
       progressManager.addNotificationListener(getId(), listener);
     }
+    ExternalSystemProcessingManager processingManager = ServiceManager.getService(ExternalSystemProcessingManager.class);
     try {
+      processingManager.add(this);
       doExecute();
+      setState(ExternalSystemTaskState.FINISHED);
     }
     catch (Throwable e) {
       setState(ExternalSystemTaskState.FAILED);
       myError.set(e);
       LOG.warn(e);
-
     }
     finally {
       for (ExternalSystemTaskNotificationListener listener : listeners) {
         progressManager.removeNotificationListener(listener);
       }
+      processingManager.release(getId());
     }
   }
 
   protected abstract void doExecute() throws Exception;
 
   @Override
-  public void cancel(@NotNull final ProgressIndicator indicator, @NotNull ExternalSystemTaskNotificationListener... listeners) {
+  public boolean cancel(@NotNull final ProgressIndicator indicator, @NotNull ExternalSystemTaskNotificationListener... listeners) {
     indicator.setIndeterminate(true);
     ExternalSystemTaskNotificationListenerAdapter adapter = new ExternalSystemTaskNotificationListenerAdapter() {
       @Override
@@ -158,23 +166,32 @@
       ls = ArrayUtil.append(listeners, adapter);
     }
     else {
-      ls = new ExternalSystemTaskNotificationListener[] { adapter };
+      ls = new ExternalSystemTaskNotificationListener[]{adapter};
     }
 
-    cancel(ls);
+    return cancel(ls);
   }
 
   @Override
-  public void cancel(@NotNull ExternalSystemTaskNotificationListener... listeners) {
+  public boolean cancel(@NotNull ExternalSystemTaskNotificationListener... listeners) {
+    ExternalSystemTaskState currentTaskState = getState();
+    if (currentTaskState.isStopped()) return true;
+
     ExternalSystemProgressNotificationManager progressManager = ServiceManager.getService(ExternalSystemProgressNotificationManager.class);
     for (ExternalSystemTaskNotificationListener listener : listeners) {
       progressManager.addNotificationListener(getId(), listener);
     }
+
+    if (!compareAndSetState(currentTaskState, ExternalSystemTaskState.CANCELING)) return false;
+
+    boolean result = false;
     try {
-      doCancel();
+      result = doCancel();
+      setState(result ? ExternalSystemTaskState.CANCELED : ExternalSystemTaskState.CANCELLATION_FAILED);
+      return result;
     }
     catch (Throwable e) {
-      setState(ExternalSystemTaskState.FAILED);
+      setState(ExternalSystemTaskState.CANCELLATION_FAILED);
       myError.set(e);
       LOG.warn(e);
     }
@@ -183,9 +200,10 @@
         progressManager.removeNotificationListener(listener);
       }
     }
+    return result;
   }
 
-  protected abstract void doCancel() throws Exception;
+  protected abstract boolean doCancel() throws Exception;
 
 
   @NotNull
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemExecuteTaskTask.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemExecuteTaskTask.java
index 8b5cb63..f44bc55 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemExecuteTaskTask.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemExecuteTaskTask.java
@@ -19,7 +19,6 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.execution.ExternalTaskPojo;
 import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
-import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskState;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType;
 import com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager;
 import com.intellij.openapi.externalSystem.service.RemoteExternalSystemFacade;
@@ -27,7 +26,9 @@
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
 import com.intellij.openapi.project.Project;
 import com.intellij.util.Function;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
+import com.intellij.util.execution.ParametersListUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -49,17 +50,19 @@
 
   @NotNull private final List<ExternalTaskPojo> myTasksToExecute;
   @Nullable private final String myVmOptions;
+  @Nullable private String myScriptParameters;
   @Nullable private final String myDebuggerSetup;
 
   public ExternalSystemExecuteTaskTask(@NotNull ProjectSystemId externalSystemId,
                                        @NotNull Project project,
                                        @NotNull List<ExternalTaskPojo> tasksToExecute,
                                        @Nullable String vmOptions,
-                                       @Nullable String debuggerSetup) throws IllegalArgumentException
-  {
+                                       @Nullable String scriptParameters,
+                                       @Nullable String debuggerSetup) throws IllegalArgumentException {
     super(externalSystemId, ExternalSystemTaskType.EXECUTE_TASK, project, getLinkedExternalProjectPath(tasksToExecute));
     myTasksToExecute = tasksToExecute;
     myVmOptions = vmOptions;
+    myScriptParameters = scriptParameters;
     myDebuggerSetup = debuggerSetup;
   }
 
@@ -80,7 +83,8 @@
           "but they are not (at least two different projects detected - '%s' and '%s'). Tasks: %s",
           result,
           task.getLinkedExternalProjectPath(),
-          tasks));
+          tasks
+        ));
       }
     }
     assert result != null;
@@ -98,26 +102,22 @@
     RemoteExternalSystemTaskManager taskManager = facade.getTaskManager();
     List<String> taskNames = ContainerUtilRt.map2List(myTasksToExecute, MAPPER);
 
-    setState(ExternalSystemTaskState.IN_PROGRESS);
-    try {
-      taskManager.executeTasks(getId(), taskNames, getExternalProjectPath(), settings, myVmOptions, myDebuggerSetup);
-    }
-    finally {
-      setState(ExternalSystemTaskState.FINISHED);
-    }
+    final List<String> vmOptions = parseCmdParameters(myVmOptions);
+    final List<String> scriptParametersList = parseCmdParameters(myScriptParameters);
+
+    taskManager.executeTasks(getId(), taskNames, getExternalProjectPath(), settings, vmOptions, scriptParametersList, myDebuggerSetup);
   }
 
   @Override
-  protected void doCancel() throws Exception {
+  protected boolean doCancel() throws Exception {
     final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
     RemoteExternalSystemFacade facade = manager.getFacade(getIdeProject(), getExternalProjectPath(), getExternalSystemId());
     RemoteExternalSystemTaskManager taskManager = facade.getTaskManager();
-    setState(ExternalSystemTaskState.CANCELING);
-    try {
-      taskManager.cancelTask(getId());
-    }
-    finally {
-      setState(ExternalSystemTaskState.CANCELED);
-    }
+
+    return taskManager.cancelTask(getId());
+  }
+
+  private static List<String> parseCmdParameters(@Nullable String cmdArgsLine) {
+    return cmdArgsLine != null ? ParametersListUtil.parse(cmdArgsLine) : ContainerUtil.<String>newArrayList();
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemProcessingManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemProcessingManager.java
index 999b201..7e103cf 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemProcessingManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemProcessingManager.java
@@ -3,10 +3,7 @@
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
-import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
-import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent;
-import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
-import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType;
+import com.intellij.openapi.externalSystem.model.task.*;
 import com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager;
 import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager;
 import com.intellij.openapi.project.Project;
@@ -14,6 +11,7 @@
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.Map;
 import java.util.concurrent.ConcurrentMap;
@@ -45,6 +43,7 @@
   private static final long TOO_LONG_EXECUTION_MS = TimeUnit.SECONDS.toMillis(10);
 
   @NotNull private final ConcurrentMap<ExternalSystemTaskId, Long> myTasksInProgress = ContainerUtil.newConcurrentMap();
+  @NotNull private final ConcurrentMap<ExternalSystemTaskId, ExternalSystemTask> myTasksDetails = ContainerUtil.newConcurrentMap();
   @NotNull private final Alarm                                     myAlarm           = new Alarm(Alarm.ThreadToUse.SHARED_THREAD);
 
   @NotNull private final ExternalSystemFacadeManager               myFacadeManager;
@@ -85,6 +84,32 @@
     return false;
   }
 
+  @Nullable
+  public ExternalSystemTask findTask(@NotNull ExternalSystemTaskType type,
+                                     @NotNull ProjectSystemId projectSystemId,
+                                     @NotNull final String externalProjectPath) {
+    for(ExternalSystemTask task : myTasksDetails.values()) {
+      if(task instanceof AbstractExternalSystemTask) {
+        AbstractExternalSystemTask externalSystemTask = (AbstractExternalSystemTask)task;
+        if(externalSystemTask.getId().getType() == type &&
+           externalSystemTask.getExternalSystemId().getId().equals(projectSystemId.getId()) &&
+           externalSystemTask.getExternalProjectPath().equals(externalProjectPath)){
+          return task;
+        }
+      }
+    }
+
+    return null;
+  }
+
+  public void add(@NotNull ExternalSystemTask task) {
+    myTasksDetails.put(task.getId(), task);
+  }
+
+  public void release(@NotNull ExternalSystemTaskId id) {
+    myTasksDetails.remove(id);
+  }
+
   @Override
   public void onQueued(@NotNull ExternalSystemTaskId id) {
     myTasksInProgress.put(id, System.currentTimeMillis() + TOO_LONG_EXECUTION_MS);
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemResolveProjectTask.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemResolveProjectTask.java
index fe0d546..42108cb 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemResolveProjectTask.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemResolveProjectTask.java
@@ -5,7 +5,6 @@
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
-import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskState;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType;
 import com.intellij.openapi.externalSystem.service.ExternalSystemFacadeManager;
 import com.intellij.openapi.externalSystem.service.remote.RemoteExternalSystemProjectResolver;
@@ -19,7 +18,7 @@
 
 /**
  * Thread-safe.
- * 
+ *
  * @author Denis Zhdanov
  * @since 1/24/12 7:21 AM
  */
@@ -27,14 +26,13 @@
 
   private final AtomicReference<DataNode<ProjectData>> myExternalProject = new AtomicReference<DataNode<ProjectData>>();
 
-  @NotNull private final String  myProjectPath;
-  private final          boolean myIsPreviewMode;
+  @NotNull private final String myProjectPath;
+  private final boolean myIsPreviewMode;
 
   public ExternalSystemResolveProjectTask(@NotNull ProjectSystemId externalSystemId,
                                           @NotNull Project project,
                                           @NotNull String projectPath,
-                                          boolean isPreviewMode)
-  {
+                                          boolean isPreviewMode) {
     super(externalSystemId, ExternalSystemTaskType.RESOLVE_PROJECT, project, projectPath);
     myProjectPath = projectPath;
     myIsPreviewMode = isPreviewMode;
@@ -45,35 +43,22 @@
     final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
     Project ideProject = getIdeProject();
     RemoteExternalSystemProjectResolver resolver = manager.getFacade(ideProject, myProjectPath, getExternalSystemId()).getResolver();
-    
-    setState(ExternalSystemTaskState.IN_PROGRESS);
-    try {
-      ExternalSystemExecutionSettings settings = ExternalSystemApiUtil
-        .getExecutionSettings(ideProject, myProjectPath, getExternalSystemId());
-      DataNode<ProjectData> project = resolver.resolveProjectInfo(getId(), myProjectPath, myIsPreviewMode, settings);
+    ExternalSystemExecutionSettings settings = ExternalSystemApiUtil.getExecutionSettings(ideProject, myProjectPath, getExternalSystemId());
 
-      if (project == null) {
-        return;
-      }
-      myExternalProject.set(project);
+    DataNode<ProjectData> project = resolver.resolveProjectInfo(getId(), myProjectPath, myIsPreviewMode, settings);
+
+    if (project == null) {
+      return;
     }
-    finally {
-      setState(ExternalSystemTaskState.FINISHED);
-    }
+    myExternalProject.set(project);
   }
 
-  protected void doCancel() throws Exception {
+  protected boolean doCancel() throws Exception {
     final ExternalSystemFacadeManager manager = ServiceManager.getService(ExternalSystemFacadeManager.class);
     Project ideProject = getIdeProject();
     RemoteExternalSystemProjectResolver resolver = manager.getFacade(ideProject, myProjectPath, getExternalSystemId()).getResolver();
 
-    setState(ExternalSystemTaskState.CANCELING);
-    try {
-      resolver.cancelTask(getId());
-    }
-    finally {
-      setState(ExternalSystemTaskState.CANCELED);
-    }
+    return resolver.cancelTask(getId());
   }
 
   @Nullable
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemTaskAware.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemTaskAware.java
index 7ecc0c6..56a13de 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemTaskAware.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/internal/ExternalSystemTaskAware.java
@@ -35,7 +35,7 @@
    *            <code>false</code> otherwise
    * @throws RemoteException      as required by RMI
    */
-  void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException;
+  boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException;
 
   /**
    * Allows to ask current service for all tasks being executed at the moment.  
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ProjectStructureHelper.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ProjectStructureHelper.java
index 54be233..79b362e1 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ProjectStructureHelper.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/ProjectStructureHelper.java
@@ -9,6 +9,7 @@
 import com.intellij.openapi.roots.*;
 import com.intellij.openapi.roots.libraries.Library;
 import com.intellij.openapi.roots.libraries.LibraryTable;
+import com.intellij.openapi.util.io.FileUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -28,7 +29,7 @@
 
   @Nullable
   public Module findIdeModule(@NotNull ModuleData module, @NotNull Project ideProject) {
-    return findIdeModule(module.getName(), ideProject);
+    return findIdeModule(module.getInternalName(), ideProject);
   }
 
   @Nullable
@@ -72,7 +73,7 @@
     for (OrderEntry entry : model.getOrderEntries()) {
       if (entry instanceof ModuleOrderEntry) {
         ModuleOrderEntry candidate = (ModuleOrderEntry)entry;
-        if (dependency.getName().equals(candidate.getModuleName()) &&
+        if (dependency.getInternalName().equals(candidate.getModuleName()) &&
             dependency.getScope().equals(candidate.getScope())) {
           return candidate;
         }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java
index 15300f0..bc7cb8d 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/autoimport/ExternalSystemAutoImporter.java
@@ -25,6 +25,10 @@
 import com.intellij.openapi.externalSystem.model.DataNode;
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTask;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskState;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType;
+import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager;
 import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback;
 import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager;
 import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
@@ -51,7 +55,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
-import java.util.concurrent.ConcurrentMap;
+import java.util.concurrent.*;
 import java.util.concurrent.locks.Lock;
 import java.util.concurrent.locks.ReadWriteLock;
 import java.util.concurrent.locks.ReentrantReadWriteLock;
@@ -332,11 +336,29 @@
       documentLock.unlock();
     }
 
+    boolean scheduleRefresh = false;
+    ExternalSystemProcessingManager processingManager = ServiceManager.getService(ExternalSystemProcessingManager.class);
     for (Map.Entry<ProjectSystemId, Set<String>> entry : copy.entrySet()) {
       for (String path : entry.getValue()) {
-        ExternalSystemUtil.refreshProject(myProject, entry.getKey(), path, myRefreshCallback, false, ProgressExecutionMode.IN_BACKGROUND_ASYNC, false);
+        final ExternalSystemTask resolveTask = processingManager.findTask(ExternalSystemTaskType.RESOLVE_PROJECT, entry.getKey(), path);
+        final ExternalSystemTaskState taskState = resolveTask == null ? null : resolveTask.getState();
+        if (taskState == null || taskState.isStopped() ||
+            (taskState == ExternalSystemTaskState.IN_PROGRESS && resolveTask.cancel())) {
+          ExternalSystemUtil.refreshProject(
+            myProject, entry.getKey(), path, myRefreshCallback, false, ProgressExecutionMode.IN_BACKGROUND_ASYNC, false);
+        }
+        else if (taskState != ExternalSystemTaskState.NOT_STARTED) {
+          // re-schedule to wait for the project import task end
+          scheduleRefresh = true;
+          addPath(entry.getKey(), path);
+        }
       }
     }
+
+    if (scheduleRefresh) {
+      myVfsAlarm.cancelAllRequests();
+      myVfsAlarm.addRequest(myFilesRequest, ExternalSystemConstants.AUTO_IMPORT_DELAY_MILLIS);
+    }
   }
   
   private static class MyEntry {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
index ad37b00..e0c5225 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ContentRootDataService.java
@@ -4,10 +4,13 @@
 import com.intellij.openapi.externalSystem.model.DataNode;
 import com.intellij.openapi.externalSystem.model.Key;
 import com.intellij.openapi.externalSystem.model.ProjectKeys;
+import com.intellij.openapi.externalSystem.model.ProjectSystemId;
 import com.intellij.openapi.externalSystem.model.project.ContentRootData;
 import com.intellij.openapi.externalSystem.model.project.ExternalSystemSourceType;
 import com.intellij.openapi.externalSystem.model.project.ModuleData;
 import com.intellij.openapi.externalSystem.service.project.ProjectStructureHelper;
+import com.intellij.openapi.externalSystem.settings.AbstractExternalSystemSettings;
+import com.intellij.openapi.externalSystem.settings.ExternalProjectSettings;
 import com.intellij.openapi.externalSystem.util.DisposeAwareProjectChange;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
 import com.intellij.openapi.externalSystem.util.ExternalSystemConstants;
@@ -95,30 +98,45 @@
         for(ContentEntry contentEntry : contentEntries) {
           contentEntriesMap.put(contentEntry.getUrl(), contentEntry);
         }
+
+        boolean createEmptyContentRootDirectories = false;
+        if (!datas.isEmpty()) {
+          ProjectSystemId projectSystemId = datas.iterator().next().getData().getOwner();
+          AbstractExternalSystemSettings externalSystemSettings =
+            ExternalSystemApiUtil.getSettings(module.getProject(), projectSystemId);
+
+          String path = module.getOptionValue(ExternalSystemConstants.ROOT_PROJECT_PATH_KEY);
+          if (path != null) {
+            ExternalProjectSettings projectSettings = externalSystemSettings.getLinkedProjectSettings(path);
+            createEmptyContentRootDirectories = projectSettings != null && projectSettings.isCreateEmptyContentRootDirectories();
+          }
+        }
+
         try {
           for (final DataNode<ContentRootData> data : datas) {
             final ContentRootData contentRoot = data.getData();
+
             final ContentEntry contentEntry = findOrCreateContentRoot(model, contentRoot.getRootPath());
             contentEntry.clearExcludeFolders();
             contentEntry.clearSourceFolders();
             LOG.info(String.format("Importing content root '%s' for module '%s'", contentRoot.getRootPath(), module.getName()));
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.SOURCE)) {
-              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, false);
+              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, false, createEmptyContentRootDirectories);
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST)) {
-              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, false);
+              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, false, createEmptyContentRootDirectories);
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.RESOURCE)) {
-              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.RESOURCE, false);
+              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.RESOURCE, false, createEmptyContentRootDirectories);
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST_RESOURCE)) {
-              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.TEST_RESOURCE, false);
+              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaResourceRootType.TEST_RESOURCE, false, createEmptyContentRootDirectories);
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.SOURCE_GENERATED)) {
-              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, true);
+              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.SOURCE, true, createEmptyContentRootDirectories);
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.TEST_GENERATED)) {
-              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, true);
+              createSourceRootIfAbsent(contentEntry, path, module.getName(), JavaSourceRootType.TEST_SOURCE, true, createEmptyContentRootDirectories);
             }
             for (String path : contentRoot.getPaths(ExternalSystemSourceType.EXCLUDED)) {
               createExcludedRootIfAbsent(contentEntry, path, module.getName());
@@ -154,7 +172,7 @@
 
   private static void createSourceRootIfAbsent(
     @NotNull ContentEntry entry, @NotNull String path, @NotNull String moduleName,
-    @NotNull JpsModuleSourceRootType sourceRootType, boolean generated) {
+    @NotNull JpsModuleSourceRootType sourceRootType, boolean generated, boolean createEmptyContentRootDirectories) {
     List<SourceFolder> folders = entry.getSourceFolders(sourceRootType);
     for (SourceFolder folder : folders) {
       VirtualFile file = folder.getFile();
@@ -173,11 +191,13 @@
         properties.setForGeneratedSources(true);
       }
     }
-    try {
-      VfsUtil.createDirectoryIfMissing(path);
-    }
-    catch (IOException e) {
-      LOG.warn(String.format("Unable to create directory for the path: %s", path), e);
+    if(createEmptyContentRootDirectories) {
+      try {
+        VfsUtil.createDirectoryIfMissing(path);
+      }
+      catch (IOException e) {
+        LOG.warn(String.format("Unable to create directory for the path: %s", path), e);
+      }
     }
   }
 
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java
index b37452e..d04d728 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDataService.java
@@ -82,7 +82,7 @@
       syncPaths(toImport, library, project, synchronous);
       return;
     }
-    importLibrary(ExternalSystemApiUtil.getLibraryName(toImport), libraryFiles, project, synchronous);
+    importLibrary(toImport.getInternalName(), libraryFiles, project, synchronous);
   }
 
   @NotNull
@@ -227,7 +227,7 @@
           for (Map.Entry<OrderRootType, Set<String>> entry : toAdd.entrySet()) {
             Map<OrderRootType, Collection<File>> roots = ContainerUtilRt.newHashMap();
             roots.put(entry.getKey(), ContainerUtil.map(entry.getValue(), PATH_TO_FILE));
-            registerPaths(roots, model, ExternalSystemApiUtil.getLibraryName(externalLibrary));
+            registerPaths(roots, model, externalLibrary.getInternalName());
           }
         }
         finally {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java
index f15eb00..05c1d72 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/LibraryDependencyDataService.java
@@ -112,7 +112,7 @@
         // The trick is that we should perform module settings modification inside try/finally block against target root model.
         // That means that we need to prepare all necessary data, obtain a model and modify it as necessary.
         Map<Set<String>/* library paths */, LibraryDependencyData> moduleLibrariesToImport = ContainerUtilRt.newHashMap();
-        Map<String/* library name */, LibraryDependencyData> projectLibrariesToImport = ContainerUtilRt.newHashMap();
+        Map<String/* library name + scope */, LibraryDependencyData> projectLibrariesToImport = ContainerUtilRt.newHashMap();
         Set<LibraryDependencyData> toImport = ContainerUtilRt.newLinkedHashSet();
         
         boolean hasUnresolved = false;
@@ -132,7 +132,7 @@
               }
               break;
             case PROJECT:
-              projectLibrariesToImport.put(ExternalSystemApiUtil.getLibraryName(libraryData), dependencyData);
+              projectLibrariesToImport.put(libraryData.getInternalName() + dependencyData.getScope().name(), dependencyData);
               toImport.add(dependencyData);
           }
         }
@@ -164,7 +164,7 @@
   {
     for (LibraryDependencyData dependencyData : toImport) {
       LibraryData libraryData = dependencyData.getTarget();
-      String libraryName = ExternalSystemApiUtil.getLibraryName(libraryData);
+      String libraryName = libraryData.getInternalName();
       switch (dependencyData.getLevel()) {
         case MODULE:
           @SuppressWarnings("ConstantConditions") Library moduleLib = moduleLibraryTable.createLibrary(libraryName);
@@ -224,8 +224,8 @@
       else if (entry instanceof LibraryOrderEntry) {
         final LibraryOrderEntry libraryOrderEntry = (LibraryOrderEntry)entry;
         final String libraryName = libraryOrderEntry.getLibraryName();
-        final LibraryDependencyData existing = projectLibrariesToImport.remove(libraryName);
-        if (existing != null && libraryOrderEntry.getScope() == existing.getScope()) {
+        final LibraryDependencyData existing = projectLibrariesToImport.remove(libraryName + libraryOrderEntry.getScope().name());
+        if (existing != null) {
           toImport.remove(existing);
         }
         else if (!hasUnresolvedLibraries) {
@@ -248,7 +248,7 @@
       if (dependencyData.getLevel() != LibraryLevel.PROJECT) {
         continue;
       }
-      final Library library = libraryTable.getLibraryByName(ExternalSystemApiUtil.getLibraryName(dependencyData));
+      final Library library = libraryTable.getLibraryByName(dependencyData.getInternalName());
       if (library == null) {
         DataNode<ProjectData> projectNode = dataNode.getDataNode(ProjectKeys.PROJECT);
         if (projectNode != null) {
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java
index 5a78201..f8e368a 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ModuleDependencyDataService.java
@@ -93,7 +93,7 @@
       @Override
       public void execute() {
         ModuleRootManager moduleRootManager = ModuleRootManager.getInstance(module);
-        Map<Pair<String /* dependency module name */, /* dependency module scope */DependencyScope> , ModuleOrderEntry> toRemove = ContainerUtilRt.newHashMap();
+        Map<Pair<String /* dependency module internal name */, /* dependency module scope */DependencyScope> , ModuleOrderEntry> toRemove = ContainerUtilRt.newHashMap();
         for (OrderEntry entry : moduleRootManager.getOrderEntries()) {
           if (entry instanceof ModuleOrderEntry) {
             ModuleOrderEntry e = (ModuleOrderEntry)entry;
@@ -105,8 +105,8 @@
         try {
           for (DataNode<ModuleDependencyData> dependencyNode : toImport) {
             final ModuleDependencyData dependencyData = dependencyNode.getData();
-            toRemove.remove(Pair.create(dependencyData.getName(), dependencyData.getScope()));
-            final String moduleName = dependencyData.getName();
+            toRemove.remove(Pair.create(dependencyData.getInternalName(), dependencyData.getScope()));
+            final String moduleName = dependencyData.getInternalName();
             Module ideDependencyModule = myProjectStructureHelper.findIdeModule(moduleName, module.getProject());
             if (ideDependencyModule == null) {
               DataNode<ProjectData> projectNode = dependencyNode.getDataNode(ProjectKeys.PROJECT);
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java
index b6f564b..34c18a9 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/project/manage/ProjectDataServiceImpl.java
@@ -52,8 +52,8 @@
       return;
     }
     
-    if (!project.getName().equals(projectData.getName())) {
-      renameProject(projectData.getName(), projectData.getOwner(), project, synchronous);
+    if (!project.getName().equals(projectData.getInternalName())) {
+      renameProject(projectData.getInternalName(), projectData.getOwner(), project, synchronous);
     }
   }
 
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 23ccbbb..8560aca 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
@@ -375,7 +375,7 @@
       assert false;
       return;
     }
-    context.setProjectName(myExternalProjectNode.getData().getName());
+    context.setProjectName(myExternalProjectNode.getData().getInternalName());
     context.setProjectFileDirectory(myExternalProjectNode.getData().getIdeProjectFileDirectoryPath());
     applyExtraSettings(context);
   }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolver.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolver.java
index 2e5ce64..818bbdb 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolver.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolver.java
@@ -65,7 +65,8 @@
     }
 
     @Override
-    public void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
+    public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
+      return false;
     }
 
     @NotNull
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolverImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolverImpl.java
index 2bc3371..8b57b36 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolverImpl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemProjectResolverImpl.java
@@ -43,10 +43,9 @@
     });
   }
 
-  @Nullable
   @Override
-  public void cancelTask(@NotNull final ExternalSystemTaskId id)
+  public boolean cancelTask(@NotNull final ExternalSystemTaskId id)
     throws ExternalSystemException, IllegalArgumentException, IllegalStateException {
-    // canceling of the project resolving does not support yet
+    return myDelegate.cancelTask(id, getNotificationListener());
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManager.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManager.java
index 6f9d4e3b5..ab3f6c5 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManager.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManager.java
@@ -45,14 +45,16 @@
                                @NotNull List<String> taskNames,
                                @NotNull String projectPath,
                                @Nullable ExternalSystemExecutionSettings settings,
-                               @Nullable String vmOptions,
+                               @NotNull List<String> vmOptions,
+                               @NotNull List<String> scriptParameters,
                                @Nullable String debuggerSetup) throws RemoteException, ExternalSystemException
       {
       }
 
       @Override
-      public void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException
+      public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException
       {
+        return false;
       }
 
       @Override
@@ -79,8 +81,9 @@
                     @NotNull List<String> taskNames,
                     @NotNull String projectPath,
                     @Nullable S settings,
-                    @Nullable String vmOptions,
+                    @NotNull List<String> vmOptions,
+                    @NotNull List<String> scriptParameters,
                     @Nullable String debuggerSetup) throws RemoteException, ExternalSystemException;
 
-  void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException;
+  boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException;
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManagerImpl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManagerImpl.java
index 4e5a45e..566695a5 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManagerImpl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/RemoteExternalSystemTaskManagerImpl.java
@@ -18,8 +18,10 @@
 import com.intellij.openapi.externalSystem.model.ExternalSystemException;
 import com.intellij.openapi.externalSystem.model.settings.ExternalSystemExecutionSettings;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
+import com.intellij.openapi.externalSystem.task.AbstractExternalSystemTaskManager;
 import com.intellij.openapi.externalSystem.task.ExternalSystemTaskManager;
 import com.intellij.util.Producer;
+import com.intellij.util.execution.ParametersListUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -45,22 +47,28 @@
                            @NotNull final List<String> taskNames,
                            @NotNull final String projectPath,
                            @Nullable final S settings,
-                           @Nullable final String vmOptions,
+                           @NotNull final List<String> vmOptions,
+                           @NotNull final List<String> scriptParameters,
                            @Nullable final String debuggerSetup) throws RemoteException, ExternalSystemException
   {
     execute(id, new Producer<Object>() {
       @Nullable
       @Override
       public Object produce() {
-        myDelegate.executeTasks(id, taskNames, projectPath, settings, vmOptions, debuggerSetup, getNotificationListener());
+        if(myDelegate instanceof AbstractExternalSystemTaskManager) {
+          ((AbstractExternalSystemTaskManager<S>)myDelegate)
+            .executeTasks(id, taskNames, projectPath, settings, vmOptions, scriptParameters, debuggerSetup, getNotificationListener());
+        } else {
+          myDelegate.executeTasks(id, taskNames, projectPath, settings, ParametersListUtil.join(vmOptions), debuggerSetup, getNotificationListener());
+        }
         return null;
       }
     });
   }
 
   @Override
-  public void cancelTask(@NotNull final ExternalSystemTaskId id) throws RemoteException, ExternalSystemException
+  public boolean cancelTask(@NotNull final ExternalSystemTaskId id) throws RemoteException, ExternalSystemException
   {
-    myDelegate.cancelTask(id, getNotificationListener());
+    return myDelegate.cancelTask(id, getNotificationListener());
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemFacadeWrapper.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemFacadeWrapper.java
index 231bf06..f5bb19b 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemFacadeWrapper.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemFacadeWrapper.java
@@ -74,7 +74,7 @@
   }
 
   @Override
-  public void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
-    myDelegate.cancelTask(id);
+  public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException {
+    return myDelegate.cancelTask(id);
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemProjectResolverWrapper.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemProjectResolverWrapper.java
index 5c1262b..ec2883a 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemProjectResolverWrapper.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemProjectResolverWrapper.java
@@ -64,11 +64,11 @@
   }
 
   @Override
-  public void cancelTask(@NotNull ExternalSystemTaskId id)
+  public boolean cancelTask(@NotNull ExternalSystemTaskId id)
     throws ExternalSystemException, IllegalArgumentException, IllegalStateException, RemoteException {
     myProgressManager.onQueued(id);
     try {
-      getDelegate().cancelTask(id);
+      return getDelegate().cancelTask(id);
     }
     finally {
       myProgressManager.onEnd(id);
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemTaskManagerWrapper.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemTaskManagerWrapper.java
index 5c6adde..281bc8e 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemTaskManagerWrapper.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/remote/wrapper/ExternalSystemTaskManagerWrapper.java
@@ -49,12 +49,13 @@
                            @NotNull List<String> taskNames,
                            @NotNull String projectPath,
                            @Nullable S settings,
-                           @Nullable String vmOptions,
+                           @NotNull List<String> vmOptions,
+                           @NotNull List<String> scriptParameters,
                            @Nullable String debuggerSetup) throws RemoteException, ExternalSystemException
   {
     myProgressManager.onQueued(id);
     try {
-      getDelegate().executeTasks(id, taskNames, projectPath, settings, vmOptions, debuggerSetup);
+      getDelegate().executeTasks(id, taskNames, projectPath, settings, vmOptions, scriptParameters, debuggerSetup);
     }
     catch (ExternalSystemException e) {
       myProgressManager.onFailure(id, e);
@@ -70,11 +71,11 @@
   }
 
   @Override
-  public void cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException
+  public boolean cancelTask(@NotNull ExternalSystemTaskId id) throws RemoteException, ExternalSystemException
   {
     myProgressManager.onQueued(id);
     try {
-      getDelegate().cancelTask(id);
+      return getDelegate().cancelTask(id);
     }
     finally {
       myProgressManager.onEnd(id);
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java
index a7d09eb..2bcfde8 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalProjectSettingsControl.java
@@ -37,6 +37,7 @@
   @NotNull private S myInitialSettings;
 
   private JBCheckBox myUseAutoImportBox;
+  private JBCheckBox myCreateEmptyContentRootDirectoriesBox;
   private boolean myHideUseAutoImportBox;
 
   protected AbstractExternalProjectSettingsControl(@NotNull S initialSettings) {
@@ -57,13 +58,18 @@
     myUseAutoImportBox = new JBCheckBox(ExternalSystemBundle.message("settings.label.use.auto.import"));
     myUseAutoImportBox.setVisible(!myHideUseAutoImportBox);
     canvas.add(myUseAutoImportBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
+    myCreateEmptyContentRootDirectoriesBox =
+      new JBCheckBox(ExternalSystemBundle.message("settings.label.create.empty.content.root.directories"));
+    canvas.add(myCreateEmptyContentRootDirectoriesBox, ExternalSystemUiUtil.getFillLineConstraints(indentLevel));
     fillExtraControls(canvas, indentLevel); 
   }
   
   protected abstract void fillExtraControls(@NotNull PaintAwarePanel content, int indentLevel);
 
   public boolean isModified() {
-    return myUseAutoImportBox.isSelected() != getInitialSettings().isUseAutoImport() || isExtraSettingModified();
+    return myUseAutoImportBox.isSelected() != getInitialSettings().isUseAutoImport()
+           || myCreateEmptyContentRootDirectoriesBox.isSelected() != getInitialSettings().isCreateEmptyContentRootDirectories()
+           || isExtraSettingModified();
   }
 
   protected abstract boolean isExtraSettingModified();
@@ -74,6 +80,7 @@
 
   public void reset(boolean isDefaultModuleCreation) {
     myUseAutoImportBox.setSelected(getInitialSettings().isUseAutoImport());
+    myCreateEmptyContentRootDirectoriesBox.setSelected(getInitialSettings().isCreateEmptyContentRootDirectories());
     resetExtraSettings(isDefaultModuleCreation);
   }
 
@@ -82,7 +89,7 @@
   @Override
   public void apply(@NotNull S settings) {
     settings.setUseAutoImport(myUseAutoImportBox.isSelected());
-    myInitialSettings.setUseAutoImport(myUseAutoImportBox.isSelected());
+    settings.setCreateEmptyContentRootDirectories(myCreateEmptyContentRootDirectoriesBox.isSelected());
     if (myInitialSettings.getExternalProjectPath() != null) {
       settings.setExternalProjectPath(myInitialSettings.getExternalProjectPath());
     }
@@ -99,4 +106,12 @@
   public void showUi(boolean show) {
     ExternalSystemUiUtil.showUi(this, show);
   }
+
+  public void updateInitialSettings() {
+    myInitialSettings.setUseAutoImport(myUseAutoImportBox.isSelected());
+    myInitialSettings.setCreateEmptyContentRootDirectories(myCreateEmptyContentRootDirectoriesBox.isSelected());
+    updateInitialExtraSettings();
+  }
+
+  protected void updateInitialExtraSettings(){}
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java
index e1efe0a..b996f4d 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/settings/AbstractExternalSystemConfigurable.java
@@ -233,6 +233,11 @@
         projectSettings.add(s);
       }
       systemSettings.setLinkedProjectsSettings(projectSettings);
+      for (ExternalSystemSettingsControl<ProjectSettings> control : myProjectSettingsControls) {
+        if(control instanceof AbstractExternalProjectSettingsControl){
+          AbstractExternalProjectSettingsControl.class.cast(control).updateInitialSettings();
+        }
+      }
       if (mySystemSettingsControl != null) {
         mySystemSettingsControl.apply(systemSettings);
       }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java
index 3ee91ab..1282862 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/service/task/ui/ExternalSystemTasksTree.java
@@ -16,6 +16,7 @@
 package com.intellij.openapi.externalSystem.service.task.ui;
 
 import com.intellij.openapi.externalSystem.model.ProjectSystemId;
+import com.intellij.openapi.externalSystem.model.execution.ExternalSystemTaskExecutionSettings;
 import com.intellij.openapi.externalSystem.model.execution.ExternalTaskExecutionInfo;
 import com.intellij.openapi.externalSystem.util.ExternalSystemUtil;
 import com.intellij.openapi.project.Project;
@@ -23,6 +24,7 @@
 import com.intellij.ui.treeStructure.Tree;
 import com.intellij.util.Alarm;
 import com.intellij.util.Producer;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.ui.tree.TreeModelAdapter;
 import org.jetbrains.annotations.NotNull;
@@ -52,12 +54,12 @@
       return o2.getPathCount() - o1.getPathCount();
     }
   };
-  
+
   @NotNull private final Alarm myCollapseStateAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
 
   /** Holds list of paths which 'expand/collapse' state should be restored. */
   @NotNull private final Set<TreePath> myPathsToProcessCollapseState = ContainerUtilRt.newHashSet();
-  
+
   @NotNull private final Map<String/*tree path*/, Boolean/*expanded*/> myExpandedStateHolder;
 
   private boolean mySuppressCollapseTracking;
@@ -86,7 +88,7 @@
         }
       }
     });
-    
+
     model.addTreeModelListener(new TreeModelAdapter() {
       @Override
       public void treeStructureChanged(TreeModelEvent e) {
@@ -183,16 +185,39 @@
   @Nullable
   @Override
   public ExternalTaskExecutionInfo produce() {
-    TreePath selectionPath = getLeadSelectionPath();
-    if (selectionPath == null) {
-      return null;
-    }
-    Object component = selectionPath.getLastPathComponent();
-    if (!(component instanceof ExternalSystemNode)) {
+    TreePath[] selectionPaths = getSelectionPaths();
+    if (selectionPaths == null || selectionPaths.length == 0) {
       return null;
     }
 
-    Object element = ((ExternalSystemNode)component).getDescriptor().getElement();
-    return element instanceof ExternalTaskExecutionInfo ? ((ExternalTaskExecutionInfo)element) : null;
+    Map<String, ExternalTaskExecutionInfo> map = ContainerUtil.newHashMap();
+    for (TreePath selectionPath : selectionPaths) {
+      Object component = selectionPath.getLastPathComponent();
+      if (!(component instanceof ExternalSystemNode)) {
+        continue;
+      }
+
+      Object element = ((ExternalSystemNode)component).getDescriptor().getElement();
+      if (element instanceof ExternalTaskExecutionInfo) {
+        ExternalTaskExecutionInfo taskExecutionInfo = (ExternalTaskExecutionInfo)element;
+        ExternalSystemTaskExecutionSettings executionSettings = taskExecutionInfo.getSettings();
+        String key = executionSettings.getExternalSystemIdString() + executionSettings.getExternalProjectPath() + executionSettings.getVmOptions();
+        ExternalTaskExecutionInfo executionInfo = map.get(key);
+        if(executionInfo == null) {
+          ExternalSystemTaskExecutionSettings taskExecutionSettings = new ExternalSystemTaskExecutionSettings();
+          taskExecutionSettings.setExternalProjectPath(executionSettings.getExternalProjectPath());
+          taskExecutionSettings.setExternalSystemIdString(executionSettings.getExternalSystemIdString());
+          taskExecutionSettings.setVmOptions(executionSettings.getVmOptions());
+          executionInfo = new ExternalTaskExecutionInfo(taskExecutionSettings, taskExecutionInfo.getExecutorId());
+          map.put(key, executionInfo);
+        }
+        executionInfo.getSettings().getTaskNames().addAll(executionSettings.getTaskNames());
+        executionInfo.getSettings().getTaskDescriptions().addAll(executionSettings.getTaskDescriptions());
+      }
+    }
+
+    // Disable tasks execution if it comes from different projects
+    if(map.values().size() != 1) return null;
+    return map.values().iterator().next();
   }
 }
diff --git a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
index d998a99..e828a42 100644
--- a/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
+++ b/platform/external-system-impl/src/com/intellij/openapi/externalSystem/util/ExternalSystemUtil.java
@@ -34,10 +34,12 @@
 import com.intellij.openapi.externalSystem.model.project.ModuleData;
 import com.intellij.openapi.externalSystem.model.project.ProjectData;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
+import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType;
 import com.intellij.openapi.externalSystem.service.ImportCanceledException;
 import com.intellij.openapi.externalSystem.service.execution.AbstractExternalSystemTaskConfigurationType;
 import com.intellij.openapi.externalSystem.service.execution.ExternalSystemRunConfiguration;
 import com.intellij.openapi.externalSystem.service.execution.ProgressExecutionMode;
+import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager;
 import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask;
 import com.intellij.openapi.externalSystem.service.notification.ExternalSystemIdeNotificationManager;
 import com.intellij.openapi.externalSystem.service.project.ExternalProjectRefreshCallback;
@@ -74,6 +76,7 @@
 import com.intellij.ui.content.ContentManager;
 import com.intellij.util.Consumer;
 import com.intellij.util.Function;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
@@ -456,20 +459,41 @@
       public void execute(@NotNull ProgressIndicator indicator) {
         if(project.isDisposed()) return;
 
+        ExternalSystemProcessingManager processingManager = ServiceManager.getService(ExternalSystemProcessingManager.class);
+        if (processingManager.findTask(ExternalSystemTaskType.RESOLVE_PROJECT, externalSystemId, externalProjectPath) != null) {
+          callback.onFailure(ExternalSystemBundle.message("error.resolve.already.running", externalProjectPath), null);
+          return;
+        }
+
         ExternalSystemResolveProjectTask task
           = new ExternalSystemResolveProjectTask(externalSystemId, project, externalProjectPath, isPreviewMode);
 
         task.execute(indicator, ExternalSystemTaskNotificationListener.EP_NAME.getExtensions());
         final Throwable error = task.getError();
         if (error == null) {
+          ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
+          assert manager != null;
           long stamp = getTimeStamp(externalProjectPath, externalSystemId);
           if (stamp > 0) {
-            ExternalSystemManager<?, ?, ?, ?, ?> manager = ExternalSystemApiUtil.getManager(externalSystemId);
-            assert manager != null;
             if(project.isDisposed()) return;
             manager.getLocalSettingsProvider().fun(project).getExternalConfigModificationStamps().put(externalProjectPath, stamp);
           }
           DataNode<ProjectData> externalProject = task.getExternalProject();
+
+          if(externalProject != null) {
+            Set<String> externalModulePaths = ContainerUtil.newHashSet();
+            Collection<DataNode<ModuleData>> moduleNodes = ExternalSystemApiUtil.findAll(externalProject, ProjectKeys.MODULE);
+            for (DataNode<ModuleData> node : moduleNodes) {
+              externalModulePaths.add(node.getData().getLinkedExternalProjectPath());
+            }
+
+            String projectPath = externalProject.getData().getLinkedExternalProjectPath();
+            ExternalProjectSettings linkedProjectSettings = manager.getSettingsProvider().fun(project).getLinkedProjectSettings(projectPath);
+            if (linkedProjectSettings != null) {
+              linkedProjectSettings.setModules(externalModulePaths);
+            }
+          }
+
           callback.onSuccess(externalProject);
           return;
         }
diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy
index b763920..cdbd811 100644
--- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy
+++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/service/project/ExternalProjectServiceTest.groovy
@@ -54,7 +54,7 @@
         dependencies[name]++
       }
     }
-    ExternalSystemTestUtil.assertMapsEqual(['lib1': 1, 'lib2': 1], dependencies)
+    ExternalSystemTestUtil.assertMapsEqual(['Test_external_system_id: lib1': 1, 'Test_external_system_id: lib2': 1], dependencies)
   }
 
   void 'test changes in a project layout (content roots) could be detected on Refresh'() {
diff --git a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy
index 957f072..1b01fa4 100644
--- a/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy
+++ b/platform/external-system-impl/testSrc/com/intellij/openapi/externalSystem/test/ExternalProjectBuilder.groovy
@@ -60,15 +60,15 @@
     switch (name) {
       case 'project':
         ProjectSystemId projectSystemId = attributes.projectSystemId ?: TEST_EXTERNAL_SYSTEM_ID
-        ProjectData projectData = new ProjectData(projectSystemId, projectDir.path, projectDir.path)
-        projectData.name = attributes.name ?: 'project'
+        ProjectData projectData = new ProjectData(projectSystemId, attributes.name ?: 'project', projectDir.path, projectDir.path)
         projectNode = new DataNode<ProjectData>(ProjectKeys.PROJECT, projectData, null)
         return projectNode
       case 'module':
         ProjectSystemId projectSystemId = attributes.projectSystemId ?: TEST_EXTERNAL_SYSTEM_ID
         String moduleFilePath = attributes.moduleFilePath ?: projectDir.path
         String externalConfigPath = attributes.externalConfigPath ?: projectDir.path
-        ModuleData moduleData = new ModuleData(projectSystemId,
+        ModuleData moduleData = new ModuleData(attributes.name ?: name as String,
+                                               projectSystemId,
                                                ModuleTypeId.JAVA_MODULE,
                                                attributes.name ?: name as String,
                                                moduleFilePath,
@@ -106,7 +106,7 @@
   @NotNull
   private LibraryData getLibrary(@NotNull String name, @NotNull Map attributes) {
     DataNode<LibraryData> existing = ExternalSystemApiUtil.find(projectNode, ProjectKeys.LIBRARY, {
-      DataNode<LibraryData> node -> node.data.name == name
+      DataNode<LibraryData> node -> node.data.externalName == name
     } as BooleanFunction)
     if (existing != null) {
       return existing.data
diff --git a/platform/icons/src/modules/generatedSourceRoot.png b/platform/icons/src/modules/generatedSourceRoot.png
new file mode 100644
index 0000000..56a7620
--- /dev/null
+++ b/platform/icons/src/modules/generatedSourceRoot.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..41f98ff
--- /dev/null
+++ b/platform/icons/src/modules/[email protected]
Binary files differ
diff --git a/platform/icons/src/modules/generatedSourceRoot@2x_dark.png b/platform/icons/src/modules/generatedSourceRoot@2x_dark.png
new file mode 100644
index 0000000..1c93192
--- /dev/null
+++ b/platform/icons/src/modules/generatedSourceRoot@2x_dark.png
Binary files differ
diff --git a/platform/icons/src/modules/generatedSourceRoot_dark.png b/platform/icons/src/modules/generatedSourceRoot_dark.png
new file mode 100644
index 0000000..39d18bf
--- /dev/null
+++ b/platform/icons/src/modules/generatedSourceRoot_dark.png
Binary files differ
diff --git a/platform/icons/src/modules/generatedTestRoot.png b/platform/icons/src/modules/generatedTestRoot.png
new file mode 100644
index 0000000..114f685
--- /dev/null
+++ b/platform/icons/src/modules/generatedTestRoot.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..1c08e64
--- /dev/null
+++ b/platform/icons/src/modules/[email protected]
Binary files differ
diff --git a/platform/icons/src/modules/generatedTestRoot@2x_dark.png b/platform/icons/src/modules/generatedTestRoot@2x_dark.png
new file mode 100644
index 0000000..818a6b3
--- /dev/null
+++ b/platform/icons/src/modules/generatedTestRoot@2x_dark.png
Binary files differ
diff --git a/platform/icons/src/modules/generatedTestRoot_dark.png b/platform/icons/src/modules/generatedTestRoot_dark.png
new file mode 100644
index 0000000..3485f89
--- /dev/null
+++ b/platform/icons/src/modules/generatedTestRoot_dark.png
Binary files differ
diff --git a/platform/indexing-api/src/com/intellij/psi/search/PsiSearchHelper.java b/platform/indexing-api/src/com/intellij/psi/search/PsiSearchHelper.java
index e2f78291..741b31c 100644
--- a/platform/indexing-api/src/com/intellij/psi/search/PsiSearchHelper.java
+++ b/platform/indexing-api/src/com/intellij/psi/search/PsiSearchHelper.java
@@ -169,6 +169,13 @@
                                   short searchContext,
                                   boolean caseSensitive);
 
+  boolean processElementsWithWord(@NotNull TextOccurenceProcessor processor,
+                                  @NotNull SearchScope searchScope,
+                                  @NotNull String text,
+                                  short searchContext,
+                                  boolean caseSensitive,
+                                  boolean processInjectedPsi);
+
   @NotNull
   AsyncFuture<Boolean> processElementsWithWordAsync(
                                        @NotNull TextOccurenceProcessor processor,
diff --git a/platform/indexing-api/src/com/intellij/util/indexing/FileBasedIndexExtension.java b/platform/indexing-api/src/com/intellij/util/indexing/FileBasedIndexExtension.java
index 0dc808f..91d9470 100644
--- a/platform/indexing-api/src/com/intellij/util/indexing/FileBasedIndexExtension.java
+++ b/platform/indexing-api/src/com/intellij/util/indexing/FileBasedIndexExtension.java
@@ -24,7 +24,6 @@
 
 import java.util.Collection;
 import java.util.Collections;
-import java.util.Map;
 
 /**
  * @author Eugene Zhuravlev
@@ -83,9 +82,4 @@
   public boolean traceKeyHashToVirtualFileMapping() {
     return false;
   }
-
-  /** Per-filetype index version support */
-  public Map<FileType, Integer> getVersionMap() {
-    return Collections.emptyMap();
-  }
 }
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 8354390..f039357 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
@@ -20,7 +20,10 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ReadAction;
 import com.intellij.openapi.application.Result;
+import com.intellij.openapi.application.ex.ApplicationEx;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.fileEditor.FileDocumentManager;
+import com.intellij.openapi.fileEditor.impl.LoadTextUtil;
 import com.intellij.openapi.progress.ProcessCanceledException;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.ProgressIndicatorProvider;
@@ -42,6 +45,7 @@
 import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.util.CommonProcessors;
 import com.intellij.util.Processor;
+import com.intellij.util.SmartList;
 import com.intellij.util.codeInsight.CommentUtilCore;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.MultiMap;
@@ -60,7 +64,6 @@
 
 public class PsiSearchHelperImpl implements PsiSearchHelper {
   private static final Logger LOG = Logger.getInstance("#com.intellij.psi.impl.search.PsiSearchHelperImpl");
-
   private final PsiManagerEx myManager;
 
   @Override
@@ -76,8 +79,7 @@
     return scope;
   }
 
-
-  public PsiSearchHelperImpl(PsiManagerEx manager) {
+  public PsiSearchHelperImpl(@NotNull PsiManagerEx manager) {
     myManager = manager;
   }
 
@@ -123,8 +125,18 @@
                                          @NotNull String text,
                                          short searchContext,
                                          boolean caseSensitive) {
+    return processElementsWithWord(processor, searchScope, text, searchContext, caseSensitive, shouldProcessInjectedPsi(searchScope));
+  }
+
+  @Override
+  public boolean processElementsWithWord(@NotNull TextOccurenceProcessor processor,
+                                         @NotNull SearchScope searchScope,
+                                         @NotNull String text,
+                                         short searchContext,
+                                         boolean caseSensitive,
+                                         boolean processInjectedPsi) {
     final AsyncFuture<Boolean> result =
-      processElementsWithWordAsync(processor, searchScope, text, searchContext, caseSensitive);
+      processElementsWithWordAsync(processor, searchScope, text, searchContext, caseSensitive, processInjectedPsi, null);
     return AsyncUtil.get(result);
   }
 
@@ -135,7 +147,7 @@
                                                            @NotNull final String text,
                                                            final short searchContext,
                                                            final boolean caseSensitively) {
-    return processElementsWithWordAsync(processor, searchScope, text, searchContext, caseSensitively, null);
+    return processElementsWithWordAsync(processor, searchScope, text, searchContext, caseSensitively, shouldProcessInjectedPsi(searchScope), null);
   }
 
   @NotNull
@@ -144,7 +156,8 @@
                                                             @NotNull final String text,
                                                             final short searchContext,
                                                             final boolean caseSensitively,
-                                                            String containerName) {
+                                                            boolean processInjectedPsi,
+                                                            @Nullable String containerName) {
     if (text.isEmpty()) {
       return AsyncFutureFactory.wrapException(new IllegalArgumentException("Cannot search for elements with empty text"));
     }
@@ -155,15 +168,29 @@
       return processElementsWithTextInGlobalScopeAsync(processor,
                                                        (GlobalSearchScope)searchScope,
                                                        searcher,
-                                                       searchContext, caseSensitively, containerName, progress);
+                                                       searchContext, caseSensitively, containerName, progress, processInjectedPsi);
     }
     LocalSearchScope scope = (LocalSearchScope)searchScope;
     PsiElement[] scopeElements = scope.getScope();
-    final boolean processInjectedPsi = !scope.isIgnoreInjectedPsi();
-
     final StringSearcher searcher = new StringSearcher(text, caseSensitively, true, searchContext == UsageSearchContext.IN_STRINGS);
     Processor<PsiElement> localProcessor = localProcessor(processor, progress, processInjectedPsi, searcher);
-    return JobLauncher.getInstance().invokeConcurrentlyUnderProgressAsync(Arrays.asList(scopeElements), progress, false, localProcessor);
+    return wrapInFuture(Arrays.asList(scopeElements), progress, localProcessor);
+  }
+
+  private static <T> AsyncFuture<Boolean> wrapInFuture(@NotNull List<T> files, final ProgressIndicator progress, @NotNull Processor<T> processor) {
+    AsyncFutureResult<Boolean> asyncFutureResult = AsyncFutureFactory.getInstance().createAsyncFutureResult();
+    try {
+      boolean result = JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files, progress, true, true, processor);
+      asyncFutureResult.set(result);
+    }
+    catch (Throwable t) {
+      asyncFutureResult.setException(t);
+    }
+    return asyncFutureResult;
+  }
+
+  private static boolean shouldProcessInjectedPsi(SearchScope scope) {
+    return scope instanceof LocalSearchScope ? !((LocalSearchScope)scope).isIgnoreInjectedPsi() : true;
   }
 
   @NotNull
@@ -196,7 +223,7 @@
                                                                          final short searchContext,
                                                                          final boolean caseSensitively,
                                                                          String containerName,
-                                                                         final ProgressIndicator progress) {
+                                                                         final ProgressIndicator progress, final boolean processInjectedPsi) {
     if (Thread.holdsLock(PsiLock.LOCK)) {
       throw new AssertionError("You must not run search from within updating PSI activity. Please consider invokeLatering it instead.");
     }
@@ -213,7 +240,7 @@
       progress.setText(PsiBundle.message("psi.search.for.word.progress", text));
     }
 
-    final Processor<PsiElement> localProcessor = localProcessor(processor, progress, true, searcher);
+    final Processor<PsiElement> localProcessor = localProcessor(processor, progress, processInjectedPsi, searcher);
     if (containerName != null) {
       List<VirtualFile> intersectionWithContainerFiles = new ArrayList<VirtualFile>();
       // intersectionWithContainerFiles holds files containing words from both `text` and `containerName`
@@ -252,7 +279,7 @@
     }
 
     AsyncFuture<Boolean> result = fileSet.isEmpty()
-                                  ? AsyncFutureFactory.wrap(true)
+                                  ? AsyncFutureFactory.wrap(Boolean.TRUE)
                                   : processPsiFileRootsAsync(new ArrayList<VirtualFile>(fileSet), fileSet.size(), 0, progress, localProcessor);
     return popStateAfter(result, progress);
   }
@@ -286,32 +313,25 @@
     return totalResult;
   }
 
-  // splits mainList into 2 lists: outIntersection containing elements from both mainList and list2 and outRest with all the rest elements from mainList
-  private static <T> void splitSortedLists(@NotNull List<T> mainList,
-                                           @NotNull List<T> list2,
-                                           @NotNull Comparator<? super T> comparator,
-                                           @NotNull List<T> outIntersection,
-                                           @NotNull List<T> outRest) {
-    int index1 = 0;
-    int index2 = 0;
-    while (index1 != mainList.size()) {
-      T element1 = mainList.get(index1);
-      T element2 = index2 == list2.size() ? null : list2.get(index2);
-      int c = element2 == null ? -1 : comparator.compare(element1, element2);
-      if (c == 0) {
-        outIntersection.add(element1);
-        index1++;
-        index2++;
-      }
-      else if (c < 0) {
-        index1++;
-        outRest.add(element1);
-      }
-      else {
-        index2++;
-      }
+  private static class CannotRunReadActionException extends RuntimeException{
+    @Override
+    public Throwable fillInStackTrace() {
+      return this;
     }
   }
+  // throws exception if can't grab read action right now
+  private static <T> T tryRead(final Computable<T> computable) throws CannotRunReadActionException {
+    final Ref<T> result = new Ref<T>();
+    if (((ApplicationEx)ApplicationManager.getApplication()).tryRunReadAction(new Runnable() {
+      @Override
+      public void run() {
+        result.set(computable.compute());
+      }
+    })) {
+      return result.get();
+    }
+    throw new CannotRunReadActionException();
+  }
 
   /**
    * @param files to scan for references in this pass.
@@ -324,64 +344,96 @@
                                                         final int totalSize,
                                                         int alreadyProcessedFiles,
                                                         final ProgressIndicator progress,
-                                                        @NotNull final Processor<? super PsiFile> psiRootProcessor) {
+                                                        @NotNull final Processor<? super PsiFile> localProcessor) {
     myManager.startBatchFilesProcessingMode();
     final AtomicInteger counter = new AtomicInteger(alreadyProcessedFiles);
     final AtomicBoolean canceled = new AtomicBoolean(false);
 
-    AsyncFuture<Boolean>
-      completed = JobLauncher.getInstance().invokeConcurrentlyUnderProgressAsync(files, progress, false, new Processor<VirtualFile>() {
-      @Override
-      public boolean process(final VirtualFile vfile) {
-        final PsiFile file = ApplicationManager.getApplication().runReadAction(new Computable<PsiFile>() {
+    AsyncFutureResult<Boolean> asyncFutureResult = AsyncFutureFactory.getInstance().createAsyncFutureResult();
+    final List<VirtualFile> failedFiles = Collections.synchronizedList(new SmartList<VirtualFile>());
+    try {
+      boolean completed =
+        JobLauncher.getInstance().invokeConcurrentlyUnderProgress(files, progress, false, false, new Processor<VirtualFile>() {
           @Override
-          public PsiFile compute() {
-            return vfile.isValid() ? myManager.findFile(vfile) : null;
+          public boolean process(final VirtualFile vfile) {
+            try {
+              TooManyUsagesStatus.getFrom(progress).pauseProcessingIfTooManyUsages();
+              processVirtualFile(vfile, progress, localProcessor, canceled, counter, totalSize);
+            }
+            catch (CannotRunReadActionException action) {
+              failedFiles.add(vfile);
+            }
+            return !canceled.get();
           }
         });
-        if (file != null && !(file instanceof PsiBinaryFile)) {
-          file.getViewProvider().getContents(); // load contents outside read action
-          if (myManager.getProject().isDisposed()) throw new ProcessCanceledException();
-          List<PsiFile> psiRoots = ApplicationManager.getApplication().runReadAction(new Computable<List<PsiFile>>() {
+      if (!failedFiles.isEmpty()) {
+        for (final VirtualFile vfile : failedFiles) {
+          TooManyUsagesStatus.getFrom(progress).pauseProcessingIfTooManyUsages();
+          // we failed to run read action in job launcher thread
+          // run read action in our thread instead
+          ApplicationManager.getApplication().runReadAction(new Runnable() {
             @Override
-            public List<PsiFile> compute() {
-              return file.getViewProvider().getAllFiles();
+            public void run() {
+              processVirtualFile(vfile, progress, localProcessor, canceled, counter, totalSize);
             }
           });
+        }
+      }
+      asyncFutureResult.set(completed);
+      myManager.finishBatchFilesProcessingMode();
+    }
+    catch (Throwable t) {
+      asyncFutureResult.setException(t);
+    }
+
+    return asyncFutureResult;
+  }
+
+  private void processVirtualFile(@NotNull final VirtualFile vfile,
+                                  final ProgressIndicator progress,
+                                  @NotNull final Processor<? super PsiFile> localProcessor,
+                                  @NotNull final AtomicBoolean canceled,
+                                  @NotNull AtomicInteger counter,
+                                  int totalSize) {
+    final PsiFile file = tryRead(new Computable<PsiFile>() {
+      @Override
+      public PsiFile compute() {
+        return vfile.isValid() ? myManager.findFile(vfile) : null;
+      }
+    });
+    if (file != null && !(file instanceof PsiBinaryFile)) {
+      // load contents outside read action
+      if (FileDocumentManager.getInstance().getCachedDocument(vfile) == null) {
+        LoadTextUtil.loadText(vfile); // cache bytes in vfs
+      }
+      tryRead(new Computable<Void>() {
+        @Override
+        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);
           for (final PsiFile psiRoot : psiRoots) {
             checkCanceled(progress);
             assert psiRoot != null : "One of the roots of file " + file + " is null. All roots: " + psiRoots +
                                      "; ViewProvider: " + file.getViewProvider() + "; Virtual file: " + file.getViewProvider().getVirtualFile();
             if (!processed.add(psiRoot)) continue;
-            if (!ApplicationManager.getApplication().runReadAction(new Computable<Boolean>() {
-              @Override
-              public Boolean compute() {
-                return psiRoot.isValid();
-              }
-            })) {
+            if (!psiRoot.isValid()) {
               continue;
             }
-            if (!psiRootProcessor.process(psiRoot)) {
+
+            if (!localProcessor.process(psiRoot)) {
               canceled.set(true);
               break;
             }
           }
+          return null;
         }
-        if (progress != null && progress.isRunning()) {
-          double fraction = (double)counter.incrementAndGet() / totalSize;
-          progress.setFraction(fraction);
-        }
-        return !canceled.get();
-      }
-    });
-
-    return new FinallyFuture<Boolean>(completed, new Runnable() {
-      @Override
-      public void run() {
-        myManager.finishBatchFilesProcessingMode();
-      }
-    });
+      });
+    }
+    if (progress != null && progress.isRunning()) {
+      double fraction = (double)counter.incrementAndGet() / totalSize;
+      progress.setFraction(fraction);
+    }
   }
 
   private static void checkCanceled(ProgressIndicator progress) {
@@ -756,6 +808,7 @@
     return popStateAfter(result, progress);
   }
 
+  @NotNull
   private AsyncFuture<Boolean> processCandidatesAsync(final ProgressIndicator progress,
                                                       @NotNull final Map<RequestWithProcessor, Processor<PsiElement>> localProcessors,
                                                       @NotNull final MultiMap<VirtualFile, RequestWithProcessor> candidateFiles,
@@ -766,20 +819,19 @@
     return processPsiFileRootsAsync(files, totalSize, alreadyProcessedFiles, progress, new Processor<PsiFile>() {
       @Override
       public boolean process(final PsiFile psiRoot) {
-        final VirtualFile vfile = ApplicationManager.getApplication().runReadAction(new Computable<VirtualFile>() {
+        return tryRead(new Computable<Boolean>() {
           @Override
-          public VirtualFile compute() {
-            return psiRoot.getVirtualFile();
+          public Boolean compute() {
+            final VirtualFile vfile = psiRoot.getVirtualFile();
+            for (final RequestWithProcessor singleRequest : candidateFiles.get(vfile)) {
+              Processor<PsiElement> localProcessor = localProcessors.get(singleRequest);
+              if (!localProcessor.process(psiRoot)) {
+                return false;
+              }
+            }
+            return true;
           }
         });
-        for (final RequestWithProcessor singleRequest : candidateFiles.get(vfile)) {
-          Processor<PsiElement> localProcessor = localProcessors.get(singleRequest);
-          TooManyUsagesStatus.getFrom(progress).pauseProcessingIfTooManyUsages();
-          if (!localProcessor.process(psiRoot)) {
-            return false;
-          }
-        }
-        return true;
       }
     });
   }
@@ -988,7 +1040,7 @@
   @NotNull
   private AsyncFuture<Boolean> processSingleRequestAsync(@NotNull PsiSearchRequest single, @NotNull Processor<PsiReference> consumer) {
     return processElementsWithWordAsync(adaptProcessor(single, consumer), single.searchScope, single.word, single.searchContext,
-                                        single.caseSensitive, single.containerName);
+                                        single.caseSensitive, shouldProcessInjectedPsi(single.searchScope), single.containerName);
   }
 
   @NotNull
diff --git a/platform/indexing-impl/src/com/intellij/xml/index/XsdNamespaceBuilder.java b/platform/indexing-impl/src/com/intellij/xml/index/XsdNamespaceBuilder.java
index 59807a2..ea7f39f 100644
--- a/platform/indexing-impl/src/com/intellij/xml/index/XsdNamespaceBuilder.java
+++ b/platform/indexing-impl/src/com/intellij/xml/index/XsdNamespaceBuilder.java
@@ -105,7 +105,7 @@
     if (tagName != null && myTags.contains(tagName)) {
       rate |= 0x02;
     }
-    if (Comparing.equal(version, myVersion)) {
+    if (version != null && version.equals(myVersion)) {
       rate |= 0x01;
     }
     return rate;
diff --git a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionContributor.java b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionContributor.java
index 56e474f..65a6db8 100644
--- a/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionContributor.java
+++ b/platform/lang-api/src/com/intellij/codeInsight/completion/CompletionContributor.java
@@ -141,8 +141,9 @@
    *
    * If you want to implement this functionality directly by overriding this method, the following is for you.
    * Always check that parameters match your situation, and that completion type ({@link CompletionParameters#getCompletionType()}
-   * is of your favourite kind. This method is run outside of read action, so you have to manage this manually
-   * ({@link com.intellij.openapi.application.Application#runReadAction(Runnable)}). Don't take read actions for too long.<p>
+   * is of your favourite kind. This method is run inside a read action. If you do any long activity non-related to PSI in it, please
+   * ensure you call {@link com.intellij.openapi.progress.ProgressManager#checkCanceled()} often enough so that the completion process 
+   * can be cancelled smoothly when the user begins to type in the editor. 
    *
    * @param parameters
    * @param result
diff --git a/platform/lang-api/src/com/intellij/refactoring/listeners/RefactoringEventData.java b/platform/lang-api/src/com/intellij/refactoring/listeners/RefactoringEventData.java
new file mode 100644
index 0000000..3907b5a
--- /dev/null
+++ b/platform/lang-api/src/com/intellij/refactoring/listeners/RefactoringEventData.java
@@ -0,0 +1,73 @@
+/*
+ * 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.refactoring.listeners;
+
+import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.UserDataHolder;
+import com.intellij.psi.PsiElement;
+import com.intellij.util.Function;
+import com.intellij.util.containers.HashMap;
+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.Map;
+
+public class RefactoringEventData implements UserDataHolder {
+  private Map<Key, Object> data;
+
+  public static final Key<Collection<? extends String>> CONFLICTS_KEY = Key.create("conflicts");
+  public static final Key<PsiElement> PSI_ELEMENT_KEY = Key.create("element");
+  public static final Key<PsiElement[]> PSI_ELEMENT_ARRAY_KEY = Key.create("elementArray");
+
+  public RefactoringEventData() {
+    data = new HashMap<Key, Object>();
+  }
+
+  public void addElement(PsiElement element) {
+    putUserData(PSI_ELEMENT_KEY, element);
+  }
+
+  public <T> void addMembers(T[] members, Function<T, PsiElement> converter) {
+    List<PsiElement> elements = new ArrayList<PsiElement>();
+    for (T info : members) {
+      elements.add(converter.fun(info));
+    }
+    addElements(elements);
+  }
+  
+  public void addElements(Collection<PsiElement> elements) {
+    putUserData(PSI_ELEMENT_ARRAY_KEY, elements.toArray(new PsiElement[elements.size()]));
+  }
+  
+  public void addElements(PsiElement[] elements) {
+    putUserData(PSI_ELEMENT_ARRAY_KEY, elements);
+  }
+  
+  
+  @Nullable
+  @Override
+  public <T> T getUserData(@NotNull Key<T> key) {
+    return (T)data.get(key);
+  }
+
+  @Override
+  public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
+    data.put(key, value);
+  }
+}
diff --git a/platform/lang-api/src/com/intellij/refactoring/listeners/RefactoringEventListener.java b/platform/lang-api/src/com/intellij/refactoring/listeners/RefactoringEventListener.java
new file mode 100644
index 0000000..208b867
--- /dev/null
+++ b/platform/lang-api/src/com/intellij/refactoring/listeners/RefactoringEventListener.java
@@ -0,0 +1,54 @@
+/*
+ * 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.refactoring.listeners;
+
+import com.intellij.util.messages.Topic;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * Listener to get high level notifications about performed refactorings in the selected project.
+ * 
+ * RefactoringEventData depends on the refactoring performed. It should reflect state of the data before/after refactoring.
+ */
+public interface RefactoringEventListener {
+  /**
+   * Entry point to attach a client listener. Events are posted on the project bus and its children so connection should be done as following
+   * {@code project.getMessageBus().connect(Disposable).subscribe(RefactoringEventListener.REFACTORING_EVENT_TOPIC, new Listener())}
+   */
+  Topic<RefactoringEventListener> REFACTORING_EVENT_TOPIC = Topic.create("REFACTORING_EVENT_TOPIC", RefactoringEventListener.class);
+
+  /**
+   * Is fired when refactoring enters its write phase (find usages, conflict detection phases are passed already) 
+   */
+  void refactoringStarted(@NotNull String refactoringId, @Nullable RefactoringEventData beforeData);
+
+  /**
+   * Is fired when refactoring is completed, probably with conflicts.
+   */
+  void refactoringDone(@NotNull String refactoringId, @Nullable RefactoringEventData afterData);
+
+  /**
+   * Is fired when conflicts are detected. If the next event comes from the same refactoring then conflicts were ignored.
+   * @param conflictsData should contain string representation of the conflicts
+   */
+  void conflictsDetected(@NotNull String refactoringId, @NotNull RefactoringEventData conflictsData);
+
+  /**
+   * Is fired when undoable action created on refactoring execution is undone.
+   */
+  void undoRefactoring(@NotNull String refactoringId);
+}
diff --git a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java
index 75784fc..7780f7a 100644
--- a/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java
+++ b/platform/lang-impl/src/com/intellij/application/options/codeStyle/CodeStyleSchemesUIConfiguration.java
@@ -75,7 +75,10 @@
     public static void setRecentImportFile(@NotNull VirtualFile recentFile) {
       CodeStyleSchemesUIConfiguration configuration = getInstance();
       if (configuration != null) {
-        configuration.RECENT_IMPORT_FILE_LOCATION = recentFile.getUrl();
+        URL url = VfsUtil.convertToURL(recentFile.getUrl());
+        if (url != null) {
+          configuration.RECENT_IMPORT_FILE_LOCATION = url.toString();
+        }
       }
     }
   }
diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/ColorSettingsUtil.java b/platform/lang-impl/src/com/intellij/application/options/colors/ColorSettingsUtil.java
index e31c851..275a040 100644
--- a/platform/lang-impl/src/com/intellij/application/options/colors/ColorSettingsUtil.java
+++ b/platform/lang-impl/src/com/intellij/application/options/colors/ColorSettingsUtil.java
@@ -28,7 +28,9 @@
 import com.intellij.openapi.options.colors.AttributesDescriptor;
 import com.intellij.openapi.options.colors.ColorAndFontDescriptorsProvider;
 import com.intellij.openapi.options.colors.ColorSettingsPage;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.containers.HashMap;
+import org.jetbrains.annotations.NotNull;
 
 import java.util.ArrayList;
 import java.util.Collections;
@@ -89,8 +91,13 @@
     for (SeveritiesProvider provider : Extensions.getExtensions(SeveritiesProvider.EP_NAME)) {
       for (HighlightInfoType highlightInfoType : provider.getSeveritiesHighlightInfoTypes()) {
         final TextAttributesKey attributesKey = highlightInfoType.getAttributesKey();
-        descriptors.add(new AttributesDescriptor(attributesKey.myExternalName, attributesKey));
+        descriptors.add(new AttributesDescriptor(toDisplayName(attributesKey), attributesKey));
       }
     }
   }
+
+  @NotNull
+  private static String toDisplayName(@NotNull TextAttributesKey attributesKey) {
+    return StringUtil.capitalize(attributesKey.getExternalName().toLowerCase().replaceAll("_", " "));
+  }
 }
diff --git a/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java b/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java
index b66eef0..72c8f5c 100644
--- a/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java
+++ b/platform/lang-impl/src/com/intellij/application/options/colors/FontOptions.java
@@ -173,7 +173,7 @@
 
   private float getLineSpacingFromField() {
     try {
-       return Math.min(30, Math.max(1, Float.parseFloat(myLineSpacingField.getText())));
+       return Math.min(30, Math.max(.6F, Float.parseFloat(myLineSpacingField.getText())));
     } catch (NumberFormatException e){
       return 1;
     }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java b/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java
index f321173..89413c58 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/AutoPopupController.java
@@ -153,6 +153,7 @@
   public void autoPopupParameterInfo(final Editor editor, @Nullable final PsiElement highlightedMethod){
     if (ApplicationManager.getApplication().isUnitTestMode()) return;
     if (DumbService.isDumb(myProject)) return;
+    if (PowerSaveMode.isEnabled()) return;
 
     ApplicationManager.getApplication().assertIsDispatchThread();
     final CodeInsightSettings settings = CodeInsightSettings.getInstance();
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeDialog.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeDialog.java
index 45862ed..950e4c9 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeDialog.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeDialog.java
@@ -55,7 +55,6 @@
   private JCheckBox    myDoNotAskMeCheckBox;
 
   private final String myHelpId;
-  @NotNull private String myRearrangeEntriesKeyForLanguage;
   @Nullable private CommonCodeStyleSettings myCommonSettings;
   private boolean myForceArrangeModeEnabled;
 
@@ -77,7 +76,6 @@
                                 && myCommonSettings.isForceArrangeMenuAvailable()
                                 && myCommonSettings.FORCE_REARRANGE_MODE != CommonCodeStyleSettings.REARRANGE_ACCORDIND_TO_DIALOG;
 
-    myRearrangeEntriesKeyForLanguage = LayoutCodeConstants.REARRANGE_ENTRIES_KEY + (myFile == null ? "" : myFile.getLanguage().getDisplayName());
     setOKButtonText(CodeInsightBundle.message("reformat.code.accept.button.text"));
     setTitle(title);
     init();
@@ -104,7 +102,7 @@
     //Loading previous state
     myCbOptimizeImports.setSelected(PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.OPTIMIZE_IMPORTS_KEY, false));
     myCbArrangeEntries.setSelected(myForceArrangeModeEnabled ? myCommonSettings.FORCE_REARRANGE_MODE == CommonCodeStyleSettings.REARRANGE_ALWAYS
-                                                             : PropertiesComponent.getInstance(myProject).getBoolean(myRearrangeEntriesKeyForLanguage, false));
+                                                             : ReformatCodeAction.getLastSavedRearrangeCbState(myProject, myFile));
 
     myCbOnlyVcsChangedRegions.setSelected(PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.PROCESS_CHANGED_TEXT_KEY, false));
 
@@ -274,8 +272,15 @@
     super.doOKAction();
     //Saving checkboxes state
     PropertiesComponent.getInstance().setValue(LayoutCodeConstants.OPTIMIZE_IMPORTS_KEY, Boolean.toString(myCbOptimizeImports.isSelected()));
-    PropertiesComponent.getInstance(myProject).setValue(myRearrangeEntriesKeyForLanguage, Boolean.toString(myCbArrangeEntries.isSelected()));
     PropertiesComponent.getInstance().setValue(LayoutCodeConstants.PROCESS_CHANGED_TEXT_KEY, Boolean.toString(myCbOnlyVcsChangedRegions.isSelected()));
+    saveRearrangeCbState(myCbArrangeEntries.isSelected());
+  }
+
+  private void saveRearrangeCbState(boolean isSelected) {
+    if (myFile != null)
+      LayoutCodeSettingsStorage.saveRearrangeEntriesOptionFor(myProject, myFile.getLanguage(), isSelected);
+    else
+      LayoutCodeSettingsStorage.saveRearrangeEntriesOptionFor(myProject, isSelected);
   }
 
   private boolean canTargetVcsRegions() {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeSettingsStorage.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeSettingsStorage.java
new file mode 100644
index 0000000..5175cf5
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/LayoutCodeSettingsStorage.java
@@ -0,0 +1,50 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.codeInsight.actions;
+
+import com.intellij.ide.util.PropertiesComponent;
+import com.intellij.lang.Language;
+import com.intellij.openapi.project.Project;
+import org.jetbrains.annotations.NotNull;
+
+public class LayoutCodeSettingsStorage {
+
+  private LayoutCodeSettingsStorage() {
+  }
+
+  public static void saveRearrangeEntriesOptionFor(@NotNull Project project, @NotNull Language language, boolean value) {
+    String key = getRearrangeEntriesKeyForLanguage(language);
+    PropertiesComponent.getInstance(project).setValue(key, Boolean.toString(value));
+  }
+
+  public static void saveRearrangeEntriesOptionFor(@NotNull Project project, boolean value) {
+    PropertiesComponent.getInstance(project).setValue(LayoutCodeConstants.REARRANGE_ENTRIES_KEY, Boolean.toString(value));
+  }
+
+  public static boolean getLastSavedRearrangeEntriesCbStateFor(@NotNull Project project) {
+    return PropertiesComponent.getInstance(project).getBoolean(LayoutCodeConstants.REARRANGE_ENTRIES_KEY, false);
+  }
+
+  public static boolean getLastSavedRearrangeEntriesCbStateFor(@NotNull Project project, @NotNull Language language) {
+    String key = getRearrangeEntriesKeyForLanguage(language);
+    return PropertiesComponent.getInstance(project).getBoolean(key, false);
+  }
+
+  private static String getRearrangeEntriesKeyForLanguage(@NotNull Language language) {
+    return LayoutCodeConstants.REARRANGE_ENTRIES_KEY + language.getDisplayName();
+  }
+
+}
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java
index 3d56196..c0c2332 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/actions/ReformatCodeAction.java
@@ -46,6 +46,7 @@
 import com.intellij.psi.util.PsiUtilCore;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import javax.swing.event.HyperlinkEvent;
@@ -151,7 +152,8 @@
     boolean optimizeImports = ReformatFilesDialog.isOptmizeImportsOptionOn();
     boolean processWholeFile = false;
     boolean processChangedTextOnly = PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.PROCESS_CHANGED_TEXT_KEY, false);
-    boolean rearrangeEntries = PropertiesComponent.getInstance().getBoolean(LayoutCodeConstants.REARRANGE_ENTRIES_KEY, false);
+    boolean rearrangeEntries = getLastSavedRearrangeCbState(project, file);
+
     final boolean showDialog = EditorSettingsExternalizable.getInstance().getOptions().SHOW_REFORMAT_DIALOG;
     if (showDialog || (file == null && dir != null)) {
       final LayoutCodeDialog dialog = new LayoutCodeDialog(project, CodeInsightBundle.message("process.reformat.code"), file, dir,
@@ -218,6 +220,13 @@
     }
   }
 
+  public static boolean getLastSavedRearrangeCbState(@NotNull Project project, @Nullable PsiFile file) {
+    if (file != null) {
+      return LayoutCodeSettingsStorage.getLastSavedRearrangeEntriesCbStateFor(project, file.getLanguage());
+    }
+    return LayoutCodeSettingsStorage.getLastSavedRearrangeEntriesCbStateFor(project);
+  }
+
   public static void updateShowDialogSetting(LayoutCodeDialog dialog, String title) {
     if (dialog.isDoNotAskMe()) {
       Notifications.Bus.notify(new Notification("Reformat Code", title,
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 c5c5d6f..853ea8f 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CodeCompletionHandlerBase.java
@@ -775,9 +775,9 @@
           }
           final Document document = pair.second;
           assert document != null;
-          document.setText(file.getText());
+          document.setText(file.getViewProvider().getContents());
           return copy;
-        }
+        }        
       }
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionAssertions.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionAssertions.java
index 4d1eea7..76ca0b5 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionAssertions.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionAssertions.java
@@ -145,8 +145,9 @@
     }
 
     final TextRange range = insertedElement.getTextRange();
-    String fileCopyText = fileCopy.getText();
-    if ((range.getEndOffset() > fileCopyText.length()) || !range.substring(fileCopyText).equals(insertedElement.getText())) {
+    CharSequence fileCopyText = fileCopy.getViewProvider().getContents();
+    if ((range.getEndOffset() > fileCopyText.length()) ||
+        !fileCopyText.subSequence(range.getStartOffset(), range.getEndOffset()).toString().equals(insertedElement.getText())) {
       throw new LogEventException("Inconsistent completion tree", "range=" + range + "\n" + DebugUtil.currentStackTrace(),
                                          createFileTextAttachment(fileCopy, originalFile), createAstAttachment(fileCopy, originalFile),
                                          new Attachment("Element at caret.txt", insertedElement.getText()));
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 52ed9c8..1aa02d4 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/CompletionProgressIndicator.java
@@ -209,11 +209,7 @@
         final int selectionEndOffset = initContext.getSelectionEndOffset();
         final PsiReference reference = initContext.getFile().findReferenceAt(selectionEndOffset);
         if (reference != null) {
-          int referenceStart = reference.getElement().getTextRange().getStartOffset();
-          if (referenceStart + reference.getRangeInElement().getStartOffset() != selectionEndOffset ||
-              referenceStart == initContext.getStartOffset()) {
-            initContext.setReplacementOffset(findReplacementOffset(selectionEndOffset, reference));
-          }
+          initContext.setReplacementOffset(findReplacementOffset(selectionEndOffset, reference));
         }
       }
       catch (IndexNotReadyException ignored) {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java
index 19d4804..8852c85 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/actions/HippieWordCompletionHandler.java
@@ -65,6 +65,7 @@
 
     String oldPrefix = completionState.oldPrefix;
     CompletionVariant lastProposedVariant = completionState.lastProposedVariant;
+    boolean fromOtherFiles = completionState.fromOtherFiles;
 
     if (lastProposedVariant == null || oldPrefix == null || !new CamelHumpMatcher(oldPrefix).isStartMatch(currentPrefix) ||
         !currentPrefix.equals(lastProposedVariant.variant)) {
@@ -72,16 +73,18 @@
       oldPrefix = currentPrefix;
       completionState.oldPrefix = oldPrefix;
       lastProposedVariant = null;
+      fromOtherFiles = false;
     }
 
-    CompletionVariant nextVariant = computeNextVariant(editor, oldPrefix, lastProposedVariant, data, file);
+    CompletionVariant nextVariant = computeNextVariant(editor, oldPrefix, lastProposedVariant, data, file, fromOtherFiles);
     if (nextVariant == null) return;
 
     int replacementEnd = data.startOffset + data.myWordUnderCursor.length();
     editor.getDocument().replaceString(data.startOffset, replacementEnd, nextVariant.variant);
     editor.getCaretModel().moveToOffset(data.startOffset + nextVariant.variant.length());
     completionState.lastProposedVariant = nextVariant;
-    highlightWord(nextVariant, project, data);
+    completionState.fromOtherFiles = nextVariant.editor != editor;
+    if (nextVariant.editor == editor) highlightWord(nextVariant, project, data);
   }
 
   private static void highlightWord(final CompletionVariant variant, final Project project, CompletionData data) {
@@ -105,12 +108,15 @@
   private CompletionVariant computeNextVariant(final Editor editor,
                                                @Nullable final String prefix,
                                                @Nullable CompletionVariant lastProposedVariant,
-                                               final CompletionData data, PsiFile file) {
-    final List<CompletionVariant> variants = computeVariants(editor, new CamelHumpMatcher(StringUtil.notNullize(prefix)), file);
+                                               final CompletionData data,
+                                               PsiFile file,
+                                               boolean includeWordsFromOtherFiles
+  ) {
+    final List<CompletionVariant> variants = computeVariants(editor, new CamelHumpMatcher(StringUtil.notNullize(prefix)), file, includeWordsFromOtherFiles);
     if (variants.isEmpty()) return null;
 
-    for (CompletionVariant variant : variants) {
-      if (lastProposedVariant != null) {
+    if (lastProposedVariant != null) {
+      for (CompletionVariant variant : variants) {
         if (variant.variant.equals(lastProposedVariant.variant)) {
           if (lastProposedVariant.offset > data.startOffset && variant.offset > data.startOffset) lastProposedVariant = variant;
           if (lastProposedVariant.offset < data.startOffset && variant.offset < data.startOffset) lastProposedVariant = variant;
@@ -135,7 +141,9 @@
       }
       else {
         for (CompletionVariant variant : variants) {
-          if (variant.offset > data.startOffset) return variant;
+          if (variant.offset > data.startOffset) {
+            return variant;
+          }
         }
 
         return variants.iterator().next();
@@ -149,7 +157,9 @@
       CompletionVariant result = null;
       for (CompletionVariant variant : variants) {
         if (variant == lastProposedVariant) {
-          if (result == null) return variants.get(variants.size() - 1);
+          if (result == null) {
+            return computeNextVariant(editor, prefix, null, data, file, !includeWordsFromOtherFiles);
+          }
           return result;
         }
         result = variant;
@@ -165,7 +175,7 @@
             return i.next();
           }
           else {
-            return variants.iterator().next();
+            return computeNextVariant(editor, prefix, null, data, file, !includeWordsFromOtherFiles);
           }
         }
       }
@@ -186,7 +196,7 @@
       this.offset = offset;
     }
   }
-  
+
   private static boolean containsLetters(CharSequence seq, int start, int end) {
     for (int i = start; i < end; i++) {
       if (Character.isLetter(seq.charAt(i))) {
@@ -196,7 +206,10 @@
     return false;
   }
 
-  private static List<CompletionVariant> computeVariants(@NotNull final Editor editor, CamelHumpMatcher matcher, PsiFile file) {
+  private static List<CompletionVariant> computeVariants(@NotNull final Editor editor,
+                                                         CamelHumpMatcher matcher,
+                                                         PsiFile file,
+                                                         boolean includeWordsFromOtherFiles) {
 
     final CharSequence chars = editor.getDocument().getCharsSequence();
 
@@ -205,15 +218,17 @@
 
     final int caretOffset = editor.getCaretModel().getOffset();
 
-    addWordsForEditor((EditorEx)editor, matcher, chars, words, afterWords, caretOffset);
-
-    for(FileEditor fileEditor: FileEditorManager.getInstance(file.getProject()).getAllEditors()) {
-      if (fileEditor instanceof TextEditor) {
-        Editor anotherEditor = ((TextEditor)fileEditor).getEditor();
-        if (anotherEditor != editor) {
-          addWordsForEditor((EditorEx)anotherEditor, matcher, anotherEditor.getDocument().getCharsSequence(), words, afterWords, 0);
+    if (includeWordsFromOtherFiles) {
+      for(FileEditor fileEditor: FileEditorManager.getInstance(file.getProject()).getAllEditors()) {
+        if (fileEditor instanceof TextEditor) {
+          Editor anotherEditor = ((TextEditor)fileEditor).getEditor();
+          if (anotherEditor != editor) {
+            addWordsForEditor((EditorEx)anotherEditor, matcher, anotherEditor.getDocument().getCharsSequence(), words, afterWords, 0);
+          }
         }
       }
+    } else {
+      addWordsForEditor((EditorEx)editor, matcher, chars, words, afterWords, caretOffset);
     }
 
     Set<String> allWords = new HashSet<String>();
@@ -240,10 +255,10 @@
 
     return result;
   }
-  
+
   private interface TokenProcessor {
     boolean processToken(int start, int end);
-  } 
+  }
 
   private static void addWordsForEditor(final EditorEx editor,
                                         final CamelHumpMatcher matcher,
@@ -304,8 +319,8 @@
     final int offset = editor.getCaretModel().getOffset();
 
     final CompletionData data = new CompletionData();
-    
-    processWords(editor, offset - 1, new TokenProcessor() {
+
+    processWords(editor, Math.max(offset - 1, 0), new TokenProcessor() {
       @Override
       public boolean processToken(int start, int end) {
         if (start > offset) {
@@ -347,5 +362,6 @@
   private static class CompletionState {
     public String oldPrefix;
     public CompletionVariant lastProposedVariant;
+    public boolean fromOtherFiles;
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java
index 4efaf7f..1565d9e 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/completion/impl/CompletionServiceImpl.java
@@ -84,7 +84,7 @@
                                              @NotNull final CompletionContributor contributor) {
     final PsiElement position = parameters.getPosition();
     final String prefix = CompletionData.findPrefixStatic(position, parameters.getOffset());
-    final String textBeforePosition = parameters.getPosition().getContainingFile().getText().substring(0, parameters.getOffset());
+    final int lengthOfTextBeforePosition = parameters.getOffset();
     ProgressIndicator indicator = ProgressManager.getInstance().getProgressIndicator();
     if (!(indicator instanceof CompletionProgressIndicator)) {
       throw new AssertionError("createResultSet may be invoked only from completion thread: " + indicator + "!=" + getCurrentCompletion() + "; phase set at " + ourPhaseTrace);
@@ -92,7 +92,7 @@
     CompletionProgressIndicator process = (CompletionProgressIndicator)indicator;
     CamelHumpMatcher matcher = new CamelHumpMatcher(prefix);
     CompletionSorterImpl sorter = defaultSorter(parameters, matcher);
-    return new CompletionResultSetImpl(consumer, textBeforePosition, matcher, contributor,parameters, sorter, process, null);
+    return new CompletionResultSetImpl(consumer, lengthOfTextBeforePosition, matcher, contributor,parameters, sorter, process, null);
   }
 
   @Override
@@ -105,13 +105,13 @@
   }
 
   private static class CompletionResultSetImpl extends CompletionResultSet {
-    private final String myTextBeforePosition;
+    private final int myLengthOfTextBeforePosition;
     private final CompletionParameters myParameters;
     private final CompletionSorterImpl mySorter;
     private final CompletionProgressIndicator myProcess;
     @Nullable private final CompletionResultSetImpl myOriginal;
 
-    public CompletionResultSetImpl(final Consumer<CompletionResult> consumer, final String textBeforePosition,
+    public CompletionResultSetImpl(final Consumer<CompletionResult> consumer, final int lengthOfTextBeforePosition,
                                    final PrefixMatcher prefixMatcher,
                                    CompletionContributor contributor,
                                    CompletionParameters parameters,
@@ -119,7 +119,7 @@
                                    @NotNull CompletionProgressIndicator process,
                                    @Nullable CompletionResultSetImpl original) {
       super(prefixMatcher, consumer, contributor);
-      myTextBeforePosition = textBeforePosition;
+      myLengthOfTextBeforePosition = lengthOfTextBeforePosition;
       myParameters = parameters;
       mySorter = sorter;
       myProcess = process;
@@ -142,7 +142,7 @@
     @Override
     @NotNull
     public CompletionResultSet withPrefixMatcher(@NotNull final PrefixMatcher matcher) {
-      return new CompletionResultSetImpl(getConsumer(), myTextBeforePosition, matcher, myContributor, myParameters, mySorter, myProcess, this);
+      return new CompletionResultSetImpl(getConsumer(), myLengthOfTextBeforePosition, matcher, myContributor, myParameters, mySorter, myProcess, this);
     }
 
     @Override
@@ -165,7 +165,7 @@
     @NotNull
     @Override
     public CompletionResultSet withRelevanceSorter(@NotNull CompletionSorter sorter) {
-      return new CompletionResultSetImpl(getConsumer(), myTextBeforePosition, getPrefixMatcher(), myContributor, myParameters, (CompletionSorterImpl)sorter, myProcess, this);
+      return new CompletionResultSetImpl(getConsumer(), myLengthOfTextBeforePosition, getPrefixMatcher(), myContributor, myParameters, (CompletionSorterImpl)sorter, myProcess, this);
     }
 
     @Override
@@ -183,7 +183,7 @@
     public void restartCompletionOnPrefixChange(ElementPattern<String> prefixCondition) {
       final CompletionProgressIndicator indicator = getCompletionService().getCurrentCompletion();
       if (indicator != null) {
-        indicator.addWatchedPrefix(myTextBeforePosition.length() - getPrefixMatcher().getPrefix().length(), prefixCondition);
+        indicator.addWatchedPrefix(myLengthOfTextBeforePosition - getPrefixMatcher().getPrefix().length(), prefixCondition);
       }
     }
 
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
index c37adbf..d536fa7 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/DaemonTooltipRendererProvider.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -24,6 +24,7 @@
 import com.intellij.codeInsight.hint.LineTooltipRenderer;
 import com.intellij.codeInsight.hint.TooltipLinkHandlerEP;
 import com.intellij.codeInsight.hint.TooltipRenderer;
+import com.intellij.codeInspection.ui.DefaultInspectionToolPresentation;
 import com.intellij.openapi.editor.Editor;
 import com.intellij.openapi.editor.ex.ErrorStripTooltipRendererProvider;
 import com.intellij.openapi.editor.impl.TrafficTooltipRenderer;
@@ -42,8 +43,6 @@
 import java.util.Collection;
 import java.util.Comparator;
 import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
 
 public class DaemonTooltipRendererProvider implements ErrorStripTooltipRendererProvider {
   @NonNls private static final String END_MARKER = "<!-- end marker -->";
@@ -143,20 +142,7 @@
         if (ref != null) {
           String description = TooltipLinkHandlerEP.getDescription(ref, editor);
           if (description != null) {
-            description = UIUtil.getHtmlBody(description);
-            final int descriptionEnd = description.indexOf("<!-- tooltip end -->");
-            if (descriptionEnd < 0) {
-              final Pattern pattern = Pattern.compile(".*Use.*(the (panel|checkbox|checkboxes|field|button|controls).*below).*", Pattern.DOTALL);
-              final Matcher matcher = pattern.matcher(description);
-              int startFindIdx = 0;
-              while (matcher.find(startFindIdx)) {
-                final int end = matcher.end(1);
-                startFindIdx = end;
-                description = description.substring(0, matcher.start(1)) + " inspection settings " + description.substring(end);
-              }
-            } else {
-              description = description.substring(0, descriptionEnd);
-            }
+            description = DefaultInspectionToolPresentation.stripUIRefsFromInspectionDescription(UIUtil.getHtmlBody(description));
             text += UIUtil.getHtmlBody(problem).replace(DaemonBundle.message("inspection.extended.description"),
                                                         DaemonBundle.message("inspection.collapse.description")) +
                     END_MARKER + "<p>" + description + BORDER_LINE;
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java
index 22e3b55..208e382 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/PassExecutorService.java
@@ -492,7 +492,7 @@
 
   public static void log(ProgressIndicator progressIndicator, TextEditorHighlightingPass pass, @NonNls Object... info) {
     if (LOG.isDebugEnabled()) {
-      String docText = pass == null ? "" : StringUtil.first(pass.getDocument().getText(), 10, true);
+      CharSequence docText = pass == null ? "" : StringUtil.first(pass.getDocument().getCharsSequence(), 10, true);
       synchronized (PassExecutorService.class) {
         StringBuilder s = new StringBuilder();
         for (Object o : info) {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java
index 9ada20e..0250a15 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/daemon/impl/ShowIntentionsPass.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -45,6 +45,7 @@
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
+import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.Pair;
 import com.intellij.psi.IntentionFilterOwner;
 import com.intellij.psi.PsiDocumentManager;
@@ -132,10 +133,10 @@
   }
 
   public static class IntentionsInfo {
-    public final List<HighlightInfo.IntentionActionDescriptor> intentionsToShow = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
-    public final List<HighlightInfo.IntentionActionDescriptor> errorFixesToShow = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
-    public final List<HighlightInfo.IntentionActionDescriptor> inspectionFixesToShow = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
-    public final List<HighlightInfo.IntentionActionDescriptor> guttersToShow = new ArrayList<HighlightInfo.IntentionActionDescriptor>();
+    public final List<HighlightInfo.IntentionActionDescriptor> intentionsToShow = ContainerUtil.createLockFreeCopyOnWriteList();
+    public final List<HighlightInfo.IntentionActionDescriptor> errorFixesToShow = ContainerUtil.createLockFreeCopyOnWriteList();
+    public final List<HighlightInfo.IntentionActionDescriptor> inspectionFixesToShow = ContainerUtil.createLockFreeCopyOnWriteList();
+    public final List<HighlightInfo.IntentionActionDescriptor> guttersToShow = ContainerUtil.createLockFreeCopyOnWriteList();
 
     public void filterActions(@NotNull IntentionFilterOwner.IntentionActionsFilter actionsFilter) {
       filter(intentionsToShow, actionsFilter);
@@ -220,16 +221,13 @@
     if (myIntentionsInfo.isEmpty()) {
       return;
     }
-    myShowBulb = !myIntentionsInfo.guttersToShow.isEmpty();
-    if (!myShowBulb) {
-      for (HighlightInfo.IntentionActionDescriptor descriptor : ContainerUtil.concat(myIntentionsInfo.errorFixesToShow, myIntentionsInfo.inspectionFixesToShow,myIntentionsInfo.intentionsToShow)) {
-        final IntentionAction action = descriptor.getAction();
-        if (IntentionManagerSettings.getInstance().isShowLightBulb(action)) {
-          myShowBulb = true;
-          break;
+    myShowBulb = !myIntentionsInfo.guttersToShow.isEmpty() ||
+      ContainerUtil.exists(ContainerUtil.concat(myIntentionsInfo.errorFixesToShow, myIntentionsInfo.inspectionFixesToShow,myIntentionsInfo.intentionsToShow), new Condition<HighlightInfo.IntentionActionDescriptor>() {
+        @Override
+        public boolean value(HighlightInfo.IntentionActionDescriptor descriptor) {
+          return IntentionManagerSettings.getInstance().isShowLightBulb(descriptor.getAction());
         }
-      }
-    }
+      });
   }
 
   private void updateActions(@NotNull DaemonCodeAnalyzerImpl codeAnalyzer) {
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java
index e83d2d7..ffbfece 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/intention/impl/IntentionHintComponent.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -48,6 +48,7 @@
 import com.intellij.openapi.ui.popup.LightweightWindowEvent;
 import com.intellij.openapi.ui.popup.ListPopup;
 import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.psi.PsiFile;
 import com.intellij.refactoring.BaseRefactoringIntentionAction;
@@ -57,6 +58,7 @@
 import com.intellij.ui.awt.RelativePoint;
 import com.intellij.util.Alarm;
 import com.intellij.util.IncorrectOperationException;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.EmptyIcon;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -104,11 +106,10 @@
 
   private static final int DELAY = 500;
   private final MyComponentHint myComponentHint;
-  private boolean myPopupShown = false;
+  private volatile boolean myPopupShown = false;
   private boolean myDisposed = false;
-  private ListPopup myPopup;
+  private volatile ListPopup myPopup;
   private final PsiFile myFile;
-  private static final int LIGHTBULB_OFFSET = 20;
 
   private PopupMenuListener myOuterComboboxPopupListener;
 
@@ -118,6 +119,7 @@
                                                          @NotNull Editor editor,
                                                          @NotNull ShowIntentionsPass.IntentionsInfo intentions,
                                                          boolean showExpanded) {
+    ApplicationManager.getApplication().assertIsDispatchThread();
     final Point position = getHintPosition(editor);
     return showIntentionHint(project, file, editor, intentions, showExpanded, position);
   }
@@ -129,6 +131,7 @@
                                                          @NotNull ShowIntentionsPass.IntentionsInfo intentions,
                                                          boolean showExpanded,
                                                          @NotNull Point position) {
+    ApplicationManager.getApplication().assertIsDispatchThread();
     final IntentionHintComponent component = new IntentionHintComponent(project, file, editor, intentions);
 
     component.showIntentionHintImpl(!showExpanded, position);
@@ -177,7 +180,7 @@
   //true if actions updated, there is nothing to do
   //false if has to recreate popup, no need to reshow
   //null if has to reshow
-  public synchronized Boolean updateActions(ShowIntentionsPass.IntentionsInfo intentions) {
+  public Boolean updateActions(@NotNull ShowIntentionsPass.IntentionsInfo intentions) {
     if (myPopup.isDisposed()) return null;
     if (!myFile.isValid()) return null;
     IntentionListStep step = (IntentionListStep)myPopup.getListStep();
@@ -204,7 +207,8 @@
     return values.get(index).getAction();
   }
 
-  public synchronized void recreate() {
+  public void recreate() {
+    ApplicationManager.getApplication().assertIsDispatchThread();
     IntentionListStep step = (IntentionListStep)myPopup.getListStep();
     recreateMyPopup(step);
   }
@@ -298,31 +302,25 @@
                                  @NotNull PsiFile file,
                                  @NotNull final Editor editor,
                                  @NotNull ShowIntentionsPass.IntentionsInfo intentions) {
-    ApplicationManager.getApplication().assertReadAccessAllowed();
+    ApplicationManager.getApplication().assertIsDispatchThread();
     myFile = file;
     myEditor = editor;
 
     setLayout(new BorderLayout());
     setOpaque(false);
 
-    boolean showRefactoringsBulb = false;
-    for (HighlightInfo.IntentionActionDescriptor descriptor : intentions.inspectionFixesToShow) {
-      if (descriptor.getAction() instanceof BaseRefactoringIntentionAction) {
-        showRefactoringsBulb = true;
-        break;
+    boolean showRefactoringsBulb = ContainerUtil.exists(intentions.inspectionFixesToShow, new Condition<HighlightInfo.IntentionActionDescriptor>() {
+      @Override
+      public boolean value(HighlightInfo.IntentionActionDescriptor descriptor) {
+        return descriptor.getAction() instanceof BaseRefactoringIntentionAction;
       }
-    }
-    boolean showFix = false;
-    if (!showRefactoringsBulb) {
-      showFix = false;
-      for (final HighlightInfo.IntentionActionDescriptor pairs : intentions.errorFixesToShow) {
-        IntentionAction fix = pairs.getAction();
-        if (IntentionManagerSettings.getInstance().isShowLightBulb(fix)) {
-          showFix = true;
-          break;
-        }
+    });
+    boolean showFix = !showRefactoringsBulb && ContainerUtil.exists(intentions.errorFixesToShow, new Condition<HighlightInfo.IntentionActionDescriptor>() {
+      @Override
+      public boolean value(HighlightInfo.IntentionActionDescriptor descriptor) {
+        return IntentionManagerSettings.getInstance().isShowLightBulb(descriptor.getAction());
       }
-    }
+    });
 
     Icon smartTagIcon = showRefactoringsBulb ? AllIcons.Actions.RefactoringBulb : showFix ? AllIcons.Actions.QuickfixBulb : AllIcons.Actions.IntentionBulb;
 
@@ -404,11 +402,13 @@
   }
 
   private void closePopup() {
+    ApplicationManager.getApplication().assertIsDispatchThread();
     myPopup.cancel();
     myPopupShown = false;
   }
 
   private void showPopup() {
+    ApplicationManager.getApplication().assertIsDispatchThread();
     if (myPopup == null || myPopup.isDisposed()) return;
 
     if (isShowing()) {
@@ -424,6 +424,7 @@
   }
 
   private void recreateMyPopup(@NotNull IntentionListStep step) {
+    ApplicationManager.getApplication().assertIsDispatchThread();
     if (myPopup != null) {
       Disposer.dispose(myPopup);
     }
@@ -468,7 +469,7 @@
     });
   }
 
-  void canceled(IntentionListStep intentionListStep) {
+  void canceled(@NotNull IntentionListStep intentionListStep) {
     if (myPopup.getListStep() != intentionListStep || myDisposed) {
       return;
     }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
index f66fb88..b16cfe8 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/navigation/CtrlMouseHandler.java
@@ -916,12 +916,13 @@
   private static TextAttributes patchAttributesColor(TextAttributes attributes, TextRange range, Editor editor) {
     int line = editor.offsetToLogicalPosition(range.getStartOffset()).line;
     for (RangeHighlighter highlighter : editor.getMarkupModel().getAllHighlighters()) {
+      if (!highlighter.isValid()) continue;
       if (highlighter.getTargetArea() == HighlighterTargetArea.LINES_IN_RANGE &&
           editor.offsetToLogicalPosition(highlighter.getStartOffset()).line == line) {
         TextAttributes textAttributes = highlighter.getTextAttributes();
         if (textAttributes != null) {
           Color color = textAttributes.getBackgroundColor();
-          if (color.getBlue() > 128 && color.getRed() < 128 && color.getGreen() < 128) {
+          if (color != null && color.getBlue() > 128 && color.getRed() < 128 && color.getGreen() < 128) {
             TextAttributes clone = attributes.clone();
             clone.setForegroundColor(Color.orange);
             clone.setEffectColor(Color.orange);
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 8f6086c..8c583ca 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/CustomTemplateCallback.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2010 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -96,16 +96,9 @@
   public List<TemplateImpl> filterApplicableCandidates(Collection<? extends TemplateImpl> candidates) {
     List<TemplateImpl> result = new ArrayList<TemplateImpl>();
     for (TemplateImpl candidate : candidates) {
-      if (TemplateManagerImpl.isApplicable(myFile, myOffset, candidate)) {
+      if (!candidate.isDeactivated() && TemplateManagerImpl.isApplicable(myFile, myOffset, candidate)) {
         result.add(candidate);
       }
-      /*TemplateContext context = candidate.getTemplateContext();
-      for (TemplateContextType contextType : contextTypes) {
-        if (context.isEnabled(contextType)) {
-          result.add(candidate);
-          break;
-        }
-      }*/
     }
     return result;
   }
diff --git a/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java b/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java
index 29125be..26d4652 100644
--- a/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java
+++ b/platform/lang-impl/src/com/intellij/codeInsight/template/TemplateBuilderImpl.java
@@ -115,7 +115,8 @@
   }
 
   public void replaceElement(PsiElement element, TextRange textRange, String primaryVariableName, String otherVariableName, boolean alwaysStopAt) {
-    final RangeMarker key = myDocument.createRangeMarker(textRange.shiftRight(element.getTextRange().getStartOffset()));
+    final TextRange elementTextRange = InjectedLanguageManager.getInstance(element.getProject()).injectedToHost(element, element.getTextRange());
+    final RangeMarker key = myDocument.createRangeMarker(textRange.shiftRight(elementTextRange.getStartOffset()));
     myAlwaysStopAtMap.put(key, alwaysStopAt ? Boolean.TRUE : Boolean.FALSE);
     myVariableNamesMap.put(key, primaryVariableName);
     myVariableExpressions.put(key, otherVariableName);
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/Browser.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/Browser.java
index 2dc1cf0..5a0b5a4 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ui/Browser.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/Browser.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -450,7 +450,7 @@
       if (description == null) {
         description = underConstruction;
       }
-      page.append(UIUtil.getHtmlBody(description));
+      page.append(DefaultInspectionToolPresentation.stripUIRefsFromInspectionDescription(UIUtil.getHtmlBody(description)));
 
       page.append("</td></tr></table>");
       myHTMLViewer.setText(XmlStringUtil.wrapInHtml(page));
diff --git a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java
index 14be260e..40f2b22 100644
--- a/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java
+++ b/platform/lang-impl/src/com/intellij/codeInspection/ui/DefaultInspectionToolPresentation.java
@@ -51,6 +51,8 @@
 import javax.swing.tree.DefaultTreeModel;
 import java.io.*;
 import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 public class DefaultInspectionToolPresentation implements ProblemDescriptionsProcessor, InspectionToolPresentation {
   @NotNull private final InspectionToolWrapper myToolWrapper;
@@ -91,6 +93,23 @@
     return FileStatus.NOT_CHANGED;
   }
 
+  public static String stripUIRefsFromInspectionDescription(String description) {
+    final int descriptionEnd = description.indexOf("<!-- tooltip end -->");
+    if (descriptionEnd < 0) {
+      final Pattern pattern = Pattern.compile(".*Use.*(the (panel|checkbox|checkboxes|field|button|controls).*below).*", Pattern.DOTALL);
+      final Matcher matcher = pattern.matcher(description);
+      int startFindIdx = 0;
+      while (matcher.find(startFindIdx)) {
+        final int end = matcher.end(1);
+        startFindIdx = end;
+        description = description.substring(0, matcher.start(1)) + " inspection settings " + description.substring(end);
+      }
+    } else {
+      description = description.substring(0, descriptionEnd);
+    }
+    return description;
+  }
+
   protected static HighlightSeverity getSeverity(@NotNull RefElement element,
                                                  @NotNull GlobalInspectionContextImpl context,
                                                  @NotNull InspectionToolWrapper thisToolWrapper) {
diff --git a/platform/lang-impl/src/com/intellij/execution/runners/BaseConsoleExecuteActionHandler.java b/platform/lang-impl/src/com/intellij/execution/runners/BaseConsoleExecuteActionHandler.java
index 3646620..396c663 100644
--- a/platform/lang-impl/src/com/intellij/execution/runners/BaseConsoleExecuteActionHandler.java
+++ b/platform/lang-impl/src/com/intellij/execution/runners/BaseConsoleExecuteActionHandler.java
@@ -42,7 +42,7 @@
     myAddCurrentToHistory = addCurrentToHistory;
   }
 
-  public void runExecuteAction(LanguageConsoleImpl languageConsole) {
+  public void runExecuteAction(@NotNull LanguageConsoleImpl languageConsole) {
     // process input and add to history
     Document document = languageConsole.getCurrentEditor().getDocument();
     String text = document.getText();
@@ -56,7 +56,7 @@
 
     languageConsole.setInputText("");
 
-    UndoManager manager = languageConsole.getProject() == null ? UndoManager.getGlobalInstance() : UndoManager.getInstance(languageConsole.getProject());
+    UndoManager manager = UndoManager.getInstance(languageConsole.getProject());
     ((UndoManagerImpl)manager).invalidateActionsFor(DocumentReferenceManager.getInstance().create(document));
 
     myConsoleHistoryModel.addToHistory(text);
diff --git a/platform/lang-impl/src/com/intellij/facet/impl/ui/FacetErrorPanel.java b/platform/lang-impl/src/com/intellij/facet/impl/ui/FacetErrorPanel.java
index 7b2675c..5c66162 100644
--- a/platform/lang-impl/src/com/intellij/facet/impl/ui/FacetErrorPanel.java
+++ b/platform/lang-impl/src/com/intellij/facet/impl/ui/FacetErrorPanel.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -20,8 +20,8 @@
 import com.intellij.facet.ui.FacetEditorValidator;
 import com.intellij.facet.ui.FacetValidatorsManager;
 import com.intellij.facet.ui.ValidationResult;
+import com.intellij.icons.AllIcons;
 import com.intellij.ide.IdeBundle;
-import com.intellij.openapi.ui.Messages;
 import com.intellij.ui.UserActivityListener;
 import com.intellij.ui.UserActivityWatcher;
 import com.intellij.util.containers.ContainerUtil;
@@ -53,7 +53,7 @@
   public FacetErrorPanel() {
     myValidatorsManager = new FacetValidatorsManagerImpl();
     myWarningLabel = new JLabel();
-    myWarningLabel.setIcon(Messages.getWarningIcon());
+    myWarningLabel.setIcon(AllIcons.General.WarningDialog);
     myQuickFixButton.addActionListener(new ActionListener() {
       @Override
       public void actionPerformed(final ActionEvent e) {
diff --git a/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java b/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java
index cc332d2..4ced6fb 100644
--- a/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java
+++ b/platform/lang-impl/src/com/intellij/find/actions/FindInPathAction.java
@@ -31,6 +31,10 @@
 public class FindInPathAction extends AnAction implements DumbAware {
   static final NotificationGroup NOTIFICATION_GROUP = NotificationGroup.toolWindowGroup("FindInPath", ToolWindowId.FIND, false);
 
+  { // enabled in modal content for find in path <-> replace in path modal dialog transition
+    setEnabledInModalContext(true);
+  }
+
   @Override
   public void actionPerformed(AnActionEvent e) {
     DataContext dataContext = e.getDataContext();
diff --git a/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java b/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java
index ae7a023..eef79eed 100644
--- a/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java
+++ b/platform/lang-impl/src/com/intellij/find/actions/ReplaceInPathAction.java
@@ -22,6 +22,10 @@
 import com.intellij.openapi.project.Project;
 
 public class ReplaceInPathAction extends AnAction {
+  { // enabled in modal content for find in path <-> replace in path modal dialog transition
+    setEnabledInModalContext(true);
+  }
+
   @Override
   public void actionPerformed(AnActionEvent e) {
     DataContext dataContext = e.getDataContext();
diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java
index 9721e1b..45622f0 100644
--- a/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java
+++ b/platform/lang-impl/src/com/intellij/find/impl/FindInProjectUtil.java
@@ -23,7 +23,6 @@
 import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.actionSystem.LangDataKeys;
-import com.intellij.openapi.actionSystem.PlatformDataKeys;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ApplicationNamesInfo;
 import com.intellij.openapi.editor.Document;
@@ -114,6 +113,13 @@
     if (model.getModuleName() == null || editor == null) {
       model.setDirectoryName(directoryName);
       model.setProjectScope(directoryName == null && module == null && !model.isCustomScope() || editor != null);
+
+      // for convenience set directory name to directory of current file, note that we doesn't change default projectScope
+      if (directoryName == null) {
+        VirtualFile virtualFile = CommonDataKeys.VIRTUAL_FILE.getData(dataContext);
+        if (virtualFile != null && !virtualFile.isDirectory()) virtualFile = virtualFile.getParent();
+        if (virtualFile != null) model.setDirectoryName(virtualFile.getPresentableUrl());
+      }
     }
   }
 
diff --git a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java
index b35309e..59c3ca8 100644
--- a/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java
+++ b/platform/lang-impl/src/com/intellij/find/impl/FindManagerImpl.java
@@ -454,7 +454,7 @@
       SyntaxHighlighter highlighter = getHighlighter(file, lang);
 
       if (highlighter == null) {
-        LOG.error("Syntax highlighter is null:"+file);
+        // no syntax highlighter -> no search
         return NOT_FOUND_RESULT;
       }
 
diff --git a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
index 81b51bf..558a29c 100644
--- a/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
+++ b/platform/lang-impl/src/com/intellij/ide/actions/SearchEverywhereAction.java
@@ -29,7 +29,10 @@
 import com.intellij.ide.ui.search.OptionDescription;
 import com.intellij.ide.ui.search.SearchableOptionsRegistrarImpl;
 import com.intellij.ide.util.DefaultPsiElementCellRenderer;
+import com.intellij.ide.util.PropertiesComponent;
 import com.intellij.ide.util.gotoByName.*;
+import com.intellij.navigation.ItemPresentation;
+import com.intellij.navigation.NavigationItem;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.actionSystem.*;
 import com.intellij.openapi.actionSystem.ex.AnActionListener;
@@ -65,6 +68,7 @@
 import com.intellij.openapi.wm.ToolWindowManager;
 import com.intellij.openapi.wm.WindowManager;
 import com.intellij.openapi.wm.impl.IdeFrameImpl;
+import com.intellij.pom.Navigatable;
 import com.intellij.psi.PsiDirectory;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
@@ -92,6 +96,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
+import javax.swing.border.EmptyBorder;
 import javax.swing.event.DocumentEvent;
 import java.awt.*;
 import java.awt.event.*;
@@ -105,6 +110,7 @@
  * @author Konstantin Bulenkov
  */
 public class SearchEverywhereAction extends AnAction implements CustomComponentAction, DumbAware{
+  public static final String SE_HISTORY_KEY = "SearchEverywhereHistory";
   public static final int SEARCH_FIELD_COLUMNS = 25;
   private static final int MAX_CLASSES = 6;
   private static final int MAX_FILES = 6;
@@ -113,6 +119,7 @@
   private static final int MAX_SETTINGS = 5;
   private static final int MAX_ACTIONS = 5;
   private static final int MAX_RECENT_FILES = 10;
+  public static final int MAX_SEARCH_EVERYWHERE_HISTORY = 50;
 
   private SearchEverywhereAction.MyListRenderer myRenderer;
   MySearchTextField myPopupField;
@@ -131,13 +138,14 @@
   private int myMoreFilesIndex = -1;
   private int myMoreActionsIndex = -1;
   private int myMoreSettingsIndex = -1;
+  private int myMoreSymbolsIndex = -1;
   private TitleIndexes myTitleIndexes;
   private Map<String, String> myConfigurables = new HashMap<String, String>();
 
   private Alarm myAlarm = new Alarm(Alarm.ThreadToUse.POOLED_THREAD, ApplicationManager.getApplication());
   private Alarm myUpdateAlarm = new Alarm(ApplicationManager.getApplication());
-  private JBList myList = new JBList(myListModel);
-  private JCheckBox myNonProjectCheckBox = new JCheckBox();
+  private JBList myList;
+  private JCheckBox myNonProjectCheckBox;
   private AnActionEvent myActionEvent;
   private Component myContextComponent;
   private CalcThread myCalcThread;
@@ -149,6 +157,7 @@
   private static AtomicLong ourLastTimePressed = new AtomicLong(0);
   private static AtomicBoolean showAll = new AtomicBoolean(false);
   private ArrayList<VirtualFile> myAlreadyAddedFiles = new ArrayList<VirtualFile>();
+  private int myHistoryIndex = 0;
 
   static {
     IdeEventQueue.getInstance().addPostprocessor(new IdeEventQueue.EventDispatcher() {
@@ -176,6 +185,9 @@
           } else {
             ourLastTimePressed.set(System.currentTimeMillis());
             ourOtherKeyWasPressed.set(true);
+            if (keyCode == KeyEvent.VK_ESCAPE || keyCode == KeyEvent.VK_TAB)  {
+              ourLastTimePressed.set(0);
+            }
           }
           resetState();
         }
@@ -230,7 +242,7 @@
                   }
                   final AnActionEvent anActionEvent = new AnActionEvent(event,
                                                                         DataManager.getInstance().getDataContext(IdeFocusManager.findInstance().getFocusOwner()),
-                                                                        ActionPlaces.UNKNOWN,
+                                                                        ActionPlaces.MAIN_MENU,
                                                                         action.getTemplatePresentation(),
                                                                         actionManager,
                                                                         0);
@@ -250,8 +262,8 @@
       @Override
       protected void paintComponent(Graphics g) {
         if (myBalloon != null && !myBalloon.isDisposed() && myActionEvent != null && myActionEvent.getInputEvent() instanceof MouseEvent) {
-          ((Graphics2D)g).setPaint(new GradientPaint(0,0, new JBColor(new Color(147, 162, 174), new Color(64, 80, 94)), 0, getHeight(),
-                                                     new JBColor(new Color(116, 128, 143), new Color(53, 65, 87))));
+          final Gradient gradient = getGradientColors();
+          ((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor()));
           g.fillRect(0,0,getWidth(), getHeight());
         } else {
           super.paintComponent(g);
@@ -299,9 +311,32 @@
     return panel;
   }
 
+  private static Gradient getGradientColors() {
+    return new Gradient(
+      new JBColor(new Color(101, 147, 242), new Color(64, 80, 94)),
+      new JBColor(new Color(46, 111, 205), new Color(53, 65, 87)));
+  }
 
   public SearchEverywhereAction() {
+    updateComponents();
+    //noinspection SSBasedInspection
+    SwingUtilities.invokeLater(new Runnable() {
+      public void run() {
+        onFocusLost();
+      }
+    });
+
+  }
+
+  private void updateComponents() {
     myRenderer = new MyListRenderer();
+    myList = new JBList(myListModel) {
+      @Override
+      public Dimension getPreferredSize() {
+        final Dimension size = super.getPreferredSize();
+        return new Dimension(Math.min(size.width, 800), size.height);
+      }
+    };
     myList.setCellRenderer(myRenderer);
     myList.addMouseListener(new MouseAdapter() {
       @Override
@@ -314,6 +349,7 @@
       }
     });
 
+    myNonProjectCheckBox = new JCheckBox();
     myNonProjectCheckBox.setOpaque(false);
     myNonProjectCheckBox.setAlignmentX(1.0f);
     myNonProjectCheckBox.addActionListener(new ActionListener() {
@@ -337,13 +373,6 @@
         }
       }
     });
-    //noinspection SSBasedInspection
-    SwingUtilities.invokeLater(new Runnable() {
-      public void run() {
-        onFocusLost();
-      }
-    });
-
   }
 
   private void initTooltip(JLabel label) {
@@ -496,6 +525,7 @@
       else if (index == myMoreFilesIndex) actionId = "GotoFile";
       else if (index == myMoreSettingsIndex) actionId = "ShowSettings";
       else if (index == myMoreActionsIndex) actionId = "GotoAction";
+      else if (index == myMoreSymbolsIndex) actionId = "GotoSymbol";
       if (actionId != null) {
         final AnAction action = ActionManager.getInstance().getAction(actionId);
         GotoActionAction.openOptionOrPerformAction(action, getField().getText(), project, getField(), myActionEvent);
@@ -511,6 +541,15 @@
     if (myPopup != null && myPopup.isVisible()) {
       myPopup.cancel();
     }
+
+    if (value instanceof BooleanOptionDescription) {
+      final BooleanOptionDescription option = (BooleanOptionDescription)value;
+      option.setOptionState(!option.isOptionEnabled());
+      myList.revalidate();
+      myList.repaint();
+      return;
+    }
+
     AccessToken token = ApplicationManager.getApplication().acquireReadActionLock();
     try {
       if (value instanceof PsiElement) {
@@ -524,28 +563,30 @@
           return;
         }
       }
-      else {
+      else if (isActionValue(value) || isSetting(value)) {
         focusManager.requestDefaultFocus(true);
         final Component comp = myContextComponent;
         final AnActionEvent event = myActionEvent;
         IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
           @Override
           public void run() {
-            if (value instanceof BooleanOptionDescription) {
-              final BooleanOptionDescription option = (BooleanOptionDescription)value;
-              option.setOptionState(!option.isOptionEnabled());
+            Component c = comp;
+            if (c == null) {
+              c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
             }
-            else {
-              Component c = comp;
-              if (c == null) {
-                c = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
-              }
-              GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event);
-            }
+            GotoActionAction.openOptionOrPerformAction(value, pattern, project, c, event);
           }
         });
         return;
       }
+      else if (value instanceof Navigatable) {
+        IdeFocusManager.getInstance(project).doWhenFocusSettlesDown(new Runnable() {
+          @Override
+          public void run() {
+            OpenSourceUtil.navigate(true, (Navigatable)value);
+          }
+        });
+      }
     }
     finally {
       token.finish();
@@ -555,7 +596,7 @@
   }
 
   private boolean isMoreItem(int index) {
-    return index == myMoreClassesIndex || index == myMoreFilesIndex || index == myMoreSettingsIndex || index == myMoreActionsIndex;
+    return index == myMoreClassesIndex || index == myMoreFilesIndex || index == myMoreSettingsIndex || index == myMoreActionsIndex || index == myMoreSymbolsIndex;
   }
 
   private void rebuildList(final String pattern) {
@@ -584,10 +625,13 @@
       return;
     }
     if (e == null && myFocusOwner != null) {
-      e = new AnActionEvent(me, DataManager.getInstance().getDataContext(myFocusComponent), ActionPlaces.UNKNOWN, getTemplatePresentation(), ActionManager.getInstance(), 0);
+      e = new AnActionEvent(me, DataManager.getInstance().getDataContext(myFocusOwner), ActionPlaces.UNKNOWN, getTemplatePresentation(), ActionManager.getInstance(), 0);
     }
     if (e == null) return;
+
+    updateComponents();
     myContextComponent = PlatformDataKeys.CONTEXT_COMPONENT.getData(e.getDataContext());
+    final Project project = e.getProject();
     Window wnd = myContextComponent != null ? SwingUtilities.windowForComponent(myContextComponent)
       : KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
     if (wnd == null && myContextComponent instanceof Window) {
@@ -601,35 +645,56 @@
     myPopupField = new MySearchTextField();
     initSearchField(myPopupField);
     myPopupField.setOpaque(false);
-    myPopupField.getTextEditor().setColumns(SEARCH_FIELD_COLUMNS);
+    final JTextField editor = myPopupField.getTextEditor();
+    editor.setColumns(SEARCH_FIELD_COLUMNS);
     final JPanel panel = new JPanel(new BorderLayout()) {
       @Override
       protected void paintComponent(Graphics g) {
-        ((Graphics2D)g).setPaint(new GradientPaint(0,0, new JBColor(new Color(147, 162, 174), new Color(64, 80, 94)), 0, getHeight(),
-                                                   new JBColor(new Color(116, 128, 143), new Color(53, 65, 87))));
+        final Gradient gradient = getGradientColors();
+        ((Graphics2D)g).setPaint(new GradientPaint(0, 0, gradient.getStartColor(), 0, getHeight(), gradient.getEndColor()));
         g.fillRect(0, 0, getWidth(), getHeight());
       }
    };
     final JLabel title = new JLabel(" Search Everywhere:       ");
     final JPanel topPanel = new NonOpaquePanel(new BorderLayout());
-    title.setForeground(new JBColor(Gray._50, Gray._180));
+    title.setForeground(new JBColor(Gray._240, Gray._200));
     if (SystemInfo.isMac) {
       title.setFont(title.getFont().deriveFont(Font.BOLD, title.getFont().getSize() - 1f));
     } else {
       title.setFont(title.getFont().deriveFont(Font.BOLD));
     }
     topPanel.add(title, BorderLayout.WEST);
+    myNonProjectCheckBox.setForeground(new JBColor(Gray._240, Gray._200));
     myNonProjectCheckBox.setText("Include non-project items (" + getShortcut() + ")");
     topPanel.add(myNonProjectCheckBox, BorderLayout.EAST);
     panel.add(myPopupField, BorderLayout.CENTER);
     panel.add(topPanel, BorderLayout.NORTH);
     panel.setBorder(IdeBorderFactory.createEmptyBorder(3, 5, 4, 5));
-    final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, myPopupField.getTextEditor());
+    final ComponentPopupBuilder builder = JBPopupFactory.getInstance().createComponentPopupBuilder(panel, editor);
     myBalloon = builder
       .setCancelOnClickOutside(true)
       .setModalContext(false)
+      .setCancelCallback(new Computable<Boolean>() {
+        @Override
+        public Boolean compute() {
+          final String last = editor.getText().trim();
+          if (project == null || project.isDisposed() || !project.isInitialized()) {
+            return true;
+          }
+          final PropertiesComponent storage = PropertiesComponent.getInstance(project);
+          final String historyString = storage.getValue(SE_HISTORY_KEY);
+          List<String> history = StringUtil.isEmpty(historyString) ? new ArrayList<String>() : StringUtil.split(historyString, "\n");
+          history.remove(last);
+          history.add(0, last);
+          if (history.size() > MAX_SEARCH_EVERYWHERE_HISTORY) {
+            history = history.subList(0, MAX_SEARCH_EVERYWHERE_HISTORY);
+          }
+          storage.setValue(SE_HISTORY_KEY, StringUtil.join(history, "\n"));
+          return true;
+        }
+      })
       .createPopup();
-
+    myBalloon.getContent().setBorder(new EmptyBorder(0,0,0,0));
     final Window window = WindowManager.getInstance().suggestParentWindow(e.getProject());
 
     Component parent = UIUtil.findUltimateParent(window);
@@ -656,7 +721,7 @@
     myBalloon.show(showPoint);
     initSearchActions(myBalloon, myPopupField);
     IdeFocusManager focusManager = IdeFocusManager.getInstance(e.getProject());
-    focusManager.requestFocus(myPopupField.getTextEditor(), true);
+    focusManager.requestFocus(editor, true);
     FeatureUsageTracker.getInstance().triggerFeatureUsed(IdeActions.ACTION_SEARCH_EVERYWHERE);
   }
 
@@ -710,6 +775,28 @@
         }
       }
     }.registerCustomShortcutSet(CustomShortcutSet.fromString("ENTER"), editor, balloon);
+    new DumbAwareAction(){
+      @Override
+      public void actionPerformed(AnActionEvent e) {
+        final PropertiesComponent storage = PropertiesComponent.getInstance(e.getProject());
+        final String historyString = storage.getValue(SE_HISTORY_KEY);
+        if (historyString != null) {
+          final List<String> history = StringUtil.split(historyString, "\n");
+          if (history.size() > myHistoryIndex) {
+            final String text = history.get(myHistoryIndex);
+            editor.setText(text);
+            editor.setCaretPosition(text.length());
+            editor.moveCaretPosition(0);
+            myHistoryIndex++;
+          }
+        }
+      }
+
+      @Override
+      public void update(AnActionEvent e) {
+        e.getPresentation().setEnabled(editor.getCaretPosition() == 0);
+      }
+    }.registerCustomShortcutSet(CustomShortcutSet.fromString("LEFT"), editor, balloon);
   }
 
   private static class MySearchTextField extends SearchTextField implements DataProvider, Disposable {
@@ -792,7 +879,7 @@
                  && myProject != null
                  && (((VirtualFile)value).isDirectory()
                      || (file = PsiManager.getInstance(myProject).findFile((VirtualFile)value)) != null)) {
-        cmp = new GotoFileCellRenderer(list.getWidth()).getListCellRendererComponent(list, file == null ? value : file, index, isSelected, cellHasFocus);
+        cmp = new GotoFileCellRenderer(Math.min(800, list.getWidth())).getListCellRendererComponent(list, file == null ? value : file, index, isSelected, cellHasFocus);
       } else if (value instanceof PsiElement) {
         cmp = myPsiRenderer.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus);
       } else {
@@ -870,6 +957,12 @@
           }
 
           append(templatePresentation.getText());
+          if (actionWithParentGroup != null) {
+            final Object groupName = actionWithParentGroup.getValue();
+            if (groupName instanceof String && StringUtil.isEmpty((String)groupName)) {
+              setLocationString((String)groupName);
+            }
+          }
 
           final String groupName = actionWithParentGroup == null ? null : (String)actionWithParentGroup.getValue();
           if (!StringUtil.isEmpty(groupName)) {
@@ -888,6 +981,25 @@
             setLocationString(name);
           }
         }
+        else {
+          ItemPresentation presentation = null;
+          if (value instanceof ItemPresentation) {
+            presentation = (ItemPresentation)value;
+          }
+          else if (value instanceof NavigationItem) {
+            presentation = ((NavigationItem)value).getPresentation();
+          }
+          if (presentation != null) {
+            final String text = presentation.getPresentableText();
+            append(text == null ? value.toString() : text);
+            final String location = presentation.getLocationString();
+            if (!StringUtil.isEmpty(location)) {
+              setLocationString(location);
+            }
+            Icon icon = presentation.getIcon(false);
+            if (icon != null) setIcon(icon);
+          }
+        }
       }
       finally {
         token.finish();
@@ -1061,7 +1173,7 @@
     }
 
     private void buildActionsAndSettings(String pattern) {
-      final Set<AnAction> actions = new HashSet<AnAction>();
+      final Set<Object> actions = new HashSet<Object>();
       final Set<Object> settings = new HashSet<Object>();
       final MinusculeMatcher matcher = new MinusculeMatcher("*" +pattern, NameUtil.MatchingCaseSensitivity.NONE);
       if (myActions == null) {
@@ -1081,7 +1193,7 @@
             }
           }
           else if (!isToolWindowAction(object) && isActionValue(object) && actions.size() < MAX_ACTIONS) {
-            actions.add((AnAction)((Map.Entry)object).getKey());
+            actions.add(object);
           }
         }
       }
@@ -1110,7 +1222,7 @@
       });
     }
 
-    private void buildFiles(String pattern) {
+    private void buildFiles(final String pattern) {
       int filesCounter = 0;
       if (myFiles == null) {
         myFiles = myFileModel.getNames(showAll.get());
@@ -1129,7 +1241,9 @@
           } else if (o instanceof PsiDirectory) {
             file = ((PsiDirectory)o).getVirtualFile();
           }
-          if (file != null && (showAll.get() || scope.accept(file))) {
+          if (file != null
+              && !(pattern.indexOf(' ') != -1 && file.getName().indexOf(' ') == -1)
+              && (showAll.get() || scope.accept(file))) {
             elements.add(o);
           }
           return elements.size() < 30;
@@ -1205,7 +1319,7 @@
               for (Object file : symbols) {
                 myListModel.addElement(file);
               }
-              myMoreFilesIndex = symbols.size() >= MAX_SYMBOLS ? myListModel.size() - 1 : -1;
+              myMoreSymbolsIndex = symbols.size() >= MAX_SYMBOLS ? myListModel.size() - 1 : -1;
             }
           }
         });
@@ -1460,6 +1574,7 @@
                 }
               })
               .createPopup();
+            myPopup.getContent().setBorder(new EmptyBorder(0,0,0,0));
             Disposer.register(myPopup, new Disposable() {
               @Override
               public void dispose() {
@@ -1487,6 +1602,7 @@
                 myRenderer.myProject = null;
                 myCalcThread = null;
                 myPopup = null;
+                myHistoryIndex = 0;
                 showAll.set(false);
                 myNonProjectCheckBox.setSelected(false);
                 ActionToolbarImpl.updateAllToolbarsImmediately();
@@ -1600,18 +1716,16 @@
       size.height = 70;
     }
     Dimension sz = new Dimension(size.width, myList.getPreferredSize().height);
-    if (sz.width > 1200 || sz.height > 800) {
+    if (sz.width > 800 || sz.height > 800) {
       final JBScrollPane pane = new JBScrollPane();
       final int extraWidth = pane.getVerticalScrollBar().getWidth() + 1;
       final int extraHeight = pane.getHorizontalScrollBar().getHeight() + 1;
-      sz = new Dimension(Math.min(1000, Math.max(getField().getWidth(), size.width + extraWidth)), Math.min(800, size.height + extraHeight));
-      sz.width += 16;
-    }
-    else {
-      sz.height++;
-      sz.height++;
-      sz.width++;
-      sz.width++;
+      sz = new Dimension(Math.min(800, Math.max(getField().getWidth(), sz.width + extraWidth)), Math.min(800, sz.height + extraHeight));
+      sz.width += 20;
+      sz.height+=2;
+    } else {
+      sz.width+=2;
+      sz.height+=2;
     }
     myPopup.setSize(sz);
     if (myActionEvent != null && myActionEvent.getInputEvent() == null) {
diff --git a/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java b/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java
index 7a30086..006b99b 100644
--- a/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java
+++ b/platform/lang-impl/src/com/intellij/ide/hierarchy/actions/BrowseHierarchyActionBase.java
@@ -115,7 +115,7 @@
 
   @Nullable
   private HierarchyProvider getProvider(final AnActionEvent e) {
-    return findBestHierarchyProvider(myExtension, e.getData(CommonDataKeys.PSI_FILE), e.getDataContext());
+    return findBestHierarchyProvider(myExtension, e.getData(CommonDataKeys.PSI_ELEMENT), e.getDataContext());
   }
 
   @Nullable
diff --git a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java
index 5783b67..d565c69 100644
--- a/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java
+++ b/platform/lang-impl/src/com/intellij/ide/navigationToolbar/NavBarPopup.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,7 +18,6 @@
 import com.intellij.ide.navigationToolbar.ui.NavBarUIManager;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.actionSystem.DataProvider;
-import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.ui.Queryable;
 import com.intellij.openapi.util.Disposer;
@@ -113,10 +112,18 @@
     final RelativePoint point = new RelativePoint(item, new Point(0, item.getHeight()));
     final Point p = point.getPoint(myPanel);
     if (p.x == 0 && p.y == 0 && checkRepaint) { // need repaint of nav bar panel
-      ApplicationManager.getApplication().invokeLater(new Runnable() {
+      //noinspection SSBasedInspection
+      SwingUtilities.invokeLater(new Runnable() {
         @Override
         public void run() {
-          show(item, false); // end-less loop protection
+          myPanel.getUpdateQueue().rebuildUi();
+          //noinspection SSBasedInspection
+          SwingUtilities.invokeLater(new Runnable() {
+            @Override
+            public void run() {
+              show(item, false); // end-less loop protection
+            }
+          });
         }
       });
     } else {
diff --git a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java
index 82ecacb..49081c71 100644
--- a/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java
+++ b/platform/lang-impl/src/com/intellij/ide/util/gotoByName/GotoFileModel.java
@@ -101,13 +101,16 @@
   @Override
   public boolean loadInitialCheckBoxState() {
     PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(myProject);
-    return propertiesComponent.isTrueValue("GoToFile.includeJavaFiles");
+    return propertiesComponent.isTrueValue("GoToClass.toSaveIncludeLibraries") &&
+           propertiesComponent.isTrueValue("GoToFile.includeJavaFiles");
   }
 
   @Override
   public void saveInitialCheckBoxState(boolean state) {
     PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(myProject);
-    propertiesComponent.setValue("GoToFile.includeJavaFiles", Boolean.toString(state));
+    if (propertiesComponent.isTrueValue("GoToClass.toSaveIncludeLibraries")) {
+      propertiesComponent.setValue("GoToFile.includeJavaFiles", Boolean.toString(state));
+    }
   }
 
   @Override
diff --git a/platform/lang-impl/src/com/intellij/injected/editor/EditorWindow.java b/platform/lang-impl/src/com/intellij/injected/editor/EditorWindow.java
index 9a32f8b..897d87f 100644
--- a/platform/lang-impl/src/com/intellij/injected/editor/EditorWindow.java
+++ b/platform/lang-impl/src/com/intellij/injected/editor/EditorWindow.java
@@ -36,6 +36,7 @@
 import com.intellij.openapi.editor.highlighter.EditorHighlighter;
 import com.intellij.openapi.editor.highlighter.LightHighlighterClient;
 import com.intellij.openapi.editor.impl.EditorImpl;
+import com.intellij.openapi.editor.impl.SoftWrapModelImpl;
 import com.intellij.openapi.editor.impl.TextDrawingCallback;
 import com.intellij.openapi.editor.impl.softwrap.SoftWrapAppliancePlaces;
 import com.intellij.openapi.editor.markup.MarkupModel;
@@ -73,6 +74,7 @@
   private boolean myDisposed;
   private final MarkupModelWindow myMarkupModelDelegate;
   private final FoldingModelWindow myFoldingModelWindow;
+  private final SoftWrapModelImpl mySoftWrapModel;
 
   public static Editor create(@NotNull final DocumentWindowImpl documentRange, @NotNull final EditorImpl editor, @NotNull final PsiFile injectedFile) {
     assert documentRange.isValid();
@@ -106,6 +108,8 @@
     mySelectionModelDelegate = new SelectionModelWindow(myDelegate, myDocumentWindow,this);
     myMarkupModelDelegate = new MarkupModelWindow((MarkupModelEx)myDelegate.getMarkupModel(), myDocumentWindow);
     myFoldingModelWindow = new FoldingModelWindow(delegate.getFoldingModel(), documentWindow, this);
+    mySoftWrapModel = new SoftWrapModelImpl(this);
+    Disposer.register(myDocumentWindow, mySoftWrapModel);
   }
 
   public static void disposeInvalidEditors() {
@@ -266,7 +270,7 @@
   @Override
   @NotNull
   public SoftWrapModelEx getSoftWrapModel() {
-    return myDelegate.getSoftWrapModel();
+    return mySoftWrapModel;
   }
 
   @Override
diff --git a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java
index 8c46ec5..5af6db0 100644
--- a/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java
+++ b/platform/lang-impl/src/com/intellij/lang/javascript/boilerplate/AbstractGithubTagDownloadedProjectGenerator.java
@@ -64,7 +64,7 @@
       unpackToDir(project, new File(baseDir.getPath()), tag);
     }
     catch (GeneratorException e) {
-      showErrorMessage(e.getMessage());
+      showErrorMessage(project, e.getMessage());
     }
     ApplicationManager.getApplication().runWriteAction(new Runnable() {
       @Override
@@ -149,10 +149,9 @@
     return GithubDownloadUtil.findCacheFile(getGithubUserName(), getGithubRepositoryName(), fileName);
   }
 
-  private void showErrorMessage(@NotNull String message) {
+  private void showErrorMessage(@NotNull Project project, @NotNull String message) {
     String fullMessage = "Error creating " + getDisplayName() + " project. " + message;
     String title = "Create " + getDisplayName() + " Project";
-    Project project = null;
     Messages.showErrorDialog(project, fullMessage, title);
   }
 
diff --git a/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java b/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java
index d18bf4c..d429b48 100644
--- a/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java
+++ b/platform/lang-impl/src/com/intellij/lang/parser/GeneratedParserUtilBase.java
@@ -22,8 +22,8 @@
 import com.intellij.psi.tree.TokenSet;
 import com.intellij.util.Function;
 import com.intellij.util.PairProcessor;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.LimitedPool;
-import gnu.trove.THashSet;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -105,7 +105,7 @@
     ErrorState state = ErrorState.get(builder_);
 
     Frame frame = state.frameStack.peekLast();
-    return frame == null || frame.errorReportedAt <= builder_.getCurrentOffset();
+    return frame == null || frame.errorReportedAt <= builder_.rawTokenIndex();
   }
 
   public static TokenSet create_token_set_(IElementType... tokenTypes_) {
@@ -115,7 +115,7 @@
   public static boolean consumeTokens(PsiBuilder builder_, int pin_, IElementType... tokens_) {
     ErrorState state = ErrorState.get(builder_);
     if (state.completionState != null && state.predicateSign) {
-      addCompletionVariant(builder_, state, state.completionState, tokens_, builder_.getCurrentOffset());
+      addCompletionVariant(builder_, state.completionState, tokens_);
     }
     // suppress single token completion
     CompletionState completionState = state.completionState;
@@ -195,7 +195,7 @@
       result |= tokenType == token;
     }
     if (useFrameName) {
-      addVariantInner(state, builder_.getCurrentOffset(), frameName);
+      addVariantInner(state, builder_.rawTokenIndex(), frameName);
     }
     return result;
   }
@@ -219,7 +219,7 @@
     ErrorState state = ErrorState.get(builder_);
     if (!state.suppressErrors && state.predicateCount < 2 && state.predicateSign) {
       state.clearVariants(true, state.variants.size() - variantCount);
-      addVariantInner(state, builder_.getCurrentOffset(), frameName);
+      addVariantInner(state, builder_.rawTokenIndex(), frameName);
     }
     return true;
   }
@@ -229,21 +229,21 @@
   }
 
   private static void addVariant(PsiBuilder builder_, ErrorState state, Object o) {
-    int offset = builder_.getCurrentOffset();
-    addVariantInner(state, offset, o);
+    builder_.eof(); // skip whitespaces
+    addVariantInner(state, builder_.rawTokenIndex(), o);
 
     CompletionState completionState = state.completionState;
     if (completionState != null && state.predicateSign) {
-      addCompletionVariant(builder_, state, completionState, o, offset);
+      addCompletionVariant(builder_, completionState, o);
     }
   }
 
-  private static void addVariantInner(ErrorState state, int offset, Object o) {
-    Variant variant = state.VARIANTS.alloc().init(offset, o);
+  private static void addVariantInner(ErrorState state, int pos, Object o) {
+    Variant variant = state.VARIANTS.alloc().init(pos, o);
     if (state.predicateSign) {
       state.variants.add(variant);
-      if (state.lastExpectedVariantOffset < variant.offset) {
-        state.lastExpectedVariantOffset = variant.offset;
+      if (state.lastExpectedVariantPos < variant.position) {
+        state.lastExpectedVariantPos = variant.position;
       }
     }
     else {
@@ -282,11 +282,10 @@
     return false;
   }
 
-  private static void addCompletionVariant(PsiBuilder builder_,
-                                           ErrorState state,
-                                           CompletionState completionState,
-                                           Object o,
-                                           int offset) {
+  private static void addCompletionVariant(@NotNull PsiBuilder builder_, @NotNull CompletionState completionState, Object o) {
+    int offset = builder_.getCurrentOffset();
+    if (!builder_.eof() && offset == builder_.rawTokenTypeStart(1)) return; // suppress for zero-length tokens
+
     boolean add = false;
     int diff = completionState.offset - offset;
     String text = completionState.convertItem(o);
@@ -379,7 +378,7 @@
 
   private static void enter_section_impl_(PsiBuilder builder_, int level, int modifiers, @Nullable String frameName) {
     ErrorState state = ErrorState.get(builder_);
-    Frame frame = state.FRAMES.alloc().init(builder_.getCurrentOffset(), level, modifiers, frameName, state);
+    Frame frame = state.FRAMES.alloc().init(builder_, state, level, modifiers, frameName);
     if (((frame.modifiers & _LEFT_) | (frame.modifiers & _LEFT_INNER_)) != 0) {
       PsiBuilder.Marker left = (PsiBuilder.Marker)builder_.getLatestDoneMarker();
       if (invalid_left_marker_guard_(builder_, left, frameName)) {
@@ -430,28 +429,28 @@
     }
     exit_section_impl_(state, frame, builder_, marker, elementType, result, pinned);
 
-    int initialOffset = builder_.getCurrentOffset();
+    int initialPos = builder_.rawTokenIndex();
     boolean willFail = !result && !pinned;
-    if (willFail && initialOffset == frame.offset && state.lastExpectedVariantOffset == frame.offset &&
+    if (willFail && initialPos == frame.position && state.lastExpectedVariantPos == frame.position &&
         frame.name != null && state.variants.size() - frame.variantCount > 1) {
       state.clearVariants(true, frame.variantCount);
-      addVariantInner(state, initialOffset, frame.name);
+      addVariantInner(state, initialPos, frame.name);
     }
     if (!state.suppressErrors && eatMore != null) {
       state.suppressErrors = true;
       final boolean eatMoreFlagOnce = !builder_.eof() && eatMore.parse(builder_, frame.level + 1);
-      final int lastErrorPos = getLastVariantOffset(state, initialOffset);
-      boolean eatMoreFlag = eatMoreFlagOnce || !result && frame.offset == initialOffset && lastErrorPos > frame.offset;
+      final int lastErrorPos = getLastVariantPos(state, initialPos);
+      boolean eatMoreFlag = eatMoreFlagOnce || !result && frame.position == initialPos && lastErrorPos > frame.position;
 
-      final LighterASTNode latestDoneMarker =
-        (pinned || result) && (state.altMode || lastErrorPos > initialOffset || level == 0) &&
-        eatMoreFlagOnce ? builder_.getLatestDoneMarker() : null;
+      PsiBuilderImpl.ProductionMarker latestDoneMarker =
+        (pinned || result) && (state.altMode || elementType != null) &&
+        eatMoreFlagOnce ? (PsiBuilderImpl.ProductionMarker)builder_.getLatestDoneMarker() : null;
       PsiBuilder.Marker extensionMarker = null;
       IElementType extensionTokenType = null;
       // whitespace prefix makes the very first frame offset bigger than marker start offset which is always 0
       if (latestDoneMarker instanceof PsiBuilder.Marker &&
-          frame.offset >= latestDoneMarker.getStartOffset() &&
-          frame.offset <= latestDoneMarker.getEndOffset()) {
+          frame.position >= latestDoneMarker.getStartIndex() &&
+          frame.position <= latestDoneMarker.getEndIndex()) {
         extensionMarker = ((PsiBuilder.Marker)latestDoneMarker).precede();
         extensionTokenType = latestDoneMarker.getTokenType();
         ((PsiBuilder.Marker)latestDoneMarker).drop();
@@ -459,7 +458,7 @@
       // advance to the last error pos
       // skip tokens until lastErrorPos. parseAsTree might look better here...
       int parenCount = 0;
-      while ((eatMoreFlag || parenCount > 0) && builder_.getCurrentOffset() < lastErrorPos) {
+      while ((eatMoreFlag || parenCount > 0) && builder_.rawTokenIndex() < lastErrorPos) {
         if (state.braces != null) {
           if (builder_.getTokenType() == state.braces[0].getLeftBraceType()) parenCount ++;
           else if (builder_.getTokenType() == state.braces[0].getRightBraceType()) parenCount --;
@@ -467,7 +466,7 @@
         builder_.advanceLexer();
         eatMoreFlag = eatMore.parse(builder_, frame.level + 1);
       }
-      boolean errorReported = frame.errorReportedAt == initialOffset || !result && frame.errorReportedAt >= frame.offset;
+      boolean errorReported = frame.errorReportedAt == initialPos || !result && frame.errorReportedAt >= frame.position;
       if (errorReported) {
         if (eatMoreFlag) {
           builder_.advanceLexer();
@@ -478,7 +477,7 @@
         errorReported = reportError(builder_, state, frame, true, true);
         parseAsTree(state, builder_, frame.level + 1, DUMMY_BLOCK, true, TOKEN_ADVANCER, eatMore);
       }
-      else if (eatMoreFlagOnce || (!result && frame.offset != builder_.getCurrentOffset())) {
+      else if (eatMoreFlagOnce || (!result && frame.position != builder_.rawTokenIndex())) {
         errorReported = reportError(builder_, state, frame, true, false);
       }
       if (extensionMarker != null) {
@@ -488,12 +487,12 @@
       if (errorReported || result) {
         state.clearVariants(true, 0);
         state.clearVariants(false, 0);
-        state.lastExpectedVariantOffset = -1;
+        state.lastExpectedVariantPos = -1;
       }
     }
     else if (!result && pinned && frame.errorReportedAt < 0) {
-      // do not report if there're errors after current offset
-      if (getLastVariantOffset(state, initialOffset) == initialOffset) {
+      // do not report if there are errors beyond current position
+      if (getLastVariantPos(state, initialPos) == initialPos) {
         // do not force, inner recoverRoot might have skipped some tokens
         reportError(builder_, state, frame, false, false);
       }
@@ -513,8 +512,9 @@
                                          boolean pinned) {
     if (elementType != null && marker != null) {
       if ((frame.modifiers & _COLLAPSE_) != 0) {
-        LighterASTNode last = result || pinned? builder_.getLatestDoneMarker() : null;
-        if (last != null && last.getStartOffset() == frame.offset && state.typeExtends(last.getTokenType(), elementType)) {
+        PsiBuilderImpl.ProductionMarker last = result || pinned? (PsiBuilderImpl.ProductionMarker)builder_.getLatestDoneMarker() : null;
+        if (last != null && last.getStartIndex() == frame.position &&
+            state.typeExtends(last.getTokenType(), elementType)) {
           IElementType resultType = last.getTokenType();
           ((PsiBuilder.Marker)last).drop();
           marker.done(resultType);
@@ -532,6 +532,7 @@
           frame.leftMarker.precede().done(elementType);
         }
         else {
+          if (frame.level == 0) builder_.eof(); // skip whitespaces
           marker.done(elementType);
         }
       }
@@ -563,8 +564,8 @@
     }
     else {
       if (frame != null) {
-        int offset = ((LighterASTNode)marker).getStartOffset();
-        if (frame.errorReportedAt > offset) {
+        int position = ((PsiBuilderImpl.ProductionMarker)marker).getStartIndex();
+        if (frame.errorReportedAt > position) {
           frame.errorReportedAt = frame.errorReportedAtPrev;
         }
       }
@@ -583,14 +584,14 @@
       LOG.error("unbalanced enter/exit section call: got null");
       return;
     }
-    int offset = builder_.getCurrentOffset();
-    if (frame.errorReportedAt < offset && getLastVariantOffset(state, builder_.getCurrentOffset()) <= offset) {
+    int position = builder_.rawTokenIndex();
+    if (frame.errorReportedAt < position && getLastVariantPos(state, position) <= position) {
       reportError(builder_, state, frame, true, advance);
     }
   }
 
-  private static int getLastVariantOffset(ErrorState state, int defValue) {
-    return state.lastExpectedVariantOffset < 0? defValue : state.lastExpectedVariantOffset;
+  private static int getLastVariantPos(ErrorState state, int defValue) {
+    return state.lastExpectedVariantPos < 0? defValue : state.lastExpectedVariantPos;
   }
 
   private static boolean reportError(PsiBuilder builder_,
@@ -613,7 +614,8 @@
       else {
         builder_.error(message);
       }
-      frame.errorReportedAt = builder_.getCurrentOffset();
+      builder_.eof(); // skip whitespaces
+      frame.errorReportedAt = builder_.rawTokenIndex();
       return true;
     }
     return false;
@@ -624,10 +626,10 @@
 
   public static class CompletionState implements Function<Object, String> {
     public final int offset;
-    public final Collection<String> items = new THashSet<String>();
+    public final Collection<String> items = ContainerUtil.newTroveSet();
 
-    public CompletionState(int offset) {
-      this.offset = offset;
+    public CompletionState(int offset_) {
+      offset = offset_;
     }
 
     @Nullable
@@ -645,10 +647,10 @@
     public final ErrorState state;
     public final PsiParser parser;
 
-    public Builder(PsiBuilder builder, ErrorState state, PsiParser parser) {
-      super(builder);
-      this.state = state;
-      this.parser = parser;
+    public Builder(PsiBuilder builder_, ErrorState state_, PsiParser parser_) {
+      super(builder_);
+      state = state_;
+      parser = parser_;
     }
 
     public Lexer getLexer() {
@@ -680,9 +682,9 @@
     public BracePair[] braces;
     public boolean altMode;
 
-    private int lastExpectedVariantOffset = -1;
-    public MyList<Variant> variants = new MyList<Variant>(INITIAL_VARIANTS_SIZE);
-    public MyList<Variant> unexpected = new MyList<Variant>(INITIAL_VARIANTS_SIZE / 10);
+    int lastExpectedVariantPos = -1;
+    MyList<Variant> variants = new MyList<Variant>(INITIAL_VARIANTS_SIZE);
+    MyList<Variant> unexpected = new MyList<Variant>(INITIAL_VARIANTS_SIZE / 10);
 
     final LimitedPool<Variant> VARIANTS = new LimitedPool<Variant>(VARIANTS_POOL_SIZE, new LimitedPool.ObjectFactory<Variant>() {
       @Override
@@ -709,7 +711,7 @@
       return ((Builder)builder).state;
     }
 
-    private static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
+    public static void initState(ErrorState state, PsiBuilder builder, IElementType root, TokenSet[] extendsSets) {
       state.extendsSets = extendsSets;
       PsiFile file = builder.getUserDataUnprotected(FileContextUtil.CONTAINING_FILE_KEY);
       state.completionState = file == null? null: file.getUserData(COMPLETION_STATE_KEY);
@@ -721,23 +723,23 @@
     }
 
     public String getExpectedText(PsiBuilder builder_) {
-      int offset = builder_.getCurrentOffset();
+      int position = builder_.rawTokenIndex();
       StringBuilder sb = new StringBuilder();
-      if (addExpected(sb, offset, true)) {
+      if (addExpected(sb, position, true)) {
         sb.append(" expected, ");
       }
-      else if (addExpected(sb, offset, false)) sb.append(" unexpected, ");
+      else if (addExpected(sb, position, false)) sb.append(" unexpected, ");
       return sb.toString();
     }
 
-    private boolean addExpected(StringBuilder sb, int offset, boolean expected) {
+    private boolean addExpected(StringBuilder sb, int position, boolean expected) {
       MyList<Variant> list = expected ? variants : unexpected;
       String[] strings = new String[list.size()];
       long[] hashes = new long[strings.length];
       Arrays.fill(strings, "");
       int count = 0;
       loop: for (Variant variant : list) {
-        if (offset == variant.offset) {
+        if (position == variant.position) {
           String text = variant.object.toString();
           long hash = StringHash.calc(text);
           for (int i=0; i<count; i++) {
@@ -774,6 +776,7 @@
 
     public void clearVariants(boolean expected, int start) {
       MyList<Variant> list = expected? variants : unexpected;
+      if (start < 0 || start >= list.size()) return;
       for (int i = start, len = list.size(); i < len; i ++) {
         VARIANTS.recycle(list.get(i));
       }
@@ -793,6 +796,7 @@
 
   public static class Frame {
     public int offset;
+    public int position;
     public int level;
     public int modifiers;
     public String name;
@@ -804,13 +808,14 @@
     public Frame() {
     }
 
-    public Frame init(int offset, int level, int modifiers, String name, ErrorState state) {
-      this.offset = offset;
-      this.level = level;
-      this.modifiers = modifiers;
-      this.name = name;
-      this.variantCount = state.variants.size();
-      this.errorReportedAt = -1;
+    public Frame init(PsiBuilder builder_, ErrorState state, int level_, int modifiers_, String name_) {
+      offset = builder_.getCurrentOffset();
+      position = builder_.rawTokenIndex();
+      level = level_;
+      modifiers = modifiers_;
+      name = name_;
+      variantCount = state.variants.size();
+      errorReportedAt = -1;
 
       Frame prev = state.frameStack.peekLast();
       errorReportedAtPrev = prev == null? -1 : prev.errorReportedAt;
@@ -831,19 +836,19 @@
   }
 
 
-  public static class Variant {
-    int offset;
+  private static class Variant {
+    int position;
     Object object;
 
-    public Variant init(int offset, Object text) {
-      this.offset = offset;
-      this.object = text;
+    public Variant init(int pos, Object o) {
+      position = pos;
+      object = o;
       return this;
     }
 
     @Override
     public String toString() {
-      return "<" + offset + ", " + object + ">";
+      return "<" + position + ", " + object + ">";
     }
 
     @Override
@@ -853,7 +858,7 @@
 
       Variant variant = (Variant)o;
 
-      if (offset != variant.offset) return false;
+      if (position != variant.position) return false;
       if (!this.object.equals(variant.object)) return false;
 
       return true;
@@ -861,7 +866,7 @@
 
     @Override
     public int hashCode() {
-      int result = offset;
+      int result = position;
       result = 31 * result + object.hashCode();
       return result;
     }
@@ -997,7 +1002,7 @@
     }
   }
 
-  protected static class MyList<E> extends ArrayList<E> {
+  private static class MyList<E> extends ArrayList<E> {
     public MyList(int initialCapacity) {
       super(initialCapacity);
     }
@@ -1007,12 +1012,12 @@
     }
 
     @Override
-    public void ensureCapacity(int minCapacity) {
+    public boolean add(E e) {
       int size = size();
       if (size >= MAX_VARIANTS_SIZE) {
         removeRange(MAX_VARIANTS_SIZE / 4, size - MAX_VARIANTS_SIZE / 4);
       }
-      super.ensureCapacity(minCapacity);
+      return super.add(e);
     }
   }
 }
diff --git a/platform/lang-impl/src/com/intellij/navigation/DirectoryPresentationProvider.java b/platform/lang-impl/src/com/intellij/navigation/DirectoryPresentationProvider.java
index bb67816..ca31c08 100644
--- a/platform/lang-impl/src/com/intellij/navigation/DirectoryPresentationProvider.java
+++ b/platform/lang-impl/src/com/intellij/navigation/DirectoryPresentationProvider.java
@@ -22,7 +22,7 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ProjectRootManager;
 import com.intellij.openapi.roots.SourceFolder;
-import com.intellij.openapi.roots.ui.configuration.ModuleSourceRootEditHandler;
+import com.intellij.openapi.roots.ui.configuration.SourceRootPresentation;
 import com.intellij.openapi.util.IconLoader;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiDirectory;
@@ -52,7 +52,7 @@
     if (ProjectRootsUtil.isSourceRoot(directory)) {
       SourceFolder sourceRoot = ProjectRootsUtil.getModuleSourceRoot(vFile, project);
       if (sourceRoot != null) {
-        Icon icon = ModuleSourceRootEditHandler.getEditHandler(sourceRoot.getRootType()).getRootIcon();
+        Icon icon = SourceRootPresentation.getSourceRootIcon(sourceRoot);
         return new PresentationData(directory.getName(), locationString, icon, null);
       }
     }
diff --git a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java
index 5178202..92901eb 100644
--- a/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java
+++ b/platform/lang-impl/src/com/intellij/openapi/fileEditor/impl/http/JumpFromRemoteFileToLocalAction.java
@@ -31,6 +31,8 @@
 import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.ui.ColoredListCellRenderer;
 import com.intellij.ui.components.JBList;
+import com.intellij.util.Url;
+import com.intellij.util.Urls;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 
@@ -56,10 +58,9 @@
 
   @Override
   public void actionPerformed(AnActionEvent e) {
-    final String url = myFile.getUrl();
-    Collection<VirtualFile> files = findLocalFiles(myProject, url, myFile.getName());
+    Collection<VirtualFile> files = findLocalFiles(myProject, Urls.newFromVirtualFile(myFile), myFile.getName());
     if (files.isEmpty()) {
-      Messages.showErrorDialog(myProject, "Cannot find local file for '" + url + "'", CommonBundle.getErrorTitle());
+      Messages.showErrorDialog(myProject, "Cannot find local file for '" + myFile.getUrl() + "'", CommonBundle.getErrorTitle());
       return;
     }
 
@@ -90,7 +91,7 @@
     }
   }
 
-  private static Collection<VirtualFile> findLocalFiles(Project project, String url, String fileName) {
+  private static Collection<VirtualFile> findLocalFiles(Project project, Url url, String fileName) {
     for (LocalFileFinder finder : LocalFileFinder.EP_NAME.getExtensions()) {
       final VirtualFile file = finder.findLocalFile(url, project);
       if (file != null) {
diff --git a/platform/lang-impl/src/com/intellij/openapi/module/WebModuleBuilder.java b/platform/lang-impl/src/com/intellij/openapi/module/WebModuleBuilder.java
index cee30d3..991ae5f 100644
--- a/platform/lang-impl/src/com/intellij/openapi/module/WebModuleBuilder.java
+++ b/platform/lang-impl/src/com/intellij/openapi/module/WebModuleBuilder.java
@@ -24,14 +24,12 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.ModifiableRootModel;
 import com.intellij.openapi.roots.ModuleRootManager;
-import com.intellij.openapi.roots.ui.configuration.ModulesProvider;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.platform.WebProjectGenerator;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
-import java.util.List;
 
 /**
 * @author Dmitry Avdeev
@@ -72,13 +70,14 @@
     return myTemplate != null ? myTemplate.getIcon() : ICON;
   }
 
+  @Nullable
   @Override
-  public List<Module> commit(Project project, ModifiableModuleModel model, ModulesProvider modulesProvider) {
-    List<Module> modules = super.commit(project, model, modulesProvider);
-    if (modules != null && !modules.isEmpty() && myTemplate != null) {
-      doGenerate(myTemplate, modules.get(0));
+  public Module commitModule(@NotNull Project project, @Nullable ModifiableModuleModel model) {
+    Module module = super.commitModule(project, model);
+    if (module != null && myTemplate != null) {
+      doGenerate(myTemplate, module);
     }
-    return modules;
+    return module;
   }
 
   private static <T> void doGenerate(@NotNull WebProjectTemplate<T> template, @NotNull Module module) {
diff --git a/platform/lang-impl/src/com/intellij/openapi/options/colors/pages/GeneralColorsPage.java b/platform/lang-impl/src/com/intellij/openapi/options/colors/pages/GeneralColorsPage.java
index 76a4695..5db72dc 100644
--- a/platform/lang-impl/src/com/intellij/openapi/options/colors/pages/GeneralColorsPage.java
+++ b/platform/lang-impl/src/com/intellij/openapi/options/colors/pages/GeneralColorsPage.java
@@ -66,8 +66,7 @@
     "  <wrong_ref>Unknown symbol</wrong_ref>\n" +
     "  <server_error>Problem from server</server_error>\n" +
     "  <server_duplicate>Duplicate from server</server_duplicate>\n" +
-    getCustomSeveritiesDemoText() +
-    "\n";
+    getCustomSeveritiesDemoText();
 
   private static final AttributesDescriptor[] ATT_DESCRIPTORS = {
     new AttributesDescriptor(OptionsBundle.message("options.general.attribute.descriptor.default.text"), HighlighterColors.TEXT),
@@ -212,7 +211,7 @@
          final String tag = getHighlightDescTagName(highlightInfoType);
          buff.append("  <").append(tag).append(">");
          buff.append(tag.toLowerCase());
-         buff.append("</").append(tag).append(">");
+         buff.append("</").append(tag).append(">").append("\n");
        }
      }
 
diff --git a/platform/lang-impl/src/com/intellij/openapi/paths/GlobalPathReferenceProvider.java b/platform/lang-impl/src/com/intellij/openapi/paths/GlobalPathReferenceProvider.java
index 4ae902f..bc4b97d 100644
--- a/platform/lang-impl/src/com/intellij/openapi/paths/GlobalPathReferenceProvider.java
+++ b/platform/lang-impl/src/com/intellij/openapi/paths/GlobalPathReferenceProvider.java
@@ -31,10 +31,10 @@
 public class GlobalPathReferenceProvider implements PathReferenceProvider {
 
   @NonNls private static final String[] PREFIXES = {
-    "mailto:", "tel:", "sms:", "skype:", "data:"
+    "mailto:", "tel:", "sms:", "skype:", "data:", "xmpp:"
   };
 
-  private static boolean startsWithAllowedPrefix(String s) {
+  public static boolean startsWithAllowedPrefix(String s) {
     for (String prefix : PREFIXES) {
       if (s.startsWith(prefix)) {
         return true;
diff --git a/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkTableImpl.java b/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkTableImpl.java
index 3a5c3ec..c56f397 100644
--- a/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkTableImpl.java
+++ b/platform/lang-impl/src/com/intellij/openapi/projectRoots/impl/ProjectJdkTableImpl.java
@@ -109,7 +109,9 @@
   @Override
   @Nullable
   public Sdk findJdk(String name) {
-    for (Sdk jdk : mySdks) {
+    //noinspection ForLoopReplaceableByForEach
+    for (int i = 0, len = mySdks.size(); i < len; ++i) { // avoid foreach,  it instantiates ArrayList$Itr, this traversal happens very often
+      final Sdk jdk = mySdks.get(i);
       if (Comparing.strEqual(name, jdk.getName())) {
         return jdk;
       }
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeCellRenderer.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeCellRenderer.java
index 290243b..bdbc44b 100644
--- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeCellRenderer.java
+++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ContentEntryTreeCellRenderer.java
@@ -89,7 +89,7 @@
     final SourceFolder[] sourceFolders = entry.getSourceFolders();
     for (SourceFolder sourceFolder : sourceFolders) {
       if (file.equals(sourceFolder.getFile())) {
-        return IconSet.getSourceRootIcon(sourceFolder.getRootType(), myEditHandlers);
+        return SourceRootPresentation.getSourceRootIcon(sourceFolder);
       }
     }
 
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/IconSet.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/IconSet.java
deleted file mode 100644
index 936e56e..0000000
--- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/IconSet.java
+++ /dev/null
@@ -1,41 +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.openapi.roots.ui.configuration;
-
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.jps.model.module.JpsModuleSourceRootType;
-
-import javax.swing.*;
-import java.util.List;
-
-/**
- * @author Eugene Zhuravlev
- *         Date: Oct 20
- * @author 2003
- */
-public class IconSet {
-
-  @Nullable
-  public static Icon getSourceRootIcon(JpsModuleSourceRootType<?> type, List<ModuleSourceRootEditHandler<?>> handlers) {
-    for (ModuleSourceRootEditHandler<?> handler : handlers) {
-      if (handler.getRootType().equals(type)) {
-        return handler.getRootIcon();
-      }
-    }
-    return null;
-  }
-}
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaModuleSourceRootEditHandler.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaModuleSourceRootEditHandler.java
index a308d678..b951013 100644
--- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaModuleSourceRootEditHandler.java
+++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaModuleSourceRootEditHandler.java
@@ -57,6 +57,12 @@
     return AllIcons.Modules.SourceRoot;
   }
 
+  @NotNull
+  @Override
+  protected Icon getGeneratedRootIcon() {
+    return AllIcons.Modules.GeneratedSourceRoot;
+  }
+
   @Nullable
   @Override
   public Icon getFolderUnderRootIcon() {
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java
index 7b3f587..c3042f7 100644
--- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java
+++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaSourceRootEditHandlerBase.java
@@ -39,6 +39,15 @@
     super(rootType);
   }
 
+  @NotNull
+  @Override
+  public Icon getRootIcon(@NotNull JavaSourceRootProperties properties) {
+    return properties.isForGeneratedSources() ? getGeneratedRootIcon() : getRootIcon();
+  }
+
+  @NotNull
+  protected abstract Icon getGeneratedRootIcon();
+
   @Nullable
   @Override
   public String getPropertiesString(@NotNull JavaSourceRootProperties properties) {
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaTestSourceRootEditHandler.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaTestSourceRootEditHandler.java
index 2cdcbc4..569a63b 100644
--- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaTestSourceRootEditHandler.java
+++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/JavaTestSourceRootEditHandler.java
@@ -38,7 +38,6 @@
     super(JavaSourceRootType.TEST_SOURCE);
   }
 
-
   @NotNull
   @Override
   public String getRootTypeName() {
@@ -57,6 +56,12 @@
     return AllIcons.Modules.TestRoot;
   }
 
+  @NotNull
+  @Override
+  protected Icon getGeneratedRootIcon() {
+    return AllIcons.Modules.GeneratedTestRoot;
+  }
+
   @Nullable
   @Override
   public Icon getFolderUnderRootIcon() {
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ModuleSourceRootEditHandler.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ModuleSourceRootEditHandler.java
index cab301a..b65dc54 100644
--- a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ModuleSourceRootEditHandler.java
+++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/ModuleSourceRootEditHandler.java
@@ -57,6 +57,11 @@
   @NotNull
   public abstract Icon getRootIcon();
 
+  @NotNull
+  public Icon getRootIcon(@NotNull P properties) {
+    return getRootIcon();
+  }
+
   @Nullable
   public abstract Icon getFolderUnderRootIcon();
 
diff --git a/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SourceRootPresentation.java b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SourceRootPresentation.java
new file mode 100644
index 0000000..5435ee3
--- /dev/null
+++ b/platform/lang-impl/src/com/intellij/openapi/roots/ui/configuration/SourceRootPresentation.java
@@ -0,0 +1,42 @@
+/*
+ * 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.openapi.roots.ui.configuration;
+
+import com.intellij.openapi.roots.SourceFolder;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.jps.model.JpsElement;
+import org.jetbrains.jps.model.module.JpsTypedModuleSourceRoot;
+
+import javax.swing.*;
+
+/**
+ * @author Eugene Zhuravlev
+ *         Date: Oct 20
+ * @author 2003
+ */
+public class SourceRootPresentation {
+  @NotNull
+  public static Icon getSourceRootIcon(@NotNull SourceFolder sourceFolder) {
+    return getSourceRootIcon(sourceFolder.getJpsElement().asTyped());
+  }
+
+  @NotNull
+  private static <P extends JpsElement> Icon getSourceRootIcon(@NotNull JpsTypedModuleSourceRoot<P> root) {
+    ModuleSourceRootEditHandler<P> handler = ModuleSourceRootEditHandler.getEditHandler(root.getRootType());
+    return handler.getRootIcon(root.getProperties());
+  }
+}
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 28f86cb..73c7b4a 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
@@ -12,11 +12,13 @@
 import org.jetbrains.annotations.Nullable;
 
 import java.io.File;
-import java.io.FileInputStream;
 import java.io.FileOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
+import java.util.Enumeration;
 import java.util.concurrent.Callable;
 import java.util.zip.ZipEntry;
+import java.util.zip.ZipFile;
 import java.util.zip.ZipInputStream;
 
 /**
@@ -45,13 +47,7 @@
         @Override
         public Boolean call() throws IOException {
           ProgressIndicator progress = ProgressManager.getInstance().getProgressIndicator();
-          ZipInputStream stream = new ZipInputStream(new FileInputStream(zipArchive));
-          try {
-            unzip(progress, extractToDir, stream, null, null, unwrapSingleTopLevelFolder);
-          }
-          finally {
-            stream.close();
-          }
+          unzip(progress, extractToDir, zipArchive, null, null, unwrapSingleTopLevelFolder);
           return true;
         }
       },
@@ -73,25 +69,59 @@
     }
   }
 
+  private static File getUnzipToDir(@Nullable ProgressIndicator progress,
+                                    @NotNull File targetDir,
+                                    boolean unwrapSingleTopLevelFolder) throws IOException {
+    if (progress != null) {
+      progress.setText("Extracting...");
+    }
+    if (unwrapSingleTopLevelFolder) {
+      return FileUtil.createTempDirectory("unzip-dir-", null);
+    }
+    return targetDir;
+  }
+
+  // This method will throw IOException, if a zipArchive file isn't a valid zip archive.
+  public static void unzip(@Nullable ProgressIndicator progress,
+                           @NotNull File targetDir,
+                           @NotNull File zipArchive,
+                           @Nullable NullableFunction<String, String> pathConvertor,
+                           @Nullable ContentProcessor contentProcessor,
+                           boolean unwrapSingleTopLevelFolder) throws IOException {
+    File unzipToDir = getUnzipToDir(progress, targetDir, unwrapSingleTopLevelFolder);
+    ZipFile zipFile = new ZipFile(zipArchive, ZipFile.OPEN_READ);
+    try {
+      Enumeration<? extends ZipEntry> entries = zipFile.entries();
+      while (entries.hasMoreElements()) {
+        ZipEntry entry = entries.nextElement();
+        InputStream entryContentStream = zipFile.getInputStream(entry);
+        unzipEntryToDir(progress, entry, entryContentStream, unzipToDir, pathConvertor, contentProcessor);
+        entryContentStream.close();
+      }
+    }
+    finally {
+      zipFile.close();
+    }
+    doUnwrapSingleTopLevelFolder(unwrapSingleTopLevelFolder, unzipToDir, targetDir);
+  }
+
   public static void unzip(@Nullable ProgressIndicator progress,
                            @NotNull File targetDir,
                            @NotNull ZipInputStream stream,
                            @Nullable NullableFunction<String, String> pathConvertor,
                            @Nullable ContentProcessor contentProcessor,
                            boolean unwrapSingleTopLevelFolder) throws IOException {
-    if (progress != null) {
-      progress.setText("Extracting...");
-    }
-    File unzipToDir = targetDir;
-    if (unwrapSingleTopLevelFolder) {
-      unzipToDir = FileUtil.createTempDirectory("unzip-dir-", null);
-    }
-
+    File unzipToDir = getUnzipToDir(progress, targetDir, unwrapSingleTopLevelFolder);
     ZipEntry entry;
     while ((entry = stream.getNextEntry()) != null) {
-      unzipEntryToDir(progress, entry, unzipToDir, stream, pathConvertor, contentProcessor);
+      unzipEntryToDir(progress, entry, stream, unzipToDir,  pathConvertor, contentProcessor);
     }
+    doUnwrapSingleTopLevelFolder(unwrapSingleTopLevelFolder, unzipToDir, targetDir);
+  }
 
+  private static void doUnwrapSingleTopLevelFolder(boolean unwrapSingleTopLevelFolder,
+                                                   @NotNull File unzipToDir,
+                                                   @NotNull File targetDir) throws IOException {
     if (unwrapSingleTopLevelFolder) {
       File[] topLevelFiles = unzipToDir.listFiles();
       File dirToMove;
@@ -110,8 +140,8 @@
 
   private static void unzipEntryToDir(@Nullable ProgressIndicator progress,
                                       @NotNull final ZipEntry zipEntry,
+                                      @NotNull final InputStream entryContentStream,
                                       @NotNull final File extractToDir,
-                                      ZipInputStream stream,
                                       @Nullable NullableFunction<String, String> pathConvertor,
                                       @Nullable ContentProcessor contentProcessor) throws IOException {
     String relativeExtractPath = createRelativeExtractPath(zipEntry);
@@ -136,14 +166,14 @@
     if (contentProcessor == null) {
       FileOutputStream fileOutputStream = new FileOutputStream(child);
       try {
-        FileUtil.copy(stream, fileOutputStream);
+        FileUtil.copy(entryContentStream, fileOutputStream);
       }
       finally {
         fileOutputStream.close();
       }
     }
     else {
-      byte[] content = contentProcessor.processContent(FileUtil.loadBytes(stream), child);
+      byte[] content = contentProcessor.processContent(FileUtil.loadBytes(entryContentStream), child);
       if (content != null) {
         FileOutputStream fileOutputStream = new FileOutputStream(child);
         try {
diff --git a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java
index d792e8d..3bf3534 100644
--- a/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java
+++ b/platform/lang-impl/src/com/intellij/psi/codeStyle/arrangement/engine/ArrangementEngine.java
@@ -351,7 +351,17 @@
     for (int i = arranged.size() - 1; i >= 0; i--) {
       ArrangementEntryWrapper<E> arrangedWrapper = map.get(arranged.get(i));
       ArrangementEntryWrapper<E> initialWrapper = wrappers.get(i);
-      context.changer.replace(arrangedWrapper, initialWrapper, i > 0 ? map.get(arranged.get(i - 1)) : null, context);
+
+      ArrangementEntryWrapper<E> previous = i > 0 ? map.get(arranged.get(i - 1)) : null;
+      ArrangementEntryWrapper<E> previousInitial = i > 0 ? wrappers.get(i - 1) : null;
+
+      if (arrangedWrapper.equals(initialWrapper)) {
+        if (previous != null && previous.equals(previousInitial) || previous == null && previousInitial == null) {
+          continue;
+        }
+      }
+
+      context.changer.replace(arrangedWrapper, initialWrapper, previous, context);
     }
   }
 
diff --git a/platform/lang-impl/src/com/intellij/psi/impl/file/DirectoryIconProvider.java b/platform/lang-impl/src/com/intellij/psi/impl/file/DirectoryIconProvider.java
index a0e22f24..d12bc93 100644
--- a/platform/lang-impl/src/com/intellij/psi/impl/file/DirectoryIconProvider.java
+++ b/platform/lang-impl/src/com/intellij/psi/impl/file/DirectoryIconProvider.java
@@ -24,7 +24,7 @@
 import com.intellij.ide.projectView.impl.ProjectRootsUtil;
 import com.intellij.openapi.project.DumbAware;
 import com.intellij.openapi.roots.SourceFolder;
-import com.intellij.openapi.roots.ui.configuration.ModuleSourceRootEditHandler;
+import com.intellij.openapi.roots.ui.configuration.SourceRootPresentation;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiDirectory;
 import com.intellij.psi.PsiElement;
@@ -41,7 +41,7 @@
       final VirtualFile vFile = psiDirectory.getVirtualFile();
       SourceFolder sourceFolder = ProjectRootsUtil.getModuleSourceRoot(vFile, psiDirectory.getProject());
       if (sourceFolder != null) {
-        return ModuleSourceRootEditHandler.getEditHandler(sourceFolder.getRootType()).getRootIcon();
+        return SourceRootPresentation.getSourceRootIcon(sourceFolder);
       }
       else {
         return PlatformIcons.DIRECTORY_CLOSED_ICON;
diff --git a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java
index 92eaec7..a38266e 100644
--- a/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java
+++ b/platform/lang-impl/src/com/intellij/psi/impl/source/codeStyle/CodeStyleManagerImpl.java
@@ -68,11 +68,14 @@
     }
   };
 
+  private final FormatterTagHandler myTagHandler;
+
   private final Project myProject;
   @NonNls private static final String DUMMY_IDENTIFIER = "xxx";
 
   public CodeStyleManagerImpl(Project project) {
     myProject = project;
+    myTagHandler = new FormatterTagHandler(getSettings());
   }
 
   @Override
@@ -106,16 +109,26 @@
 
   private PsiElement postProcessElement(@NotNull final PsiElement formatted) {
     PsiElement result = formatted;
-    for (PostFormatProcessor postFormatProcessor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
-      result = postFormatProcessor.processElement(result, getSettings());
+    if (getSettings().FORMATTER_TAGS_ENABLED && formatted instanceof PsiFile) {
+      postProcessEnabledRanges((PsiFile) formatted, formatted.getTextRange(), getSettings());
+    }
+    else {
+      for (PostFormatProcessor postFormatProcessor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
+        result = postFormatProcessor.processElement(result, getSettings());
+      }
     }
     return result;
   }
 
   private void postProcessText(@NotNull final PsiFile file, @NotNull final TextRange textRange) {
-    TextRange currentRange = textRange;
-    for (final PostFormatProcessor myPostFormatProcessor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
-      currentRange = myPostFormatProcessor.processText(file, currentRange, getSettings());
+    if (!getSettings().FORMATTER_TAGS_ENABLED) {
+      TextRange currentRange = textRange;
+      for (final PostFormatProcessor myPostFormatProcessor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
+        currentRange = myPostFormatProcessor.processText(file, currentRange, getSettings());
+      }
+    }
+    else {
+      postProcessEnabledRanges(file, textRange, getSettings());
     }
   }
 
@@ -173,37 +186,9 @@
       editor = PsiUtilBase.findEditor(file);
     }
 
-    // There is a possible case that cursor is located at the end of the line that contains only white spaces. For example:
-    //     public void foo() {
-    //         <caret>
-    //     }
-    // Formatter removes such white spaces, i.e. keeps only line feed symbol. But we want to preserve caret position then.
-    // So, if 'virtual space in editor' is enabled, we save target visual column. Caret indent is ensured otherwise
-    int visualColumnToRestore = -1;
-    String caretIndentToRestore = null;
-    RangeMarker beforeCaretRangeMarker = null;
-
+    CaretPositionKeeper caretKeeper = null;
     if (editor != null) {
-      Document document = editor.getDocument();
-      int caretOffset = editor.getCaretModel().getOffset();
-      caretOffset = Math.max(Math.min(caretOffset, document.getTextLength() - 1), 0);
-      CharSequence text = document.getCharsSequence();
-      int caretLine = document.getLineNumber(caretOffset);
-      int lineStartOffset = document.getLineStartOffset(caretLine);
-      int lineEndOffset = document.getLineEndOffset(caretLine);
-      boolean fixCaretPosition = true;
-      for (int i = lineStartOffset; i < lineEndOffset; i++) {
-        char c = text.charAt(i);
-        if (c != ' ' && c != '\t' && c != '\n') {
-          fixCaretPosition = false;
-          break;
-        }
-      }
-      if (fixCaretPosition) {
-        visualColumnToRestore = editor.getCaretModel().getVisualPosition().column;
-        caretIndentToRestore = document.getText(TextRange.create(lineStartOffset, caretOffset));
-        beforeCaretRangeMarker = document.createRangeMarker(0, lineStartOffset);
-      }
+      caretKeeper = new CaretPositionKeeper(editor);
     }
 
     final SmartPointerManager smartPointerManager = SmartPointerManager.getInstance(getProject());
@@ -243,34 +228,8 @@
       if (info.endPointer != null) smartPointerManager.removePointer(info.endPointer);
     }
 
-    if (editor == null) {
-      return;
-    }
-
-    boolean virtualSpaceEnabled = editor.getSettings().isVirtualSpace();
-
-    if (virtualSpaceEnabled) {
-      if (visualColumnToRestore < 0) {
-        editor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
-        return;
-      }
-      CaretModel caretModel = editor.getCaretModel();
-      VisualPosition position = caretModel.getVisualPosition();
-      if (visualColumnToRestore != position.column) {
-        caretModel.moveToVisualPosition(new VisualPosition(position.line, visualColumnToRestore));
-      }
-    }
-    else {
-      if (beforeCaretRangeMarker == null || !beforeCaretRangeMarker.isValid() || caretIndentToRestore == null) {
-        return;
-      }
-      int offset = beforeCaretRangeMarker.getEndOffset();
-      beforeCaretRangeMarker.dispose();
-      if (editor.getCaretModel().getVisualPosition().column == visualColumnToRestore) {
-        return;
-      }
-      Document document = editor.getDocument();
-      document.replaceString(document.getLineStartOffset(document.getLineNumber(offset)), offset, caretIndentToRestore);
+    if (caretKeeper != null) {
+      caretKeeper.restoreCaretPosition();
     }
   }
 
@@ -735,4 +694,142 @@
       this.toEnd = toEnd;
     }
   }
+
+  // There is a possible case that cursor is located at the end of the line that contains only white spaces. For example:
+  //     public void foo() {
+  //         <caret>
+  //     }
+  // Formatter removes such white spaces, i.e. keeps only line feed symbol. But we want to preserve caret position then.
+  // So, if 'virtual space in editor' is enabled, we save target visual column. Caret indent is ensured otherwise
+  private static class CaretPositionKeeper {
+    Editor myEditor;
+    Document myDocument;
+    CaretModel myCaretModel;
+    RangeMarker myBeforeCaretRangeMarker;
+    String myCaretIndentToRestore;
+    int myVisualColumnToRestore = -1;
+
+    CaretPositionKeeper(@NotNull Editor editor) {
+      myEditor = editor;
+      myCaretModel = editor.getCaretModel();
+      myDocument = editor.getDocument();
+
+      int caretOffset = getCaretOffset();
+      int lineStartOffset = getLineStartOffsetByTotalOffset(caretOffset);
+      int lineEndOffset = getLineEndOffsetByTotalOffset(caretOffset);
+      boolean shouldFixCaretPosition = rangeHasWhiteSpaceSymbolsOnly(myDocument.getCharsSequence(), lineStartOffset, lineEndOffset);
+
+      if (shouldFixCaretPosition) {
+        initRestoreInfo(caretOffset);
+      }
+    }
+
+    private void initRestoreInfo(int caretOffset) {
+      int lineStartOffset = getLineStartOffsetByTotalOffset(caretOffset);
+
+      myVisualColumnToRestore = myCaretModel.getVisualPosition().column;
+      myCaretIndentToRestore = myDocument.getText(TextRange.create(lineStartOffset, caretOffset));
+      myBeforeCaretRangeMarker = myDocument.createRangeMarker(0, lineStartOffset);
+    }
+
+    public void restoreCaretPosition() {
+      if (isVirtualSpaceEnabled()) {
+        restoreVisualPosition();
+      }
+      else {
+        restorePositionByIndentInsertion();
+      }
+    }
+
+    private void restorePositionByIndentInsertion() {
+      if (myBeforeCaretRangeMarker == null || !myBeforeCaretRangeMarker.isValid() || myCaretIndentToRestore == null) {
+        return;
+      }
+      int newCaretLineStartOffset = myBeforeCaretRangeMarker.getEndOffset();
+      myBeforeCaretRangeMarker.dispose();
+      if (myCaretModel.getVisualPosition().column == myVisualColumnToRestore) {
+        return;
+      }
+      insertWhiteSpaceIndentIfNeeded(newCaretLineStartOffset);
+    }
+
+    private void restoreVisualPosition() {
+      if (myVisualColumnToRestore < 0) {
+        myEditor.getScrollingModel().scrollToCaret(ScrollType.RELATIVE);
+        return;
+      }
+      VisualPosition position = myCaretModel.getVisualPosition();
+      if (myVisualColumnToRestore != position.column) {
+        myCaretModel.moveToVisualPosition(new VisualPosition(position.line, myVisualColumnToRestore));
+      }
+    }
+
+    private void insertWhiteSpaceIndentIfNeeded(int caretLineOffset) {
+      int lineToInsertIndent = myDocument.getLineNumber(caretLineOffset);
+      if (!lineContainsWhiteSpaceSymbolsOnly(lineToInsertIndent))
+        return;
+
+      int lineToInsertStartOffset = myDocument.getLineStartOffset(lineToInsertIndent);
+
+      if (lineToInsertIndent != getCurrentCaretLine()) {
+        myCaretModel.moveToOffset(lineToInsertStartOffset);
+      }
+      myDocument.replaceString(lineToInsertStartOffset, caretLineOffset, myCaretIndentToRestore);
+    }
+
+    private boolean rangeHasWhiteSpaceSymbolsOnly(CharSequence text, int lineStartOffset, int lineEndOffset) {
+      for (int i = lineStartOffset; i < lineEndOffset; i++) {
+        char c = text.charAt(i);
+        if (c != ' ' && c != '\t' && c != '\n') {
+          return false;
+        }
+      }
+      return true;
+    }
+
+    private boolean isVirtualSpaceEnabled() {
+      return myEditor.getSettings().isVirtualSpace();
+    }
+
+    private int getLineStartOffsetByTotalOffset(int offset) {
+      int line = myDocument.getLineNumber(offset);
+      return myDocument.getLineStartOffset(line);
+    }
+
+    private int getLineEndOffsetByTotalOffset(int offset) {
+      int line = myDocument.getLineNumber(offset);
+      return myDocument.getLineEndOffset(line);
+    }
+
+    private int getCaretOffset() {
+      int caretOffset = myCaretModel.getOffset();
+      caretOffset = Math.max(Math.min(caretOffset, myDocument.getTextLength() - 1), 0);
+      return caretOffset;
+    }
+
+    private boolean lineContainsWhiteSpaceSymbolsOnly(int lineNumber) {
+      int startOffset = myDocument.getLineStartOffset(lineNumber);
+      int endOffset = myDocument.getLineEndOffset(lineNumber);
+      return rangeHasWhiteSpaceSymbolsOnly(myDocument.getCharsSequence(), startOffset, endOffset);
+    }
+
+    private int getCurrentCaretLine() {
+      return myDocument.getLineNumber(myCaretModel.getOffset());
+    }
+  }
+
+  private TextRange postProcessEnabledRanges(@NotNull final PsiFile file, @NotNull TextRange range, CodeStyleSettings settings) {
+    TextRange result = TextRange.create(range.getStartOffset(), range.getEndOffset());
+    List<TextRange> enabledRanges = myTagHandler.getEnabledRanges(file.getNode(), result);
+    int delta = 0;
+    for (TextRange enabledRange : enabledRanges) {
+      enabledRange = enabledRange.shiftRight(delta);
+      for (PostFormatProcessor processor : Extensions.getExtensions(PostFormatProcessor.EP_NAME)) {
+        TextRange processedRange = processor.processText(file, enabledRange, settings);
+        delta += processedRange.getLength() - enabledRange.getLength();
+      }
+    }
+    result = result.grown(delta);
+    return result;
+  }
 }
diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
index 8ae3282..1026321 100644
--- a/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
+++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubIndexImpl.java
@@ -315,7 +315,7 @@
 
     final MyIndex<K> index = (MyIndex<K>)myIndices.get(indexKey);
     try {
-      return index.processAllKeys(processor, idFilter);
+      return index.processAllKeys(processor, scope, idFilter);
     }
     catch (StorageException e) {
       forceRebuild(e);
diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java
index 4ba8fd2..ea22194 100644
--- a/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java
+++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubTreeLoaderImpl.java
@@ -174,7 +174,7 @@
 
   @Override
   public long getStubTreeTimestamp(VirtualFile vFile) {
-    return IndexingStamp.getIndexStamp(vFile, IndexInfrastructure.getStubId(StubUpdatingIndex.INDEX_ID, vFile.getFileType()));
+    return IndexingStamp.getIndexStamp(vFile, StubUpdatingIndex.INDEX_ID);
   }
 
   @Override
diff --git a/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java b/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java
index 10b0889..71f3640 100644
--- a/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java
+++ b/platform/lang-impl/src/com/intellij/psi/stubs/StubUpdatingIndex.java
@@ -50,7 +50,7 @@
 
   public static final ID<Integer, SerializedStubTree> INDEX_ID = ID.create("Stubs");
 
-  private static final int VERSION = 26;
+  private static final int VERSION = 27;
 
   private static final DataExternalizer<SerializedStubTree> KEY_EXTERNALIZER = new DataExternalizer<SerializedStubTree>() {
     @Override
@@ -72,8 +72,6 @@
     }
   };
 
-  private final Map<FileType,Integer> myVersionMap = computeVersionMap();
-
   public static boolean canHaveStub(@NotNull VirtualFile file) {
     final FileType fileType = file.getFileType();
     if (fileType instanceof LanguageFileType) {
@@ -88,8 +86,7 @@
         if (((IStubFileElementType)elementType).shouldBuildStubFor(file)) {
           return true;
         }
-        final ID indexId = IndexInfrastructure.getStubId(INDEX_ID, fileType);
-        if (IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId))) {
+        if (IndexingStamp.isFileIndexed(file, INDEX_ID, IndexInfrastructure.getIndexCreationStamp(INDEX_ID))) {
           return true;
         }
       }
@@ -202,15 +199,11 @@
 
   @Override
   public int getVersion() {
-    return VERSION;
+    return getCumulativeVersion();
   }
 
-  public Map<FileType, Integer> getVersionMap() {
-    return myVersionMap;
-  }
-
-  private static Map<FileType, Integer> computeVersionMap() {
-    Map<FileType, Integer> map = new HashMap<FileType, Integer>();
+  private static int getCumulativeVersion() {
+    int version = VERSION;
     for (final FileType fileType : FileTypeManager.getInstance().getRegisteredFileTypes()) {
       if (fileType instanceof LanguageFileType) {
         Language l = ((LanguageFileType)fileType).getLanguage();
@@ -218,16 +211,16 @@
         if (parserDefinition != null) {
           final IFileElementType type = parserDefinition.getFileNodeType();
           if (type instanceof IStubFileElementType) {
-            map.put(fileType, ((IStubFileElementType)type).getStubVersion());
+            version += ((IStubFileElementType)type).getStubVersion();
           }
         }
       }
       final BinaryFileStubBuilder builder = BinaryFileStubBuilders.INSTANCE.forFileType(fileType);
       if (builder != null) {
-        map.put(fileType, builder.getStubVersion());
+        version += builder.getStubVersion();
       }
     }
-    return map;
+    return version;
   }
 
   @NotNull
@@ -434,20 +427,6 @@
         if (stubIndex != null) {
           stubIndex.clearAllIndices();
         }
-
-        Map<FileType, Integer> versionMap = getVersionMap();
-        for (Map.Entry<FileType, Integer> entry : versionMap.entrySet()) {
-          ID stubId = IndexInfrastructure.getStubId(INDEX_ID, entry.getKey());
-          try {
-            IndexInfrastructure.rewriteVersion(IndexInfrastructure.getVersionFile(stubId), entry.getValue());
-          }
-          catch (IOException e) {
-            LOG.error(e);
-          }
-        }
-
-        //File dir= IndexInfrastructure.getStubVersionsDirectory();
-        //if (dir.exists()) dir.delete();
         super.clear();
       }
       finally {
diff --git a/platform/lang-impl/src/com/intellij/refactoring/BaseRefactoringProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/BaseRefactoringProcessor.java
index be2d8c3..3ff1f18 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/BaseRefactoringProcessor.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/BaseRefactoringProcessor.java
@@ -25,6 +25,9 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.command.UndoConfirmationPolicy;
+import com.intellij.openapi.command.undo.BasicUndoableAction;
+import com.intellij.openapi.command.undo.UndoManager;
+import com.intellij.openapi.command.undo.UndoableAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.progress.ProcessCanceledException;
@@ -43,6 +46,8 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.util.PsiUtilCore;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.listeners.RefactoringListenerManager;
 import com.intellij.refactoring.listeners.impl.RefactoringListenerManagerImpl;
 import com.intellij.refactoring.listeners.impl.RefactoringTransaction;
@@ -472,7 +477,34 @@
       ApplicationManager.getApplication().runWriteAction(new Runnable() {
         @Override
         public void run() {
-          performRefactoring(writableUsageInfos);
+          final String refactoringId = getRefactoringId();
+          if (refactoringId != null) {
+            myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringStarted(refactoringId, getBeforeData());
+          }
+
+          try {
+            if (refactoringId != null) {
+              UndoableAction action = new BasicUndoableAction() {
+                @Override
+                public void undo() {
+                  myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).undoRefactoring(refactoringId);
+                }
+  
+                @Override
+                public void redo() {
+                }
+              };
+              UndoManager.getInstance(myProject).undoableActionPerformed(action);
+            }
+
+            performRefactoring(writableUsageInfos);
+          }
+          finally {
+            if (refactoringId != null) {
+              myProject.getMessageBus()
+                .syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).refactoringDone(refactoringId, getAfterData(writableUsageInfos));
+            }
+          }
         }
       });
 
@@ -595,6 +627,12 @@
     }
 
     if (myPrepareSuccessfulSwingThreadCallback != null && !conflicts.isEmpty()) {
+      final String refactoringId = getRefactoringId();
+      if (refactoringId != null) {
+        RefactoringEventData conflictUsages = new RefactoringEventData();
+        conflictUsages.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts.values());
+        myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).conflictsDetected(refactoringId, conflictUsages);
+      }
       final ConflictsDialog conflictsDialog = prepareConflictsDialog(conflicts, usages);
       conflictsDialog.show();
       if (!conflictsDialog.isOK()) {
@@ -614,6 +652,21 @@
     return conflictsDialog;
   }
 
+  @Nullable
+  protected RefactoringEventData getBeforeData() {
+    return null;
+  }
+
+  @Nullable
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    return null;
+  }
+
+  @Nullable
+  protected String getRefactoringId() {
+    return null;
+  }
+  
   @NotNull
   protected ConflictsDialog createConflictsDialog(MultiMap<PsiElement, String> conflicts, @Nullable final UsageInfo[] usages) {
     return new ConflictsDialog(myProject, conflicts, usages == null ? null : new Runnable() {
diff --git a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessorBase.java b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessorBase.java
index ca06931..29596b7 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessorBase.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/changeSignature/ChangeSignatureProcessorBase.java
@@ -27,6 +27,7 @@
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.listeners.UndoRefactoringElementListener;
 import com.intellij.refactoring.listeners.impl.RefactoringTransaction;
 import com.intellij.refactoring.rename.ResolveSnapshotProvider;
@@ -113,6 +114,28 @@
     return super.isPreviewUsages(usages);
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.changeSignature";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(getChangeInfo().getMethod());
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(getChangeInfo().getMethod());
+    return data;
+  }
+
   @Override
   protected void performRefactoring(UsageInfo[] usages) {
     RefactoringTransaction transaction = getTransaction();
diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java
index c4ca070..b8d1c4e 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveClassesOrPackages/MoveDirectoryWithClassesProcessor.java
@@ -32,6 +32,7 @@
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.move.FileReferenceContextUtil;
 import com.intellij.refactoring.move.MoveCallback;
 import com.intellij.refactoring.move.MoveMultipleElementsViewDescriptor;
@@ -203,6 +204,28 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.move";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(myDirectories);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myTargetDirectory);
+    return data;
+  }
+
   private TargetDirectoryWrapper getResultDirectory(PsiDirectory dir) {
     return myTargetDirectory != null
            ? new TargetDirectoryWrapper(myTargetDirectory, dir.getName())
diff --git a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java
index 2ada56d..86924b2 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/move/moveFilesOrDirectories/MoveFilesOrDirectoriesProcessor.java
@@ -30,6 +30,7 @@
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
+import com.intellij.refactoring.listeners.RefactoringEventData;
 import com.intellij.refactoring.move.FileReferenceContextUtil;
 import com.intellij.refactoring.move.MoveCallback;
 import com.intellij.refactoring.rename.RenameUtil;
@@ -40,6 +41,7 @@
 import com.intellij.util.IncorrectOperationException;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.*;
 
@@ -213,6 +215,28 @@
     }
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.move";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElements(myElementsToMove);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myNewParent);
+    return data;
+  }
+
   private static void processDirectoryFiles(List<PsiFile> movedFiles, Map<PsiElement, PsiElement> oldToNewMap, PsiElement psiElement) {
     if (psiElement instanceof PsiFile) {
       final PsiFile movedFile = (PsiFile)psiElement;
diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java
index 565d75e..7e8ec09 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/rename/RenameProcessor.java
@@ -36,13 +36,12 @@
 import com.intellij.refactoring.RefactoringBundle;
 import com.intellij.refactoring.copy.CopyFilesOrDirectoriesHandler;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.rename.naming.AutomaticRenamer;
 import com.intellij.refactoring.rename.naming.AutomaticRenamerFactory;
 import com.intellij.refactoring.ui.ConflictsDialog;
-import com.intellij.refactoring.util.CommonRefactoringUtil;
-import com.intellij.refactoring.util.MoveRenameUsageInfo;
-import com.intellij.refactoring.util.NonCodeUsageInfo;
-import com.intellij.refactoring.util.RelatedUsageInfo;
+import com.intellij.refactoring.util.*;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.usageView.UsageViewDescriptor;
 import com.intellij.usageView.UsageViewUtil;
@@ -147,6 +146,11 @@
     RenameUtil.addConflictDescriptions(usagesIn, conflicts);
     RenamePsiElementProcessor.forElement(myPrimaryElement).findExistingNameConflicts(myPrimaryElement, myNewName, conflicts, myAllRenames);
     if (!conflicts.isEmpty()) {
+
+      final RefactoringEventData conflictData = new RefactoringEventData();
+      conflictData.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts.values());
+      myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).conflictsDetected("refactoring.rename", conflictData);
+
       if (ApplicationManager.getApplication().isUnitTestMode()) {
         throw new ConflictsInTestsException(conflicts.values());
       }
@@ -324,6 +328,28 @@
     return false;
   }
 
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.rename";
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    final RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myPrimaryElement);
+    return data;
+  }
+
+  @Nullable
+  @Override
+  protected RefactoringEventData getAfterData(UsageInfo[] usages) {
+    final RefactoringEventData data = new RefactoringEventData();
+    data.addElement(myPrimaryElement);
+    return data;
+  }
+
   @Override
   public void performRefactoring(UsageInfo[] usages) {
     final int[] choice = myAllRenames.size() > 1 ? new int[]{-1} : null;
diff --git a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java
index 5467be7..2d2d0b1 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/rename/inplace/MemberInplaceRenamer.java
@@ -229,6 +229,12 @@
       renameProcessor = new RenameProcessor(myProject, element, newName,
                                             elementProcessor.isToSearchInComments(element),
                                             elementProcessor.isToSearchForTextOccurrences(element)){
+      @Nullable
+      @Override
+      protected String getRefactoringId() {
+        return "refactoring.inplace.rename";
+      }
+
       @Override
       public void doRun() {
         try {
diff --git a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java
index 284f3fe..2cd0f7e 100644
--- a/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java
+++ b/platform/lang-impl/src/com/intellij/refactoring/safeDelete/SafeDeleteProcessor.java
@@ -34,13 +34,13 @@
 import com.intellij.psi.util.PsiUtilCore;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.RefactoringBundle;
+import com.intellij.refactoring.listeners.RefactoringEventData;
+import com.intellij.refactoring.listeners.RefactoringEventListener;
 import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteCustomUsageInfo;
 import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceSimpleDeleteUsageInfo;
 import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteReferenceUsageInfo;
 import com.intellij.refactoring.safeDelete.usageInfo.SafeDeleteUsageInfo;
-import com.intellij.refactoring.util.NonCodeSearchDescriptionLocation;
-import com.intellij.refactoring.util.RefactoringUIUtil;
-import com.intellij.refactoring.util.TextOccurrencesUtil;
+import com.intellij.refactoring.util.*;
 import com.intellij.usageView.UsageInfo;
 import com.intellij.usageView.UsageViewDescriptor;
 import com.intellij.usageView.UsageViewUtil;
@@ -200,6 +200,9 @@
     }
 
     if (!conflicts.isEmpty()) {
+      final RefactoringEventData conflictData = new RefactoringEventData();
+      conflictData.putUserData(RefactoringEventData.CONFLICTS_KEY, conflicts);
+      myProject.getMessageBus().syncPublisher(RefactoringEventListener.REFACTORING_EVENT_TOPIC).conflictsDetected("refactoring.safeDelete", conflictData);
       if (ApplicationManager.getApplication().isUnitTestMode()) {
         if (!ConflictsInTestsException.isTestIgnore()) throw new ConflictsInTestsException(conflicts);
       }
@@ -367,6 +370,20 @@
     return list.toArray(new UsageInfo[list.size()]);
   }
 
+  @Nullable
+  @Override
+  protected RefactoringEventData getBeforeData() {
+    final RefactoringEventData beforeData = new RefactoringEventData();
+    beforeData.addElements(myElements);
+    return beforeData;
+  }
+
+  @Nullable
+  @Override
+  protected String getRefactoringId() {
+    return "refactoring.safeDelete";
+  }
+
   @Override
   protected void performRefactoring(UsageInfo[] usages) {
     try {
diff --git a/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java b/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java
index a5d469b..403a17f 100644
--- a/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java
+++ b/platform/lang-impl/src/com/intellij/ui/DeferredIconImpl.java
@@ -21,6 +21,7 @@
 
 import com.intellij.concurrency.Job;
 import com.intellij.concurrency.JobLauncher;
+import com.intellij.ide.PowerSaveMode;
 import com.intellij.openapi.application.ex.ApplicationManagerEx;
 import com.intellij.openapi.progress.ProcessCanceledException;
 import com.intellij.openapi.project.IndexNotReadyException;
@@ -82,7 +83,7 @@
       myDelegateIcon.paintIcon(c, g, x, y); //SOE protection
     }
 
-    if (myIsScheduled || isDone()) {
+    if (myIsScheduled || isDone() || PowerSaveMode.isEnabled()) {
       return;
     }
     myIsScheduled = true;
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java b/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java
index 10adf97..50e87f8 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/AbstractIndex.java
@@ -16,6 +16,7 @@
 
 package com.intellij.util.indexing;
 
+import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.util.Processor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -28,5 +29,5 @@
   @NotNull
   ValueContainer<Value> getData(Key key) throws StorageException;
 
-  boolean processAllKeys(Processor<Key> processor, @Nullable IdFilter idFilter) throws StorageException;
+  boolean processAllKeys(Processor<Key> processor, GlobalSearchScope scope, @Nullable IdFilter idFilter) throws StorageException;
 }
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 8733756..6f803ce 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/FileBasedIndexImpl.java
@@ -391,17 +391,6 @@
 
     initIndexStorage(extension, version, versionFile);
 
-    // save versions at last, they must be saved after initIndexVersion as it also can rewrite version
-    Map<FileType, Integer> versionMap = extension.getVersionMap();
-    for (Map.Entry<FileType, Integer> entry : versionMap.entrySet()) {
-      ID stubId = IndexInfrastructure.getStubId(name, entry.getKey());
-      File file = IndexInfrastructure.getVersionFile(stubId);
-      Integer stubVersion = entry.getValue();
-      if (!file.exists() || IndexInfrastructure.versionDiffers(file, stubVersion)) {
-        LOG.info("Version has changed for index " + stubId + ". The index will be rebuilt.");
-        IndexInfrastructure.rewriteVersion(file, stubVersion);
-      }
-    }
     return versionChanged;
   }
 
@@ -736,7 +725,7 @@
         return true;
       }
       ensureUpToDate(indexId, scope.getProject(), scope);
-      return index.processAllKeys(processor, idFilter);
+      return index.processAllKeys(processor, scope, idFilter);
     }
     catch (StorageException e) {
       scheduleRebuild(indexId, e);
@@ -1546,7 +1535,9 @@
     final long previousDocStamp = myLastIndexedDocStamps.getAndSet(document, requestedIndexId, currentDocStamp);
     if (currentDocStamp != previousDocStamp) {
       final String contentText = content.getText();
-      if (!isTooLarge(vFile, contentText.length()) && getInputFilter(requestedIndexId).acceptInput(vFile)) {
+      if (!isTooLarge(vFile, contentText.length()) &&
+          getAffectedIndexCandidates(vFile).contains(requestedIndexId) &&
+          getInputFilter(requestedIndexId).acceptInput(vFile)) {
         // Reasonably attempt to use same file content when calculating indices as we can evaluate them several at once and store in file content
         WeakReference<FileContentImpl> previousContentRef = document.getUserData(ourFileContentKey);
         FileContentImpl previousContent = previousContentRef != null ? previousContentRef.get() : null;
@@ -1788,25 +1779,23 @@
 
     scheduleUpdate(indexId,
                    createUpdateComputableWithBufferingDisabled(update),
-                   createIndexedStampUpdateRunnable(indexId, file, fileType, currentFC != null)
+                   createIndexedStampUpdateRunnable(indexId, file, currentFC != null)
     );
   }
 
   private Runnable createIndexedStampUpdateRunnable(final ID<?, ?> indexId,
                                                     final VirtualFile file,
-                                                    final FileType fileType,
                                                     final boolean hasContent) {
     return new Runnable() {
       @Override
       public void run() {
         if (file.isValid()) {
-          ID stubId = IndexInfrastructure.getStubId(indexId, fileType);
           if (hasContent) {
-            IndexingStamp.update(file, stubId, getIndexCreationStamp(stubId, fileType));
+            IndexingStamp.update(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId));
           }
           else {
             // mark the file as unindexed
-            IndexingStamp.update(file, stubId, IndexInfrastructure.INVALID_STAMP);
+            IndexingStamp.update(file, indexId, IndexInfrastructure.INVALID_STAMP);
           }
           if (myNotRequiringContentIndices.contains(indexId)) IndexingStamp.flushCache(file);
         }
@@ -1991,9 +1980,8 @@
             for (int i = 0, size = candidates.size(); i < size; ++i) {
               final ID<?, ?> indexId = candidates.get(i);
               if (needsFileContentLoading(indexId) && getInputFilter(indexId).acceptInput(file)) {
-                ID id = IndexInfrastructure.getStubId(indexId, fileType);
-                if (IndexingStamp.isFileIndexed(file, id, IndexInfrastructure.getIndexCreationStamp(id))) {
-                  IndexingStamp.update(file, id, IndexInfrastructure.INVALID_STAMP2);
+                if (IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId))) {
+                  IndexingStamp.update(file, indexId, IndexInfrastructure.INVALID_STAMP2);
                   resetStamp = true;
                 }
                 scheduleForUpdate = true;
@@ -2083,8 +2071,7 @@
             public void run() {
               FileType fileType = file.getFileType();
               for (ID<?, ?> indexId : affectedIndices) {
-                ID id = IndexInfrastructure.getStubId(indexId, fileType);
-                IndexingStamp.update(file, id, IndexInfrastructure.INVALID_STAMP2);
+                IndexingStamp.update(file, indexId, IndexInfrastructure.INVALID_STAMP2);
               }
             }
           });
@@ -2432,12 +2419,7 @@
   }
 
   private static boolean isFileIndexed(VirtualFile file, ID<?, ?> indexId) {
-    ID id = IndexInfrastructure.getStubId(indexId, file.getFileType());
-    return IndexingStamp.isFileIndexed(file, id, IndexInfrastructure.getIndexCreationStamp(id));
-  }
-
-  private static long getIndexCreationStamp(ID<?, ?> indexId, FileType fileType) {
-    return IndexInfrastructure.getIndexCreationStamp(indexId, fileType);
+    return IndexingStamp.isFileIndexed(file, indexId, IndexInfrastructure.getIndexCreationStamp(indexId));
   }
 
   private boolean isUnderConfigOrSystem(@NotNull VirtualFile file) {
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java b/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java
index 900c6e3..6d16833 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/IndexInfrastructure.java
@@ -21,7 +21,6 @@
 
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.PathManager;
-import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.io.FileUtilRt;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -119,26 +118,6 @@
     return stamp;
   }
 
-  public static long getIndexCreationStamp(ID<?, ?> indexName, FileType fileType) {
-    return getIndexCreationStamp(getStubId(indexName, fileType));
-  }
-
-  public static ID getStubId(ID<?, ?> indexName, FileType fileType) {
-    if (StubUpdatingIndex.INDEX_ID.equals(indexName)) {
-      String name = fileType.getName();
-      ID id = ID.findByName(name);
-      if (id != null) {
-        return id;
-      }
-      else {
-        return StubIndexKey.createIndexKey(name);
-      }
-    }
-    else {
-      return indexName;
-    }
-  }
-
   public static boolean versionDiffers(final File versionFile, final int currentIndexVersion) {
     try {
       ourLastStamp = Math.max(ourLastStamp, versionFile.lastModified());
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java
index 5e0296b..0f8bb67 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/IndexStorage.java
@@ -16,6 +16,7 @@
 
 package com.intellij.util.indexing;
 
+import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.util.Processor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -39,7 +40,7 @@
   @NotNull
   ValueContainer<Value> read(Key key) throws StorageException;
 
-  boolean processKeys(Processor<Key> processor, @Nullable IdFilter idFilter) throws StorageException;
+  boolean processKeys(Processor<Key> processor, GlobalSearchScope scope, @Nullable IdFilter idFilter) throws StorageException;
 
   Collection<Key> getKeys() throws StorageException;
 
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
index b0eaf2d..649bd25 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/MapIndexStorage.java
@@ -18,20 +18,24 @@
 
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressManager;
+import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.LowMemoryWatcher;
 import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.psi.search.GlobalSearchScope;
+import com.intellij.psi.search.ProjectAndLibrariesScope;
+import com.intellij.psi.search.ProjectScopeImpl;
 import com.intellij.util.CommonProcessors;
 import com.intellij.util.Processor;
+import com.intellij.util.SystemProperties;
 import com.intellij.util.containers.SLRUCache;
 import com.intellij.util.io.*;
+import com.intellij.util.io.DataOutputStream;
 import gnu.trove.TIntHashSet;
+import gnu.trove.TIntProcedure;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.io.DataInput;
-import java.io.DataOutput;
-import java.io.File;
-import java.io.IOException;
+import java.io.*;
 import java.util.ArrayList;
 import java.util.Collection;
 import java.util.List;
@@ -44,10 +48,12 @@
 */
 public final class MapIndexStorage<Key, Value> implements IndexStorage<Key, Value>{
   private static final Logger LOG = Logger.getInstance("#com.intellij.util.indexing.MapIndexStorage");
+  private static final boolean ENABLE_CACHED_HASH_IDS = SystemProperties.getBooleanProperty("idea.index.no.cashed.hashids", true);
   private final boolean myBuildKeyHashToVirtualFileMapping;
   private PersistentMap<Key, ValueContainer<Value>> myMap;
   private PersistentBTreeEnumerator<int[]> myKeyHashToVirtualFileMapping;
   private SLRUCache<Key, ChangeTrackingValueContainer<Value>> myCache;
+  private volatile int myLastScannedId;
   private final File myStorageFile;
   private final KeyDescriptor<Key> myKeyDescriptor;
   private final int myCacheSize;
@@ -216,29 +222,58 @@
   }
 
   @Override
-  public boolean processKeys(final Processor<Key> processor, final IdFilter idFilter) throws StorageException {
+  public boolean processKeys(final Processor<Key> processor, GlobalSearchScope scope, final IdFilter idFilter) throws StorageException {
     l.lock();
     try {
       myCache.clear(); // this will ensure that all new keys are made into the map
       if (myBuildKeyHashToVirtualFileMapping && idFilter != null) {
-        final TIntHashSet hashMaskSet = new TIntHashSet(1000);
+        TIntHashSet hashMaskSet = null;
         long l = System.currentTimeMillis();
-        myKeyHashToVirtualFileMapping.iterateData(new Processor<int[]>() {
-          @Override
-          public boolean process(int[] key) {
-            if (!idFilter.containsFileId(key[1])) return true;
-            hashMaskSet.add(key[0]);
-            ProgressManager.checkCanceled();
-            return true;
+
+        File fileWithCaches = getSavedProjectFileValueIds(myLastScannedId, scope);
+        final boolean useCachedHashIds = ENABLE_CACHED_HASH_IDS &&
+                                         (scope instanceof ProjectScopeImpl || scope instanceof ProjectAndLibrariesScope) &&
+                                         fileWithCaches != null;
+        int id = myKeyHashToVirtualFileMapping.getLargestId();
+
+        if (useCachedHashIds && id == myLastScannedId) {
+          try {
+            hashMaskSet = loadHashedIds(fileWithCaches);
+          } catch (IOException ex) {
+            LOG.info(ex);
           }
-        });
+        }
+
+        if (hashMaskSet == null) {
+          if (useCachedHashIds && myLastScannedId != 0) {
+            FileUtil.asyncDelete(fileWithCaches);
+          }
+
+          hashMaskSet = new TIntHashSet(1000);
+          final TIntHashSet finalHashMaskSet = hashMaskSet;
+          myKeyHashToVirtualFileMapping.iterateData(new Processor<int[]>() {
+            @Override
+            public boolean process(int[] key) {
+              if (!idFilter.containsFileId(key[1])) return true;
+              finalHashMaskSet.add(key[0]);
+              ProgressManager.checkCanceled();
+              return true;
+            }
+          });
+
+          if (useCachedHashIds) {
+            saveHashedIds(hashMaskSet, id, scope);
+          }
+        }
+
         if (LOG.isDebugEnabled()) {
           LOG.debug("Scanned keyHashToVirtualFileMapping of " + myStorageFile + " for " + (System.currentTimeMillis() - l));
         }
+        final TIntHashSet finalHashMaskSet = hashMaskSet;
         return myMap.processKeys(new Processor<Key>() {
           @Override
           public boolean process(Key key) {
-            if (!hashMaskSet.contains(myKeyDescriptor.getHashCode(key))) return true;
+            if (!finalHashMaskSet.contains(myKeyDescriptor.getHashCode(key))) return true;
             return processor.process(key);
           }
         });
@@ -263,11 +298,70 @@
     }
   }
 
+  private static TIntHashSet loadHashedIds(File fileWithCaches) throws IOException {
+    DataInputStream inputStream = null;
+    try {
+      inputStream = new DataInputStream(new BufferedInputStream(new FileInputStream(fileWithCaches)));
+      int capacity = DataInputOutputUtil.readINT(inputStream);
+      TIntHashSet hashMaskSet = new TIntHashSet(capacity);
+      while(capacity > 0) {
+        hashMaskSet.add(DataInputOutputUtil.readINT(inputStream));
+        --capacity;
+      }
+      inputStream.close();
+      return hashMaskSet;
+    }
+    finally {
+      if (inputStream != null) {
+        try {
+          inputStream.close();
+        } catch (IOException ex) {}
+      }
+    }
+  }
+
+  private void saveHashedIds(TIntHashSet hashMaskSet, int largestId, GlobalSearchScope scope) {
+    File newFileWithCaches = getSavedProjectFileValueIds(largestId, scope);
+    assert newFileWithCaches != null;
+    DataOutputStream stream = null;
+
+    try {
+      stream = new DataOutputStream(new BufferedOutputStream(new FileOutputStream(newFileWithCaches)));
+      DataInputOutputUtil.writeINT(stream, hashMaskSet.size());
+      final DataOutputStream finalStream = stream;
+      boolean result = hashMaskSet.forEach(new TIntProcedure() {
+        @Override
+        public boolean execute(int value) {
+          try {
+            DataInputOutputUtil.writeINT(finalStream, value);
+            return true;
+          } catch (IOException ex) {
+            return false;
+          }
+        }
+      });
+      if (result) myLastScannedId = largestId;
+    } catch (IOException ex) {}
+    finally {
+      if (stream != null) {
+        try {
+          stream.close();
+        } catch (IOException ex) {}
+      }
+    }
+  }
+
+  private @Nullable File getSavedProjectFileValueIds(int id, GlobalSearchScope scope) {
+    Project project = scope.getProject();
+    if (project == null) return null;
+    return new File(myStorageFile.getPath() + ".project."+project.hashCode() + "."+id + "." + scope.isSearchInLibraries());
+  }
+
   @NotNull
   @Override
   public Collection<Key> getKeys() throws StorageException {
     List<Key> keys = new ArrayList<Key>();
-    processKeys(new CommonProcessors.CollectProcessor<Key>(keys), null);
+    processKeys(new CommonProcessors.CollectProcessor<Key>(keys), null, null);
     return keys;
   }
 
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 98b62a5..77dfef3 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/MapReduceIndex.java
@@ -22,6 +22,7 @@
 import com.intellij.openapi.util.Factory;
 import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.util.Processor;
 import com.intellij.util.io.PersistentHashMap;
 import gnu.trove.THashMap;
@@ -155,11 +156,11 @@
   }
 
   @Override
-  public boolean processAllKeys(Processor<Key> processor, IdFilter idFilter) throws StorageException {
+  public boolean processAllKeys(Processor<Key> processor, GlobalSearchScope scope, IdFilter idFilter) throws StorageException {
     final Lock lock = getReadLock();
     try {
       lock.lock();
-      return myStorage.processKeys(processor, idFilter);
+      return myStorage.processKeys(processor, scope, idFilter);
     }
     finally {
       lock.unlock();
diff --git a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java
index f07fc85..2b27622 100644
--- a/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java
+++ b/platform/lang-impl/src/com/intellij/util/indexing/MemoryIndexStorage.java
@@ -16,6 +16,7 @@
 
 package com.intellij.util.indexing;
 
+import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.util.CommonProcessors;
 import com.intellij.util.Processor;
 import com.intellij.util.containers.ContainerUtil;
@@ -101,12 +102,12 @@
   @Override
   public Collection<Key> getKeys() throws StorageException {
     final Set<Key> keys = new HashSet<Key>();
-    processKeys(new CommonProcessors.CollectProcessor<Key>(keys), null);
+    processKeys(new CommonProcessors.CollectProcessor<Key>(keys), null, null);
     return keys;
   }
 
   @Override
-  public boolean processKeys(final Processor<Key> processor, IdFilter idFilter) throws StorageException {
+  public boolean processKeys(final Processor<Key> processor, GlobalSearchScope scope, IdFilter idFilter) throws StorageException {
     final Set<Key> stopList = new HashSet<Key>();
 
     Processor<Key> decoratingProcessor = new Processor<Key>() {
@@ -128,7 +129,7 @@
       }
       stopList.add(key);
     }
-    return myBackendStorage.processKeys(stopList.size() == 0 && myMap.size() == 0 ? processor : decoratingProcessor, idFilter);
+    return myBackendStorage.processKeys(stopList.size() == 0 && myMap.size() == 0 ? processor : decoratingProcessor, scope, idFilter);
   }
 
   @Override
diff --git a/platform/lang-impl/testData/platform/templates/github/invalid-archive.zip b/platform/lang-impl/testData/platform/templates/github/invalid-archive.zip
new file mode 100644
index 0000000..e69de29
--- /dev/null
+++ b/platform/lang-impl/testData/platform/templates/github/invalid-archive.zip
diff --git a/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java b/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java
index 95e065f..2f85513 100644
--- a/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java
+++ b/platform/lang-impl/testSources/com/intellij/platform/templates/github/ZipUtilTest.java
@@ -3,11 +3,13 @@
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.testFramework.PlatformTestUtil;
 import com.intellij.util.io.TestFileSystemBuilder;
+import junit.framework.Assert;
 import org.jetbrains.annotations.NotNull;
 import org.junit.Test;
 
 import java.io.File;
 import java.io.FileInputStream;
+import java.io.IOException;
 import java.util.zip.ZipInputStream;
 
 import static com.intellij.util.io.TestFileSystemBuilder.fs;
@@ -51,6 +53,41 @@
     }
   }
 
+  @Test
+  public void testSimpleUnzipUsingFile() throws Exception {
+    File tempDir = FileUtil.createTempDirectory("unzip-test-", null);
+    File simpleZipFile = new File(getZipParentDir(), "simple.zip");
+    ZipUtil.unzip(null, tempDir, simpleZipFile, null, null, true);
+    checkFileStructure(tempDir,
+                       fs()
+                         .file("a.txt")
+                         .dir("dir").file("b.txt"));
+  }
+
+  @Test
+  public void testSingleRootDirUnzipUsingFile() throws Exception {
+    File tempDir = FileUtil.createTempDirectory("unzip-test-", null);
+    File simpleZipFile = new File(getZipParentDir(), "single-root-dir-archive.zip");
+    ZipUtil.unzip(null, tempDir, simpleZipFile, null, null, true);
+    checkFileStructure(tempDir,
+                       fs()
+                         .file("a.txt")
+                         .dir("dir").file("b.txt"));
+  }
+
+  @Test
+  public void testExpectedFailureOnBrokenZipArchive() throws Exception {
+    File tempDir = FileUtil.createTempDirectory("unzip-test-", null);
+    File file = new File(getZipParentDir(), "invalid-archive.zip");
+    try {
+      ZipUtil.unzip(null, tempDir, file, null, null, true);
+      Assert.fail("Zip archive is broken, but it was unzipped without exceptions.");
+    }
+    catch (IOException e) {
+      // expected exception
+    }
+  }
+
   private static void checkFileStructure(@NotNull File parentDir, @NotNull TestFileSystemBuilder expected) {
     expected.build().assertDirectoryEqual(parentDir);
   }
diff --git a/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java b/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java
index 1c4424b..50d7a0f 100644
--- a/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java
+++ b/platform/lvcs-impl/src/com/intellij/history/integration/IdeaGateway.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,13 +31,11 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.project.ProjectManager;
 import com.intellij.openapi.roots.ProjectRootManager;
-import com.intellij.openapi.util.Clock;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Key;
-import com.intellij.openapi.util.Pair;
+import com.intellij.openapi.util.*;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.*;
 import com.intellij.openapi.vfs.encoding.EncodingRegistry;
+import com.intellij.openapi.vfs.ex.temp.TempFileSystem;
 import com.intellij.openapi.vfs.newvfs.ManagingFS;
 import com.intellij.openapi.vfs.newvfs.NewVirtualFile;
 import com.intellij.util.NullableFunction;
@@ -54,7 +52,7 @@
     = Key.create("LocalHistory.SAVED_DOCUMENT_CONTENT_AND_STAMP_KEY");
 
   public boolean isVersioned(@NotNull VirtualFile f) {
-    if (!f.isInLocalFileSystem()) return false;
+    if (!isInLocalFS(f)) return false;
 
     String fileName = f.getName();
     if (!f.isDirectory() && fileName.endsWith(".class")) return false;
@@ -71,6 +69,10 @@
     return openProjects.length != 0 || !FileTypeManager.getInstance().isFileIgnored(f);
   }
 
+  private static boolean isInLocalFS(VirtualFile file) {
+    return file.isInLocalFileSystem() && !(file.getFileSystem() instanceof TempFileSystem);
+  }
+
   public boolean areContentChangesVersioned(@NotNull VirtualFile f) {
     return isVersioned(f) && !f.isDirectory() && areContentChangesVersioned(f.getName());
   }
@@ -151,16 +153,27 @@
   public RootEntry createTransientRootEntry() {
     ApplicationManager.getApplication().assertReadAccessAllowed();
     RootEntry root = new RootEntry();
-    doCreateChildren(root, Arrays.asList(ManagingFS.getInstance().getLocalRoots()), false);
+    doCreateChildren(root, getLocalRoots(), false);
     return root;
   }
+
   @NotNull
   public RootEntry createTransientRootEntryForPathOnly(@NotNull String path) {
     ApplicationManager.getApplication().assertReadAccessAllowed();
     RootEntry root = new RootEntry();
-    doCreateChildrenForPathOnly(root, path, Arrays.asList(ManagingFS.getInstance().getLocalRoots()));
+    doCreateChildrenForPathOnly(root, path, getLocalRoots());
     return root;
   }
+
+  private static List<VirtualFile> getLocalRoots() {
+    return ContainerUtil.filter(ManagingFS.getInstance().getLocalRoots(), new Condition<VirtualFile>() {
+      @Override
+      public boolean value(VirtualFile file) {
+        return isInLocalFS(file);
+      }
+    });
+  }
+
   private void doCreateChildrenForPathOnly(@NotNull DirectoryEntry parent,
                                            @NotNull String path,
                                            @NotNull Collection<VirtualFile> children) {
diff --git a/platform/platform-api/platform-api.iml b/platform/platform-api/platform-api.iml
index e40a631..f6769b4 100644
--- a/platform/platform-api/platform-api.iml
+++ b/platform/platform-api/platform-api.iml
@@ -32,6 +32,8 @@
     <orderEntry type="library" name="proxy-vole" level="project" />
     <orderEntry type="module" module-name="analysis-api" exported="" />
     <orderEntry type="module" module-name="editor-ui-api" exported="" />
+    <orderEntry type="library" name="pty4j" level="project" />
+    <orderEntry type="library" name="Guava" level="project" />
   </component>
 </module>
 
diff --git a/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java b/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java
index 3a1e9f4..0b6dc4ca 100644
--- a/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java
+++ b/platform/platform-api/src/com/intellij/execution/configurations/GeneralCommandLine.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.execution.configurations;
 
+import com.google.common.collect.Maps;
 import com.intellij.execution.CommandLineUtil;
 import com.intellij.execution.ExecutionException;
 import com.intellij.execution.Platform;
@@ -26,10 +27,12 @@
 import com.intellij.openapi.util.UserDataHolder;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.CharsetToolkit;
+import com.intellij.util.ArrayUtil;
 import com.intellij.util.EnvironmentUtil;
 import com.intellij.util.PlatformUtils;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.text.CaseInsensitiveStringHashingStrategy;
+import com.pty4j.PtyProcess;
 import gnu.trove.THashMap;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -62,8 +65,10 @@
   private Charset myCharset = CharsetToolkit.getDefaultSystemCharset();
   private boolean myRedirectErrorStream = false;
   private Map<Object, Object> myUserData = null;
+  private boolean myStartProcessWithPty = false;
 
-  public GeneralCommandLine() { }
+  public GeneralCommandLine() {
+  }
 
   public GeneralCommandLine(@NotNull String... command) {
     this(Arrays.asList(command));
@@ -107,13 +112,17 @@
     return myEnvParams;
   }
 
-  /** @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) */
+  /**
+   * @deprecated use {@link #getEnvironment()} (to remove in IDEA 14)
+   */
   @SuppressWarnings("unused")
   public Map<String, String> getEnvParams() {
     return getEnvironment();
   }
 
-  /** @deprecated use {@link #getEnvironment()} (to remove in IDEA 14) */
+  /**
+   * @deprecated use {@link #getEnvironment()} (to remove in IDEA 14)
+   */
   @SuppressWarnings("unused")
   public void setEnvParams(@Nullable Map<String, String> envParams) {
     myEnvParams.clear();
@@ -126,7 +135,9 @@
     myPassParentEnvironment = passParentEnvironment;
   }
 
-  /** @deprecated use {@link #setPassParentEnvironment(boolean)} (to remove in IDEA 14) */
+  /**
+   * @deprecated use {@link #setPassParentEnvironment(boolean)} (to remove in IDEA 14)
+   */
   @SuppressWarnings({"unused", "SpellCheckingInspection"})
   public void setPassParentEnvs(boolean passParentEnvironment) {
     setPassParentEnvironment(passParentEnvironment);
@@ -136,6 +147,15 @@
     return myPassParentEnvironment;
   }
 
+  /**
+   * If argument is true the process created with Pseudo-Terminal (PTY). 
+   * This works only on Unix. On Windows the option is ignored.   
+   */
+  public GeneralCommandLine withPty(boolean startProcessWithPty) {
+    myStartProcessWithPty = startProcessWithPty;
+    return this;
+  }
+
   public void addParameters(final String... parameters) {
     for (String parameter : parameters) {
       addParameter(parameter);
@@ -235,11 +255,21 @@
     }
 
     try {
-      ProcessBuilder builder = new ProcessBuilder(commands);
-      setupEnvironment(builder.environment());
-      builder.directory(myWorkDirectory);
-      builder.redirectErrorStream(myRedirectErrorStream);
-      return builder.start();
+      if (myStartProcessWithPty && SystemInfo.isUnix) {
+        try {
+          Map<String, String> env = Maps.newHashMap();
+          setupEnvironment(env);
+          if (myRedirectErrorStream) {
+            LOG.error("Launching process with PTY and redirected error stream is unsupported yet");
+          }
+          return PtyProcessHolder.doExec(myWorkDirectory, commands, env);
+        }
+        catch (Throwable e) {
+          LOG.error("Couldn't run process with PTY", e);
+        }
+      }
+
+      return startProcess(commands);
     }
     catch (IOException e) {
       LOG.warn(e);
@@ -247,6 +277,20 @@
     }
   }
 
+  private static class PtyProcessHolder { // holder for lazy PtyProcess class loading
+    private static Process doExec(File workDirectory, List<String> commands, Map<String, String> env) throws IOException {
+      return PtyProcess.exec(ArrayUtil.toStringArray(commands), env, workDirectory != null ? workDirectory.getPath() : null, true);
+    }
+  }
+
+  private Process startProcess(List<String> commands) throws IOException {
+    ProcessBuilder builder = new ProcessBuilder(commands);
+    setupEnvironment(builder.environment());
+    builder.directory(myWorkDirectory);
+    builder.redirectErrorStream(myRedirectErrorStream);
+    return builder.start();
+  }
+
   private void checkWorkingDirectory() throws ExecutionException {
     if (myWorkDirectory == null) {
       return;
diff --git a/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java b/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java
index 482915b..3191ac0 100644
--- a/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java
+++ b/platform/platform-api/src/com/intellij/execution/util/ExecUtil.java
@@ -312,11 +312,10 @@
       return Arrays.asList(getWindowsShellName(), "/c", "start", GeneralCommandLine.inescapableQuote(title), command);
     }
     else if (SystemInfo.isMac) {
-      return Arrays.asList(getOpenCommandPath(), "-a", "Terminal", command); // todo: title?
+      return Arrays.asList(getOpenCommandPath(), "-a", "Terminal", command);  // todo[r.sh] title?
     }
     else if (hasKdeTerminal.getValue()) {
-      return title != null ? Arrays.asList("/usr/bin/konsole", "-p", "tabtitle=\"" + title.replace("\"", "'") + "\"", "-e", command)
-                           : Arrays.asList("/usr/bin/konsole", "-e", command);
+      return Arrays.asList("/usr/bin/konsole", "-e", command);  // todo[r.sh] title?
     }
     else if (hasGnomeTerminal.getValue()) {
       return title != null ? Arrays.asList("/usr/bin/gnome-terminal", "-t", title, "-x", command)
diff --git a/platform/platform-api/src/com/intellij/ide/ui/UISettingsOptionDescription.java b/platform/platform-api/src/com/intellij/ide/ui/PublicFieldBasedOptionDescription.java
similarity index 69%
rename from platform/platform-api/src/com/intellij/ide/ui/UISettingsOptionDescription.java
rename to platform/platform-api/src/com/intellij/ide/ui/PublicFieldBasedOptionDescription.java
index 36777a8..d0c3989 100644
--- a/platform/platform-api/src/com/intellij/ide/ui/UISettingsOptionDescription.java
+++ b/platform/platform-api/src/com/intellij/ide/ui/PublicFieldBasedOptionDescription.java
@@ -22,19 +22,23 @@
 /**
  * @author Konstantin Bulenkov
  */
-public class UISettingsOptionDescription extends BooleanOptionDescription {
+public abstract class PublicFieldBasedOptionDescription extends BooleanOptionDescription {
   private final String myFieldName;
 
-  public UISettingsOptionDescription(String fieldName, String option, String configurableId) {
+  public PublicFieldBasedOptionDescription(String option, String configurableId, String fieldName) {
     super(option, configurableId);
     myFieldName = fieldName;
   }
 
+  public abstract Object getInstance();
+
+  protected abstract void fireUpdated();
+
   @Override
   public boolean isOptionEnabled() {
     try {
-      final Field field = UISettings.class.getField(myFieldName);
-      return field.getBoolean(UISettings.getInstance());
+      final Field field = getInstance().getClass().getField(myFieldName);
+      return field.getBoolean(getInstance());
     }
     catch (NoSuchFieldException ignore) {
     }
@@ -46,15 +50,13 @@
   @Override
   public void setOptionState(boolean enabled) {
     try {
-      final Field field = UISettings.class.getField(myFieldName);
-      field.setBoolean(UISettings.getInstance(), enabled);
+      final Field field = getInstance().getClass().getField(myFieldName);
+      field.setBoolean(getInstance(), enabled);
     }
     catch (NoSuchFieldException ignore) {
     }
     catch (IllegalAccessException ignore) {
     }
-    UISettings.getInstance().fireUISettingsChanged();
+    fireUpdated();
   }
-
-
 }
diff --git a/platform/platform-api/src/com/intellij/ide/ui/UISimpleSettingsProvider.java b/platform/platform-api/src/com/intellij/ide/ui/UISimpleSettingsProvider.java
deleted file mode 100644
index 2623a55..0000000
--- a/platform/platform-api/src/com/intellij/ide/ui/UISimpleSettingsProvider.java
+++ /dev/null
@@ -1,47 +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.ide.ui;
-
-import com.intellij.ide.SearchTopHitProvider;
-import com.intellij.util.Consumer;
-
-/**
- * @author Konstantin Bulenkov
- */
-public class UISimpleSettingsProvider implements SearchTopHitProvider {
-  private static UISettingsOptionDescription CYCLING_SCROLLING = new UISettingsOptionDescription("CYCLING_SCROLLING", "Cyclic scrolling", "appearance");
-  private static UISettingsOptionDescription MEMORY_INDICATOR = new UISettingsOptionDescription("SHOW_MEMORY_INDICATOR", "Show Memory Indicator", "appearance");
-
-
-  @Override
-  public void consumeTopHits(String pattern, Consumer<Object> collector) {
-    pattern = pattern.trim().toLowerCase();
-    if (pattern.startsWith("cyc") || pattern.startsWith("scr") || patternContains(pattern, "scroll")) {
-      collector.consume(CYCLING_SCROLLING);
-    } else if (patternContains(pattern, "memo")) {
-      collector.consume(MEMORY_INDICATOR);
-    }
-  }
-
-  private static boolean patternContains(String pattern, String search) {
-    for (String s : pattern.split(" ")) {
-      if (s.contains(search)) {
-        return true;
-      }
-    }
-    return false;
-  }
-}
diff --git a/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java b/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java
index 568abaf..7f9e405 100644
--- a/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java
+++ b/platform/platform-api/src/com/intellij/openapi/actionSystem/IdeActions.java
@@ -71,6 +71,7 @@
   @NonNls String ACTION_SMART_TYPE_COMPLETION = "SmartTypeCompletion";
   @Deprecated @NonNls String ACTION_CLASS_NAME_COMPLETION = "ClassNameCompletion";
   @NonNls String ACTION_HIPPIE_COMPLETION = "HippieCompletion";
+  @NonNls String ACTION_HIPPIE_BACKWARD_COMPLETION = "HippieBackwardCompletion";
   @NonNls String ACTION_CHOOSE_LOOKUP_ITEM = "EditorChooseLookupItem";
   @NonNls String ACTION_CHOOSE_LOOKUP_ITEM_ALWAYS = "EditorChooseLookupItemAlways";
   @NonNls String ACTION_CHOOSE_LOOKUP_ITEM_REPLACE = "EditorChooseLookupItemReplace";
diff --git a/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorProvider.java b/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorProvider.java
index 946ca43..2f6d2f6 100644
--- a/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorProvider.java
+++ b/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorProvider.java
@@ -62,7 +62,8 @@
   void disposeEditor(@NotNull FileEditor editor);
 
   /**
-   * Deserializes state from the specified <code>sourceElemet</code>
+   * Deserialize state from the specified <code>sourceElement</code>
+   * Use {@link FileEditorState#INSTANCE} as default implementation
    */
   @NotNull
   FileEditorState readState(@NotNull Element sourceElement, @NotNull Project project, @NotNull VirtualFile file);
diff --git a/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorState.java b/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorState.java
index aa356d4..277a679 100644
--- a/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorState.java
+++ b/platform/platform-api/src/com/intellij/openapi/fileEditor/FileEditorState.java
@@ -23,8 +23,8 @@
  * @author Vladimir Kondratyev
  */
 public interface FileEditorState {
-
   FileEditorState INSTANCE = new FileEditorState() {
+    @Override
     public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
       return true;
     }
diff --git a/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java b/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java
index 3acfb0d..d8f6572 100644
--- a/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java
+++ b/platform/platform-api/src/com/intellij/openapi/fileEditor/OpenFileDescriptor.java
@@ -118,12 +118,12 @@
       throw new IllegalStateException("Navigation is not possible with null project");
     }
 
-    if (!myFile.isDirectory() && navigateInEditor(myProject, requestFocus)) return;
+    if (!myFile.isDirectory() && navigateInEditorOrNativeApp(myProject, requestFocus)) return;
 
     navigateInProjectView(requestFocus);
   }
 
-  private boolean navigateInEditor(@NotNull Project project, boolean requestFocus) {
+  private boolean navigateInEditorOrNativeApp(@NotNull Project project, boolean requestFocus) {
     FileType type = FileTypeManager.getInstance().getKnownFileTypeOrAssociate(myFile,project);
     if (type == null || !myFile.isValid()) return false;
 
@@ -131,6 +131,10 @@
       return ((INativeFileType) type).openFileInAssociatedApplication(project, myFile);
     }
 
+    return navigateInEditor(project, requestFocus);
+  }
+
+  public boolean navigateInEditor(@NotNull Project project, boolean requestFocus) {
     return navigateInRequestedEditor() || navigateInAnyFileEditor(project, requestFocus);
   }
 
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java b/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java
index 7680fbb..beded7f 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/ComboBox.java
@@ -49,6 +49,7 @@
   private int myMinimumAndPreferredWidth;
   private boolean mySwingPopup = true;
   private JBPopup myJBPopup;
+  protected boolean myPaintingNow;
 
   public ComboBox() {
     this(-1);
@@ -252,7 +253,15 @@
       width = preferredSize.width;
     }
 
-    return new Dimension(width, preferredSize.height);
+    return new Dimension(width, UIUtil.fixComboBoxHeight(preferredSize.height));
+  }
+
+  @Override
+  public boolean hasFocus() {
+    if (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel() && myPaintingNow) {
+      return false;
+    }
+    return super.hasFocus();
   }
 
   protected Dimension getOriginalPreferredSize() {
@@ -261,8 +270,13 @@
 
   @Override
   public void paint(Graphics g) {
-    super.paint(g);
-    if (Boolean.TRUE != getClientProperty("JComboBox.isTableCellEditor")) MacUIUtil.drawComboboxFocusRing(this, g);
+    try {
+      myPaintingNow = true;
+      super.paint(g);
+      if (Boolean.TRUE != getClientProperty("JComboBox.isTableCellEditor")) MacUIUtil.drawComboboxFocusRing(this, g);
+    } finally {
+      myPaintingNow = false;
+    }
   }
 
   private static final class MyEditor implements ComboBoxEditor {
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/DialogBuilder.java b/platform/platform-api/src/com/intellij/openapi/ui/DialogBuilder.java
index 480cea6..65b5d76 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/DialogBuilder.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/DialogBuilder.java
@@ -93,6 +93,11 @@
     myTitle = title;
   }
 
+  public DialogBuilder title(@NotNull String title) {
+    myTitle = title;
+    return this;
+  }
+
   public void setPreferredFocusComponent(JComponent component) {
     myPreferedFocusComponent = component;
   }
@@ -101,6 +106,11 @@
     myDimensionServiceKey = dimensionServiceKey;
   }
 
+  public DialogBuilder dimensionKey(@NotNull String dimensionServiceKey) {
+    myDimensionServiceKey = dimensionServiceKey;
+    return this;
+  }
+
   public void addAction(Action action) {
     addActionDescriptor(new CustomActionDescriptor(action));
   }
@@ -212,6 +222,7 @@
       myMnemonicChar = mnemonicChar == -1 ? null : Integer.valueOf(mnemonicChar);
     }
 
+    @Override
     public Action getAction(DialogWrapper dialogWrapper) {
       Action action = createAction(dialogWrapper);
       action.putValue(Action.NAME, myName);
@@ -245,8 +256,10 @@
       return closeDialogAction;
     }
 
+    @Override
     protected Action createAction(final DialogWrapper dialogWrapper) {
       return new AbstractAction(){
+        @Override
         public void actionPerformed(ActionEvent e) {
           dialogWrapper.close(myExitCode);
         }
@@ -265,6 +278,7 @@
       myAction = action;
     }
 
+    @Override
     public Action getAction(DialogWrapper dialogWrapper) {
       return myAction;
     }
@@ -273,10 +287,12 @@
   private abstract static class BuiltinAction implements ActionDescriptor, CustomizableAction {
     protected String myText = null;
 
+    @Override
     public void setText(String text) {
       myText = text;
     }
 
+    @Override
     public Action getAction(DialogWrapper dialogWrapper) {
       Action builtinAction = getBuiltinAction((MyDialogWrapper)dialogWrapper);
       if (myText != null) builtinAction.putValue(Action.NAME, myText);
@@ -287,12 +303,14 @@
   }
 
   public static class OkActionDescriptor extends BuiltinAction {
+    @Override
     protected Action getBuiltinAction(MyDialogWrapper dialogWrapper) {
       return dialogWrapper.getOKAction();
     }
   }
 
   public static class CancelActionDescriptor extends BuiltinAction {
+    @Override
     protected Action getBuiltinAction(MyDialogWrapper dialogWrapper) {
       return dialogWrapper.getCancelAction();
     }
@@ -318,19 +336,25 @@
       return myHelpId;
     }
 
+    @Override
     public void init() { super.init(); }
+    @Override
     @NotNull
     public Action getOKAction() { return super.getOKAction(); } // Make it public
+    @Override
     @NotNull
     public Action getCancelAction() { return super.getCancelAction(); } // Make it public
 
+    @Override
     protected JComponent createCenterPanel() { return myCenterPanel; }
 
+    @Override
     public void dispose() {
       myPreferedFocusComponent = null;
       super.dispose();
     }
 
+    @Override
     public JComponent getPreferredFocusedComponent() {
       if (myPreferedFocusComponent != null) return myPreferedFocusComponent;
       FocusTraversalPolicy focusTraversalPolicy = null;
@@ -346,10 +370,12 @@
       return (JComponent)component;
     }
 
+    @Override
     protected String getDimensionServiceKey() {
       return myDimensionServiceKey;
     }
 
+    @Override
     protected JButton createJButtonForAction(Action action) {
       JButton button = super.createJButtonForAction(action);
       Object value = action.getValue(REQUEST_FOCUS_ENABLED);
@@ -357,6 +383,7 @@
       return button;
     }
 
+    @Override
     public void doCancelAction() {
       if (!getCancelAction().isEnabled()) return;
       if (myCancelOperation != null) {
@@ -367,6 +394,7 @@
       }
     }
 
+    @Override
     protected void doOKAction() {
       if (myOkOperation != null) {
         myOkOperation.run();
@@ -376,6 +404,7 @@
       }
     }
 
+    @Override
     protected void doHelpAction() {
       if (myHelpId == null) {
         super.doHelpAction();
@@ -385,6 +414,7 @@
       HelpManager.getInstance().invokeHelp(myHelpId);
     }
 
+    @Override
     @NotNull
     protected Action[] createActions() {
       if (myActions == null) return super.createActions();
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/FixedComboBoxEditor.java b/platform/platform-api/src/com/intellij/openapi/ui/FixedComboBoxEditor.java
index e4bc609..25c52c7 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/FixedComboBoxEditor.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/FixedComboBoxEditor.java
@@ -135,8 +135,6 @@
   }
 
   private class MacComboBoxTextField extends JTextField implements DocumentListener, FocusListener {
-    private boolean myRepaintingParent;
-
     private MacComboBoxTextField() {
       setBorder(isEnabled() ? EDITOR_BORDER : DISABLED_EDITOR_BORDER);
       //setFont(UIUtil.getListFont());
@@ -174,7 +172,8 @@
 
     @Override
     public boolean hasFocus() {
-      if (myRepaintingParent) {
+      final Container parent = getParent();
+      if (parent instanceof ComboBox && ((ComboBox)parent).myPaintingNow) {
         return false; // to disable focus painting around combobox button
       }
       return super.hasFocus();
@@ -191,14 +190,7 @@
       if (parent instanceof JComponent && Boolean.TRUE == ((JComponent)parent).getClientProperty("JComboBox.isTableCellEditor")) return;
       final Container grandParent = parent.getParent();
       if (grandParent != null) {
-        myRepaintingParent = true;
         grandParent.repaint();
-        SwingUtilities.invokeLater(new Runnable() {
-          @Override
-          public void run() {
-            myRepaintingParent = false;
-          }
-        });
       }
     }
 
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/MessageBuilder.java b/platform/platform-api/src/com/intellij/openapi/ui/MessageBuilder.java
deleted file mode 100644
index 89c1cb5..0000000
--- a/platform/platform-api/src/com/intellij/openapi/ui/MessageBuilder.java
+++ /dev/null
@@ -1,90 +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.openapi.ui;
-
-import com.intellij.openapi.project.Project;
-import com.intellij.openapi.wm.WindowManager;
-import com.intellij.ui.mac.MacMessages;
-import com.intellij.util.ObjectUtils;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import javax.swing.*;
-
-public final class MessageBuilder {
-  private final String myMessage;
-  private final String myTitle;
-
-  private String myYesText;
-  private String myNoText;
-
-  private Project myProject;
-  private Icon myIcon;
-  private DialogWrapper.DoNotAskOption myDoNotAskOption;
-
-  private MessageBuilder(@NotNull String title, @NotNull String message) {
-    myTitle = title;
-    myMessage = message;
-  }
-
-  public static MessageBuilder yesNo(@NotNull String title, @NotNull String message) {
-    return new MessageBuilder(title, message).icon(Messages.getQuestionIcon());
-  }
-
-  public MessageBuilder project(@Nullable Project project) {
-    myProject = project;
-    return this;
-  }
-
-  /**
-   * @see {@link com.intellij.openapi.ui.Messages#getInformationIcon()}
-   * @see {@link com.intellij.openapi.ui.Messages#getWarningIcon()}
-   * @see {@link com.intellij.openapi.ui.Messages#getErrorIcon()}
-   * @see {@link com.intellij.openapi.ui.Messages#getQuestionIcon()}
-   */
-  public MessageBuilder icon(@Nullable Icon icon) {
-    myIcon = icon;
-    return this;
-  }
-
-  public MessageBuilder doNotAsk(@NotNull DialogWrapper.DoNotAskOption doNotAskOption) {
-    myDoNotAskOption = doNotAskOption;
-    return this;
-  }
-
-  public MessageBuilder yesText(@NotNull String yesText) {
-    myYesText = yesText;
-    return this;
-  }
-
-  public MessageBuilder noText(@NotNull String noText) {
-    myNoText = noText;
-    return this;
-  }
-
-  @Messages.YesNoResult
-  public int show() {
-    String yesText = ObjectUtils.chooseNotNull(myYesText, Messages.YES_BUTTON);
-    String noText = ObjectUtils.chooseNotNull(myNoText, Messages.NO_BUTTON);
-    if (Messages.canShowMacSheetPanel()) {
-      return MacMessages.getInstance().showYesNoDialog(myTitle, myMessage, yesText, noText, WindowManager.getInstance().suggestParentWindow(myProject), myDoNotAskOption);
-    }
-    else {
-      //noinspection MagicConstant
-      return Messages.showDialog(myProject, myMessage, myTitle, new String[]{yesText, noText}, 0, myIcon, myDoNotAskOption);
-    }
-  }
-}
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/MessageDialogBuilder.java b/platform/platform-api/src/com/intellij/openapi/ui/MessageDialogBuilder.java
new file mode 100644
index 0000000..56520d4
--- /dev/null
+++ b/platform/platform-api/src/com/intellij/openapi/ui/MessageDialogBuilder.java
@@ -0,0 +1,138 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.ui;
+
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.wm.WindowManager;
+import com.intellij.ui.mac.MacMessages;
+import com.intellij.util.ObjectUtils;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import javax.swing.*;
+
+public abstract class MessageDialogBuilder<T extends MessageDialogBuilder> {
+  protected final String myMessage;
+  protected final String myTitle;
+
+  protected String myYesText;
+  protected String myNoText;
+
+  protected Project myProject;
+  protected Icon myIcon;
+  protected DialogWrapper.DoNotAskOption myDoNotAskOption;
+
+  private MessageDialogBuilder(@NotNull String title, @NotNull String message) {
+    myTitle = title;
+    myMessage = message;
+  }
+
+  public static YesNo yesNo(@NotNull String title, @NotNull String message) {
+    return new YesNo(title, message).icon(Messages.getQuestionIcon());
+  }
+
+  public static YesNoCancel yesNoCancel(@NotNull String title, @NotNull String message) {
+    return new YesNoCancel(title, message).icon(Messages.getQuestionIcon());
+  }
+
+  protected abstract T getThis();
+
+  public T project(@Nullable Project project) {
+    myProject = project;
+    return getThis();
+  }
+
+  /**
+   * @see {@link com.intellij.openapi.ui.Messages#getInformationIcon()}
+   * @see {@link com.intellij.openapi.ui.Messages#getWarningIcon()}
+   * @see {@link com.intellij.openapi.ui.Messages#getErrorIcon()}
+   * @see {@link com.intellij.openapi.ui.Messages#getQuestionIcon()}
+   */
+  public T icon(@Nullable Icon icon) {
+    myIcon = icon;
+    return getThis();
+  }
+
+  public T doNotAsk(@NotNull DialogWrapper.DoNotAskOption doNotAskOption) {
+    myDoNotAskOption = doNotAskOption;
+    return getThis();
+  }
+
+  public T yesText(@NotNull String yesText) {
+    myYesText = yesText;
+    return getThis();
+  }
+
+  public T noText(@NotNull String noText) {
+    myNoText = noText;
+    return getThis();
+  }
+
+  public static final class YesNo extends MessageDialogBuilder<YesNo> {
+    private YesNo(@NotNull String title, @NotNull String message) {
+      super(title, message);
+    }
+
+    @Override
+    protected YesNo getThis() {
+      return this;
+    }
+
+    @Messages.YesNoResult
+    public int show() {
+      String yesText = ObjectUtils.chooseNotNull(myYesText, Messages.YES_BUTTON);
+      String noText = ObjectUtils.chooseNotNull(myNoText, Messages.NO_BUTTON);
+      if (Messages.canShowMacSheetPanel() && !Messages.isApplicationInUnitTestOrHeadless()) {
+        return MacMessages.getInstance().showYesNoDialog(myTitle, myMessage, yesText, noText, WindowManager.getInstance().suggestParentWindow(myProject), myDoNotAskOption);
+      }
+      else {
+        return Messages.showDialog(myProject, myMessage, myTitle, new String[]{yesText, noText}, 0, myIcon, myDoNotAskOption) == 0 ? Messages.YES : Messages.NO;
+      }
+    }
+  }
+
+  public static final class YesNoCancel extends MessageDialogBuilder<YesNoCancel> {
+    private String myCancelText;
+
+    private YesNoCancel(@NotNull String title, @NotNull String message) {
+      super(title, message);
+    }
+
+    public YesNoCancel cancelText(@NotNull String cancelText) {
+      myCancelText = cancelText;
+      return getThis();
+    }
+
+    @Override
+    protected YesNoCancel getThis() {
+      return this;
+    }
+
+    @Messages.YesNoCancelResult
+    public int show() {
+      String yesText = ObjectUtils.chooseNotNull(myYesText, Messages.YES_BUTTON);
+      String noText = ObjectUtils.chooseNotNull(myNoText, Messages.NO_BUTTON);
+      String cancelText = ObjectUtils.chooseNotNull(myCancelText, Messages.CANCEL_BUTTON);
+      if (Messages.canShowMacSheetPanel() && !Messages.isApplicationInUnitTestOrHeadless()) {
+        return MacMessages.getInstance().showYesNoCancelDialog(myTitle, myMessage, yesText, noText, cancelText, WindowManager.getInstance().suggestParentWindow(myProject), myDoNotAskOption);
+      }
+      else {
+        int buttonNumber = Messages.showDialog(myProject, myMessage, myTitle, new String[]{yesText, noText, cancelText}, 0, myIcon, myDoNotAskOption);
+        return buttonNumber == 0 ? Messages.YES : buttonNumber == 1 ? Messages.NO : Messages.CANCEL;
+      }
+    }
+  }
+}
diff --git a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java
index fb21fe2..e95efbc 100644
--- a/platform/platform-api/src/com/intellij/openapi/ui/Messages.java
+++ b/platform/platform-api/src/com/intellij/openapi/ui/Messages.java
@@ -201,7 +201,7 @@
     return dialog.getExitCode();
   }
 
-  private static boolean isApplicationInUnitTestOrHeadless(){
+  static boolean isApplicationInUnitTestOrHeadless(){
     final Application application = ApplicationManager.getApplication();
     return application != null && (application.isUnitTestMode() || application.isHeadlessEnvironment());
   }
diff --git a/platform/platform-api/src/com/intellij/ui/SearchTextField.java b/platform/platform-api/src/com/intellij/ui/SearchTextField.java
index 0f87f2c..738cc7e 100644
--- a/platform/platform-api/src/com/intellij/ui/SearchTextField.java
+++ b/platform/platform-api/src/com/intellij/ui/SearchTextField.java
@@ -336,7 +336,7 @@
         // move item to top of the list
         myFullList.remove(index);
       }
-      else if (myFullList.size() >= myHistorySize) {
+      else if (myFullList.size() >= myHistorySize && myFullList.size() > 0) {
         // trim list
         myFullList.remove(myFullList.size() - 1);
       }
diff --git a/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java b/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java
index 7e0d6cd..25bd8ba 100644
--- a/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java
+++ b/platform/platform-api/src/com/intellij/ui/SimpleColoredComponent.java
@@ -632,7 +632,7 @@
       final String fragment = myFragments.get(i);
       final int fragmentWidth = isOracleRetina ? GraphicsUtil.stringWidth(fragment, font) : metrics.stringWidth(fragment);
 
-      final Color bgColor = attributes.getBgColor();
+      final Color bgColor = attributes.isSearchMatch() ? null : attributes.getBgColor();
       if ((attributes.isOpaque() || isOpaque()) && bgColor != null) {
         g.setColor(bgColor);
         g.fillRect(offset, 0, fragmentWidth, getHeight());
diff --git a/platform/platform-api/src/com/intellij/ui/TextFieldWithHistory.java b/platform/platform-api/src/com/intellij/ui/TextFieldWithHistory.java
index 18fe616..94ce40c 100644
--- a/platform/platform-api/src/com/intellij/ui/TextFieldWithHistory.java
+++ b/platform/platform-api/src/com/intellij/ui/TextFieldWithHistory.java
@@ -16,7 +16,7 @@
 package com.intellij.ui;
 
 import com.intellij.openapi.fileChooser.FileTextField;
-import com.intellij.openapi.ui.ComboBoxWithWidePopup;
+import com.intellij.openapi.ui.ComboBox;
 
 import javax.swing.*;
 import javax.swing.event.DocumentListener;
@@ -25,7 +25,7 @@
 import java.util.ArrayList;
 import java.util.List;
 
-public class TextFieldWithHistory extends ComboBoxWithWidePopup {
+public class TextFieldWithHistory extends ComboBox {
   private int myHistorySize = 5;
   private final MyModel myModel;
 
diff --git a/platform/platform-api/src/com/intellij/ui/components/JBCheckBox.java b/platform/platform-api/src/com/intellij/ui/components/JBCheckBox.java
index a9e0e05..e89b893 100644
--- a/platform/platform-api/src/com/intellij/ui/components/JBCheckBox.java
+++ b/platform/platform-api/src/com/intellij/ui/components/JBCheckBox.java
@@ -1,6 +1,7 @@
 package com.intellij.ui.components;
 
 import com.intellij.ui.AnchorableComponent;
+import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -65,6 +66,9 @@
    * @return true in case of success and false otherwise
    */
   public boolean setTextIcon(@NotNull Icon icon) {
+    if (UIUtil.isUnderDarcula()) {
+      return false;
+    }
     ButtonUI ui = getUI();
     if (ui instanceof BasicRadioButtonUI) {
       Icon defaultIcon = ((BasicRadioButtonUI) ui).getDefaultIcon();
diff --git a/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java b/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java
index 7ee0ab9..ee0ee8a 100644
--- a/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java
+++ b/platform/platform-api/src/com/intellij/ui/components/OnOffButton.java
@@ -17,7 +17,6 @@
 
 import com.intellij.ui.Gray;
 import com.intellij.ui.JBColor;
-import com.intellij.util.ui.GraphicsUtil;
 import com.intellij.util.ui.UIUtil;
 
 import javax.swing.*;
@@ -67,6 +66,8 @@
 
     @SuppressWarnings({"MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
     public static ComponentUI createUI(JComponent c) {
+      c.setOpaque(false);
+      c.setAlignmentY(0.5f);
       return new OnOffButtonUI((OnOffButton)c);
     }
 
@@ -92,31 +93,33 @@
         h--;
       }
       Graphics2D g = ((Graphics2D)gr);
-      GraphicsUtil.setupAAPainting(g);
-      g.translate(1,1);
+      g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+      int xOff = (myButton.getWidth() - w) / 2;
+      int yOff = (myButton.getHeight() - h) / 2;
+      g.translate(xOff, yOff);
       if (button.isSelected()) {
-        g.setColor(new JBColor(new Color(57, 113, 238), new Color(13, 41, 62)));
-        g.fillRoundRect(0, 0, w, h, h, h);
-        g.setColor(UIUtil.getBorderColor());
-        g.drawRoundRect(0, 0, w, h, h, h);
-        g.setColor(new JBColor(Gray._220, Gray._128));
-        g.fillOval(w - h + 1, 1, h - 1, h - 1);
+        g.setColor(new JBColor(new Color(74, 146, 73), new Color(77, 105, 76)));
+        g.fillRoundRect(0, 0, w, h, 5, 5);
+        g.setColor(new JBColor(Gray._192, Gray._80));
+        g.drawRoundRect(0, 0, w, h, 5, 5);
+        g.setColor(new JBColor(Gray._200, Gray._100));
+        g.fillRoundRect(w - h, 1, h, h-1, 3, 3);
         g.setColor(UIUtil.getListForeground(true));
         g.drawString(button.getOnText(), h/2, h - 4);
       } else {
         g.setColor(UIUtil.getPanelBackground());
-        g.fillRoundRect(0, 0, w, h, h, h);
-        g.setColor(UIUtil.getBorderColor());
-        g.drawRoundRect(0, 0, w, h, h, h);
+        g.fillRoundRect(0, 0, w, h, 5, 5);
+        g.setColor(new JBColor(Gray._192, Gray._100));
+        g.drawRoundRect(0, 0, w, h, 5, 5);
         g.setColor(UIUtil.getLabelDisabledForeground());
         g.drawString(button.getOffText(), h + 4 , h - 4);
         g.setColor(UIUtil.getBorderColor());
-        g.setPaint(new GradientPaint(h,0, Gray._178, 0,h, Gray._240));
-        g.fillOval(0, 0, h, h);
-        g.setColor(UIUtil.getBorderColor());
-        g.drawOval(0, 0, h, h);
+        g.setPaint(new GradientPaint(h, 0, new JBColor(Gray._158, Gray._100), 0, h, new JBColor(Gray._210, Gray._100)));
+        g.fillRoundRect(0, 0, h, h, 3, 3);
+//        g.setColor(UIUtil.getBorderColor());
+//        g.drawOval(0, 0, h, h);
       }
-      g.translate(-1, -1);
+      g.translate(-xOff, -yOff);
     }
 
     @Override
diff --git a/platform/platform-api/src/com/intellij/ui/tabs/JBTabsPresentation.java b/platform/platform-api/src/com/intellij/ui/tabs/JBTabsPresentation.java
index e354fb6..352e4b3 100644
--- a/platform/platform-api/src/com/intellij/ui/tabs/JBTabsPresentation.java
+++ b/platform/platform-api/src/com/intellij/ui/tabs/JBTabsPresentation.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -32,6 +32,8 @@
 
   JBTabsPresentation setPaintFocus(boolean paintFocus);
 
+  JBTabsPresentation setAlwaysPaintSelectedTab(final boolean paintSelected);
+
   JBTabsPresentation setStealthTabMode(boolean stealthTabMode);
 
   JBTabsPresentation setSideComponentVertical(boolean vertical);
diff --git a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java
index 2908b4f..ba9e46e 100644
--- a/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java
+++ b/platform/platform-api/src/com/intellij/ui/tabs/impl/JBTabsImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -169,6 +169,7 @@
   private SelectionChangeHandler mySelectionChangeHandler;
 
   private Runnable myDeferredFocusRequest;
+  private boolean myAlwaysPaintSelectedTab;
 
   public JBTabsImpl(@NotNull Project project) {
     this(project, project);
@@ -1674,7 +1675,7 @@
     final int alpha;
     int paintTopY = shapeInfo.labelTopY;
     int paintBottomY = shapeInfo.labelBottomY;
-    final boolean paintFocused = myPaintFocus && (myFocused || myActivePopup != null);
+    final boolean paintFocused = myPaintFocus && (myFocused || myActivePopup != null || myAlwaysPaintSelectedTab);
     Color bgPreFill = null;
     if (paintFocused) {
       final Color bgColor = getActiveTabColor(getActiveTabFillIn());
@@ -2758,6 +2759,12 @@
     return this;
   }
 
+  @Override
+  public JBTabsPresentation setAlwaysPaintSelectedTab(final boolean paintSelected) {
+    myAlwaysPaintSelectedTab = paintSelected;
+    return this;
+  }
+
   private abstract static class BaseNavigationAction extends AnAction {
 
     private final ShadowAction myShadow;
diff --git a/platform/platform-api/src/com/intellij/ui/treeStructure/WeightBasedComparator.java b/platform/platform-api/src/com/intellij/ui/treeStructure/WeightBasedComparator.java
index c7286df..44e0501 100644
--- a/platform/platform-api/src/com/intellij/ui/treeStructure/WeightBasedComparator.java
+++ b/platform/platform-api/src/com/intellij/ui/treeStructure/WeightBasedComparator.java
@@ -42,6 +42,7 @@
     myCompareToString = compareToString;
   }
 
+  @Override
   public int compare(NodeDescriptor o1, NodeDescriptor o2) {
     final int w1 = getWeight(o1);
     final int w2 = getWeight(o2);
@@ -62,6 +63,6 @@
   }
 
   protected static int compareToString(final NodeDescriptor first, final NodeDescriptor second) {
-    return StringUtil.compare(first.toString(), second.toString(), true);
+    return StringUtil.naturalCompare(first.toString(), second.toString());
   }
 }
diff --git a/platform/platform-api/src/com/intellij/util/Url.java b/platform/platform-api/src/com/intellij/util/Url.java
new file mode 100644
index 0000000..7908968
--- /dev/null
+++ b/platform/platform-api/src/com/intellij/util/Url.java
@@ -0,0 +1,33 @@
+package com.intellij.util;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+// We don't use Java URI due to problem — http://cns-etuat-2.localnet.englishtown.com/school/e12/#school/45383/201/221/382?c=countrycode=cc|culturecode=en-us|partnercode=mkge
+// it is illegal URI (fragment before query), but we must support such URI
+// Semicolon as parameters separator is supported (WEB-6671)
+public interface Url {
+  @NotNull
+  String getPath();
+
+  boolean isInLocalFileSystem();
+
+  String toDecodedForm();
+
+  @NotNull
+  String toExternalForm();
+
+  @Nullable
+  String getScheme();
+
+  @Nullable
+  String getAuthority();
+
+  @Nullable
+  String getParameters();
+
+  boolean equalsIgnoreParameters(@Nullable Url url);
+
+  @NotNull
+  Url trimParameters();
+}
diff --git a/platform/platform-api/src/com/intellij/util/net/NetUtils.java b/platform/platform-api/src/com/intellij/util/net/NetUtils.java
index 2f6270c..ae18326 100644
--- a/platform/platform-api/src/com/intellij/util/net/NetUtils.java
+++ b/platform/platform-api/src/com/intellij/util/net/NetUtils.java
@@ -129,6 +129,19 @@
     }
   }
 
+  public static int tryToFindAvailableSocketPort(int defaultPort) {
+    try {
+      return findAvailableSocketPort();
+    }
+    catch (IOException ignored) {
+      return defaultPort;
+    }
+  }
+
+  public static int tryToFindAvailableSocketPort() {
+    return tryToFindAvailableSocketPort(-1);
+  }
+
   public static int[] findAvailableSocketPorts(int capacity) throws IOException {
     final int[] ports = new int[capacity];
     final ServerSocket[] sockets = new ServerSocket[capacity];
diff --git a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java
index c0e0362..03e47c5 100644
--- a/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java
+++ b/platform/platform-impl/src/com/intellij/execution/impl/EditorHyperlinkSupport.java
@@ -330,7 +330,7 @@
         break;
       }
     }
-    int newIndex = i;
+    int newIndex = i > 0 ? i % ranges.size() : 0;
     while (newIndex < ranges.size() && newIndex >= 0) {
       newIndex = (newIndex + delta + ranges.size()) % ranges.size();
       final RangeHighlighter next = ranges.get(newIndex);
diff --git a/platform/platform-impl/src/com/intellij/execution/process/ConsoleHistoryModel.java b/platform/platform-impl/src/com/intellij/execution/process/ConsoleHistoryModel.java
index 7c512b1..a054c81 100644
--- a/platform/platform-impl/src/com/intellij/execution/process/ConsoleHistoryModel.java
+++ b/platform/platform-impl/src/com/intellij/execution/process/ConsoleHistoryModel.java
@@ -19,17 +19,19 @@
   private volatile long myModificationTracker;
 
 
-  public void addToHistory(final String statement) {
-    final int maxHistorySize = getMaxHistorySize();
+  public void addToHistory(String statement) {
+    if (StringUtil.isEmptyOrSpaces(statement)) return;
+
+    int maxHistorySize = getMaxHistorySize();
     synchronized (myHistory) {
+      myModificationTracker++;
       myHistoryCursor = -1;
-      if (!StringUtil.isEmptyOrSpaces(statement)) {
-        removeFromHistory(statement);
-        if (myHistory.size() >= maxHistorySize) {
-          myHistory.removeLast();
-        }
-        myHistory.addFirst(statement);
+
+      myHistory.remove(statement);
+      if (myHistory.size() >= maxHistorySize) {
+        myHistory.removeLast();
       }
+      myHistory.addFirst(statement);
     }
   }
 
@@ -40,6 +42,7 @@
   public void removeFromHistory(final String statement) {
     synchronized (myHistory) {
       myModificationTracker++;
+      myHistoryCursor = -1;
 
       myHistory.remove(statement);
     }
diff --git a/platform/platform-impl/src/com/intellij/execution/process/KillableColoredProcessHandler.java b/platform/platform-impl/src/com/intellij/execution/process/KillableColoredProcessHandler.java
index 51e30cc..b62778a 100644
--- a/platform/platform-impl/src/com/intellij/execution/process/KillableColoredProcessHandler.java
+++ b/platform/platform-impl/src/com/intellij/execution/process/KillableColoredProcessHandler.java
@@ -18,9 +18,11 @@
 import com.intellij.execution.ExecutionException;
 import com.intellij.execution.KillableProcess;
 import com.intellij.execution.configurations.GeneralCommandLine;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.SystemInfo;
 import org.jetbrains.annotations.NotNull;
 
+import java.io.IOException;
 import java.nio.charset.Charset;
 
 /**
@@ -32,6 +34,8 @@
  *         P.S: probably OSProcessHandler is better place for this feature but it can affect other run configurations and should be tested
  */
 public class KillableColoredProcessHandler extends ColoredProcessHandler implements KillableProcess {
+  private static final Logger LOG = Logger.getInstance(KillableColoredProcessHandler .class);
+
   private boolean myShouldKillProcessSoftly = true;
 
   public KillableColoredProcessHandler(GeneralCommandLine commandLine) throws ExecutionException {
@@ -46,6 +50,10 @@
     super(process, commandLine);
   }
 
+  /**
+   * Sets whether the process will be terminated gracefully.
+   * @param shouldKillProcessSoftly true, if graceful process termination should be attempted first (i.e. soft kill)
+   */
   public void setShouldKillProcessSoftly(boolean shouldKillProcessSoftly) {
     myShouldKillProcessSoftly = shouldKillProcessSoftly;
   }
@@ -56,30 +64,72 @@
    * @return
    */
   private boolean canKillProcessSoftly() {
-    // soft-kill works on Unix systems
-    return SystemInfo.isUnix && processCanBeKilledByOS(getProcess());
+    if (processCanBeKilledByOS(myProcess)) {
+      if (SystemInfo.isWindows) {
+        // runnerw.exe can send Ctrl+C events to a wrapped process
+        return myProcess instanceof RunnerWinProcess;
+      }
+      else if (SystemInfo.isUnix) {
+        // 'kill -SIGINT <pid>' will be executed
+        return true;
+      }
+    }
+    return false;
+  }
+
+  @Override
+  protected void destroyProcessImpl() {
+    // call super.closeStreams() after process termination, because
+    // otherwise process's output stream can also be closed for no reason
+    try {
+      myProcess.getOutputStream().flush();
+    }
+    catch (IOException e) {
+      LOG.warn(e);
+    }
+    finally {
+      doDestroyProcess();
+    }
+  }
+
+  @Override
+  protected void notifyProcessTerminated(int exitCode) {
+    try {
+      super.closeStreams();
+    }
+    finally {
+      super.notifyProcessTerminated(exitCode);
+    }
   }
 
   @Override
   protected void doDestroyProcess() {
+    boolean gracefulTerminationAttempted = false;
     if (canKillProcessSoftly() && shouldKillProcessSoftly()) {
-      // Unix: [soft-kill] at first send INT signal:
-      final Process process = getProcess();
-      if (UnixProcessManager.sendSigIntToProcessTree(process)) {
-        return;
+      gracefulTerminationAttempted = destroyProcessGracefully();
+    }
+    if (!gracefulTerminationAttempted) {
+      // execute default process destroy
+      super.doDestroyProcess();
+    }
+  }
+
+  protected boolean destroyProcessGracefully() {
+    if (SystemInfo.isWindows) {
+      if (myProcess instanceof RunnerWinProcess) {
+        RunnerWinProcess runnerWinProcess = (RunnerWinProcess) myProcess;
+        runnerWinProcess.destroyGracefully(true);
+        return true;
       }
     }
-
-    // if soft kill isn't supported - use default implementation
-    super.doDestroyProcess();
-    // else IDE will suggest 'terminate dialog'
-
+    else if (SystemInfo.isUnix) {
+      return UnixProcessManager.sendSigIntToProcessTree(myProcess);
+    }
+    return false;
   }
 
   /**
-   * This method should be overridden by children if the process shouldn't be killed softly (e.g. by kill -2)
-   *
-   * @return
+   * @return true, if graceful process termination should be attempted first
    */
   protected boolean shouldKillProcessSoftly() {
     return myShouldKillProcessSoftly;
@@ -92,7 +142,22 @@
 
   @Override
   public void killProcess() {
-    // kill -9
+    // execute 'kill -SIGKILL <pid>' on Unix
     killProcessTree(getProcess());
   }
+
+  @NotNull
+  public static KillableColoredProcessHandler create(@NotNull GeneralCommandLine commandLine) throws ExecutionException {
+    final Process process;
+    if (SystemInfo.isWindows) {
+      process = RunnerWinProcess.create(commandLine);
+    }
+    else {
+      process = commandLine.createProcess();
+    }
+    return new KillableColoredProcessHandler(process,
+                                             commandLine.getCommandLineString(),
+                                             commandLine.getCharset());
+  }
+
 }
diff --git a/platform/platform-impl/src/com/intellij/execution/process/RunnerMediator.java b/platform/platform-impl/src/com/intellij/execution/process/RunnerMediator.java
index bc561c6..3fd8711 100644
--- a/platform/platform-impl/src/com/intellij/execution/process/RunnerMediator.java
+++ b/platform/platform-impl/src/com/intellij/execution/process/RunnerMediator.java
@@ -51,15 +51,11 @@
    */
   private static void sendCtrlEventThroughStream(@NotNull final Process process, final char event) {
     OutputStream os = process.getOutputStream();
+    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
     PrintWriter pw = new PrintWriter(os);
-    try {
-      pw.print(IAC);
-      pw.print(event);
-      pw.flush();
-    }
-    finally {
-      pw.close();
-    }
+    pw.print(IAC);
+    pw.print(event);
+    pw.flush();
   }
 
   /**
@@ -101,7 +97,7 @@
     }
   }
 
-  private static void injectRunnerCommand(@NotNull GeneralCommandLine commandLine) {
+  static void injectRunnerCommand(@NotNull GeneralCommandLine commandLine) {
     final String path = getRunnerPath();
     if (path != null) {
       commandLine.getParametersList().addAt(0, commandLine.getExePath());
@@ -121,7 +117,7 @@
    * Destroys process tree: in case of windows via imitating ctrl+c, in case of unix via sending sig_int to every process in tree.
    * @param process to kill with all sub-processes.
    */
-  private static boolean destroyProcess(@NotNull final Process process, final boolean softKill) {
+  static boolean destroyProcess(@NotNull final Process process, final boolean softKill) {
     try {
       if (SystemInfo.isWindows) {
         sendCtrlEventThroughStream(process, softKill ? C : BRK);
diff --git a/platform/platform-impl/src/com/intellij/execution/process/RunnerWinProcess.java b/platform/platform-impl/src/com/intellij/execution/process/RunnerWinProcess.java
new file mode 100644
index 0000000..e2dd827
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/execution/process/RunnerWinProcess.java
@@ -0,0 +1,86 @@
+/*
+ * 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.execution.process;
+
+import com.intellij.execution.ExecutionException;
+import com.intellij.execution.configurations.GeneralCommandLine;
+import com.intellij.openapi.util.SystemInfo;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.InputStream;
+import java.io.OutputStream;
+
+public class RunnerWinProcess extends Process {
+
+  private final Process myOriginalProcess;
+
+  private RunnerWinProcess(@NotNull Process originalProcess) {
+    myOriginalProcess = originalProcess;
+  }
+
+  @Override
+  public OutputStream getOutputStream() {
+    return myOriginalProcess.getOutputStream();
+  }
+
+  @Override
+  public InputStream getInputStream() {
+    return myOriginalProcess.getInputStream();
+  }
+
+  @Override
+  public InputStream getErrorStream() {
+    return myOriginalProcess.getErrorStream();
+  }
+
+  @Override
+  public int waitFor() throws InterruptedException {
+    return myOriginalProcess.waitFor();
+  }
+
+  @Override
+  public int exitValue() {
+    return myOriginalProcess.exitValue();
+  }
+
+  @Override
+  public void destroy() {
+    myOriginalProcess.destroy();
+  }
+
+  public Process getOriginalProcess() {
+    return myOriginalProcess;
+  }
+
+  /**
+   * Sends Ctrl+C or Ctrl+Break event to the process.
+   * @param softKill if true, Ctrl+C event will be sent (otherwise, Ctrl+Break)
+   */
+  public void destroyGracefully(boolean softKill) {
+    RunnerMediator.destroyProcess(this, softKill);
+  }
+
+  @NotNull
+  public static RunnerWinProcess create(@NotNull GeneralCommandLine commandLine) throws ExecutionException {
+    if (!SystemInfo.isWindows) {
+      throw new RuntimeException(RunnerWinProcess.class.getSimpleName() + " works on Windows only!");
+    }
+    RunnerMediator.injectRunnerCommand(commandLine);
+    Process process = commandLine.createProcess();
+    return new RunnerWinProcess(process);
+  }
+
+}
diff --git a/platform/platform-impl/src/com/intellij/execution/process/impl/OSProcessManagerImpl.java b/platform/platform-impl/src/com/intellij/execution/process/impl/OSProcessManagerImpl.java
index cf6b766..e1848c7 100644
--- a/platform/platform-impl/src/com/intellij/execution/process/impl/OSProcessManagerImpl.java
+++ b/platform/platform-impl/src/com/intellij/execution/process/impl/OSProcessManagerImpl.java
@@ -16,6 +16,7 @@
 package com.intellij.execution.process.impl;
 
 import com.intellij.execution.process.OSProcessManager;
+import com.intellij.execution.process.RunnerWinProcess;
 import com.intellij.execution.process.UnixProcessManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.SystemInfo;
@@ -42,12 +43,12 @@
   public boolean killProcessTree(@NotNull Process process) {
     if (SystemInfo.isWindows) {
       try {
-        new WinProcess(process).killRecursively();
+        WinProcess winProcess = createWinProcess(process);
+        winProcess.killRecursively();
         return true;
       }
       catch (Throwable e) {
-        LOG.info("Cannot kill process tree");
-        LOG.info(e);
+        LOG.info("Cannot kill process tree", e);
       }
     }
     else if (SystemInfo.isUnix) {
@@ -56,6 +57,15 @@
     return false;
   }
 
+  @NotNull
+  private static WinProcess createWinProcess(@NotNull Process process) {
+    if (process instanceof RunnerWinProcess) {
+      RunnerWinProcess runnerWinProcess = (RunnerWinProcess) process;
+      return new WinProcess(runnerWinProcess.getOriginalProcess());
+    }
+    return new WinProcess(process);
+  }
+
   @Override
   public List<String> getCommandLinesOfRunningProcesses() {
     try {
diff --git a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java
index d7caa06..f379dd0 100644
--- a/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java
+++ b/platform/platform-impl/src/com/intellij/ide/RecentProjectsManagerBase.java
@@ -279,6 +279,7 @@
     }
 
     public void projectClosed(final Project project) {
+      if (ApplicationManager.getApplication().isHeadlessEnvironment()) return;
       Project[] openProjects = ProjectManager.getInstance().getOpenProjects();
       if (openProjects.length > 0) {
         String path = getProjectPath(openProjects[openProjects.length - 1]);
diff --git a/platform/platform-impl/src/com/intellij/ide/XmlRpcServerImpl.java b/platform/platform-impl/src/com/intellij/ide/XmlRpcServerImpl.java
index 183f722..b5a5b40 100644
--- a/platform/platform-impl/src/com/intellij/ide/XmlRpcServerImpl.java
+++ b/platform/platform-impl/src/com/intellij/ide/XmlRpcServerImpl.java
@@ -85,7 +85,7 @@
 
   @Override
   public boolean process(@NotNull String path, @NotNull FullHttpRequest request, @NotNull ChannelHandlerContext context, @Nullable Map<String, Object> handlers) throws IOException {
-    if (!(path.isEmpty() || (path.length() == 1 && path.charAt(0) == '/') || path.equalsIgnoreCase("/RPC2"))) {
+    if (!(path.isEmpty() || (path.length() == 1 && path.charAt(0) == '/') || path.equalsIgnoreCase("/rpc2"))) {
       return false;
     }
 
@@ -136,16 +136,12 @@
       return handler;
     }
 
-    IllegalStateException exception;
     if (dot > -1) {
-      exception = new IllegalStateException("RPC handler object \"" + handlerName + "\" not found");
+      throw new IllegalStateException("RPC handler object \"" + handlerName + "\" not found");
     }
     else {
-      exception = new IllegalStateException("RPC handler object not found for \"" + methodName);
+      throw new IllegalStateException("RPC handler object not found for \"" + methodName);
     }
-
-    LOG.error(exception);
-    throw exception;
   }
 
   private static Object invokeHandler(@NotNull Object handler, XmlRpcServerRequest request) throws Throwable {
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 45f0da6..57b707b 100644
--- a/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java
+++ b/platform/platform-impl/src/com/intellij/ide/actions/Switcher.java
@@ -490,9 +490,9 @@
       this.add(toolWindows, BorderLayout.WEST);
       if (filesModel.size() > 0) {
         files.setAlignmentY(1f);
-        if (files.getModel().getSize() > 30) {
+        if (files.getModel().getSize() > 20) {
           final JScrollPane pane = ScrollPaneFactory.createScrollPane(files, true);
-          pane.setPreferredSize(new Dimension(files.getPreferredSize().width + 10, 30 * 20));
+          pane.setPreferredSize(new Dimension(files.getPreferredSize().width + 10, 20 * 20));
           pane.setHorizontalScrollBarPolicy(ScrollPaneConstants.HORIZONTAL_SCROLLBAR_NEVER);
           this.add(pane, BorderLayout.EAST);
         } else {
@@ -556,16 +556,9 @@
         }.registerCustomShortcutSet(CustomShortcutSet.fromString("ESCAPE"), this, myPopup);
       }
 
-      Component comp = null;
-      final EditorWindow result = FileEditorManagerEx.getInstanceEx(project).getActiveWindow().getResult();
-      if (result != null) {
-        comp = result.getOwner();
-      }
-      if (comp == null) {
-        comp = ideFrame.getContentPane();
-      }
+      final Window window = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusedWindow();
       myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD, myPopup);
-      myPopup.showInCenterOf(comp);
+      myPopup.showInCenterOf(window);
     }
 
 
@@ -668,48 +661,67 @@
     }
 
     private void closeTabOrToolWindow() {
-      final Object value = getSelectedList().getSelectedValue();
-      if (value instanceof FileInfo) {
-        final FileInfo info = (FileInfo)value;
-        final VirtualFile virtualFile = info.first;
-        final FileEditorManagerImpl editorManager = ((FileEditorManagerImpl)FileEditorManager.getInstance(project));
-        final JList jList = getSelectedList();
-        final EditorWindow wnd = findAppropriateWindow(info);
-        if (wnd == null) {
-          editorManager.closeFile(virtualFile, false, false);
-        } else {
-          editorManager.closeFile(virtualFile, wnd, false);
-        }
-        final int selectedIndex = jList.getSelectedIndex();
-        final IdeFocusManager focusManager = IdeFocusManager.getInstance(project);
-        myAlarm.addRequest(new Runnable() {
-          @Override
-          public void run() {
-            focusManager.requestFocus(SwitcherPanel.this, true);
+      final int[] selected = getSelectedList().getSelectedIndices();
+      Arrays.sort(selected);
+      int selectedIndex = 0;
+      for (int i = selected.length - 1; i>=0; i--) {
+        selectedIndex = selected[i];
+        Object value = getSelectedList().getModel().getElementAt(selectedIndex);
+        if (value instanceof FileInfo) {
+          final FileInfo info = (FileInfo)value;
+          final VirtualFile virtualFile = info.first;
+          final FileEditorManagerImpl editorManager = ((FileEditorManagerImpl)FileEditorManager.getInstance(project));
+          final JList jList = getSelectedList();
+          final EditorWindow wnd = findAppropriateWindow(info);
+          if (wnd == null) {
+            editorManager.closeFile(virtualFile, false, false);
           }
-        }, 300);
-        if (jList.getModel().getSize() == 1) {
-          goLeft();
-          removeElementAt(jList, selectedIndex);
-          this.remove(jList);
-          this.remove(separator);
-          final Dimension size = toolWindows.getSize();
-          myPopup.setSize(new Dimension(size.width, myPopup.getSize().height));
-        } else {
-          goForward();
-          removeElementAt(jList, selectedIndex);
-          jList.setSize(jList.getPreferredSize());
+          else {
+            editorManager.closeFile(virtualFile, wnd, false);
+          }
+
+          final IdeFocusManager focusManager = IdeFocusManager.getInstance(project);
+          myAlarm.cancelAllRequests();
+          myAlarm.addRequest(new Runnable() {
+            @Override
+            public void run() {
+              focusManager.requestFocus(SwitcherPanel.this, true);
+            }
+          }, 300);
+          if (jList.getModel().getSize() == 1) {
+            goLeft();
+            removeElementAt(jList, selectedIndex);
+            this.remove(jList);
+            this.remove(separator);
+            final Dimension size = toolWindows.getSize();
+            myPopup.setSize(new Dimension(size.width, myPopup.getSize().height));
+          }
+          else {
+            removeElementAt(jList, selectedIndex);
+            jList.setSize(jList.getPreferredSize());
+          }
+          if (isPinnedMode()) {
+            EditorHistoryManager.getInstance(project).removeFile(virtualFile);
+          }
         }
-        pack();
-      } else if (value instanceof ToolWindow) {
-        final ToolWindow toolWindow = (ToolWindow)value;
-        if (twManager instanceof ToolWindowManagerImpl) {
-          ToolWindowManagerImpl manager = (ToolWindowManagerImpl)twManager;
-          manager.hideToolWindow(ids.get(toolWindow), false, false);
-        } else {
-          toolWindow.hide(null);
+        else if (value instanceof ToolWindow) {
+          final ToolWindow toolWindow = (ToolWindow)value;
+          if (twManager instanceof ToolWindowManagerImpl) {
+            ToolWindowManagerImpl manager = (ToolWindowManagerImpl)twManager;
+            manager.hideToolWindow(ids.get(toolWindow), false, false);
+          }
+          else {
+            toolWindow.hide(null);
+          }
         }
       }
+      pack();
+      myPopup.getContent().revalidate();
+      myPopup.getContent().repaint();
+      if (getSelectedList().getModel().getSize() > selectedIndex) {
+        getSelectedList().setSelectedIndex(selectedIndex);
+        getSelectedList().ensureIndexIsVisible(selectedIndex);
+      }
     }
 
     private static void removeElementAt(JList jList, int index) {
diff --git a/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java b/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java
index 6c8e9e8..565b78f 100644
--- a/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java
+++ b/platform/platform-impl/src/com/intellij/ide/actions/TogglePresentationModeAction.java
@@ -85,15 +85,18 @@
     }
 
     if (project != null) {
-      Window frame = IdeFrameImpl.getActiveFrame();
-      if (frame instanceof IdeFrameImpl) {
+      Window window = IdeFrameImpl.getActiveFrame();
+      if (window instanceof IdeFrameImpl) {
+        final IdeFrameImpl frame = (IdeFrameImpl)window;
         final PropertiesComponent propertiesComponent = PropertiesComponent.getInstance(project);
         if (settings.PRESENTATION_MODE) {
-          propertiesComponent.setValue("full.screen.before.presentation.mode", String.valueOf(((IdeFrameImpl)frame).isInFullScreen()));
-          ((IdeFrameImpl)frame).toggleFullScreen(true);
+          propertiesComponent.setValue("full.screen.before.presentation.mode", String.valueOf(frame.isInFullScreen()));
+          frame.toggleFullScreen(true);
         } else {
-          final String value = propertiesComponent.getValue("full.screen.before.presentation.mode");
-          ((IdeFrameImpl)frame).toggleFullScreen("true".equalsIgnoreCase(value));
+          if (frame.isInFullScreen()) {
+            final String value = propertiesComponent.getValue("full.screen.before.presentation.mode");
+            frame.toggleFullScreen("true".equalsIgnoreCase(value));
+          }
         }
       }
     }
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java b/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java
index 7d01ea2..bac148d 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/ActionInstallPlugin.java
@@ -51,6 +51,7 @@
     this.installed = installed;
   }
 
+  @Override
   public void update(AnActionEvent e) {
     Presentation presentation = e.getPresentation();
     IdeaPluginDescriptor[] selection = getPluginTable().getSelectedObjects();
@@ -81,6 +82,7 @@
     presentation.setEnabled(enabled);
   }
 
+  @Override
   public void actionPerformed(AnActionEvent e) {
     install();
   }
@@ -225,6 +227,7 @@
           message += "updated plugin" + (disabled.size() > 1 ? "s" : "");
         }
         else {
+          //noinspection SpellCheckingInspection
           message += "plugin dependenc" + (disabledDependants.size() > 1 ? "ies" : "y");
         }
         message += "?</body></html>";
diff --git a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java
index d36731d..6092139 100644
--- a/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java
+++ b/platform/platform-impl/src/com/intellij/ide/plugins/RepositoryContentHandler.java
@@ -53,7 +53,7 @@
 
   @NonNls private static final String DATE = "date";
   private PluginNode currentPlugin;
-  private String currentValue;
+  private final StringBuilder currentValue = new StringBuilder();
   private ArrayList<IdeaPluginDescriptor> plugins;
   private Stack<String> categoriesStack;
 
@@ -86,45 +86,47 @@
       currentPlugin.setVendorEmail(atts.getValue(EMAIL));
       currentPlugin.setVendorUrl(atts.getValue(URL));
     }
-    currentValue = "";
+    currentValue.setLength(0);
   }
 
   public void endElement(String namespaceURI, String localName, String qName) throws SAXException {
+    String currentValueString = currentValue.toString();
+    currentValue.setLength(0);
+
     if (qName.equals(ID)) {
-      currentPlugin.setId(currentValue);
+      currentPlugin.setId(currentValueString);
     }
     else if (qName.equals(NAME)) {
-      currentPlugin.setName(currentValue);
+      currentPlugin.setName(currentValueString);
     }
     else if (qName.equals(DESCRIPTION)) {
-      currentPlugin.setDescription(currentValue);
+      currentPlugin.setDescription(currentValueString);
     }
     else if (qName.equals(VERSION)) {
-      currentPlugin.setVersion(currentValue);
+      currentPlugin.setVersion(currentValueString);
     }
     else if (qName.equals(VENDOR)) {
-      currentPlugin.setVendor(currentValue);
+      currentPlugin.setVendor(currentValueString);
     }
     else if (qName.equals(DEPENDS)) {
-      currentPlugin.addDepends(PluginId.getId(currentValue));
+      currentPlugin.addDepends(PluginId.getId(currentValueString));
     }
     else if (qName.equals(CHNAGE_NOTES)) {
-      currentPlugin.setChangeNotes(currentValue);
+      currentPlugin.setChangeNotes(currentValueString);
     }
     else if (qName.equals(CATEGORY)) {
       categoriesStack.pop();
     }
     else if (qName.equals(RATING)) {
-      currentPlugin.setRating(currentValue);
+      currentPlugin.setRating(currentValueString);
     }
     else if (qName.equals(DOWNLOAD_URL)) {
-      currentPlugin.setDownloadUrl(currentValue);
+      currentPlugin.setDownloadUrl(currentValueString);
     }
-    currentValue = "";
   }
 
   public void characters(char[] ch, int start, int length) throws SAXException {
-    currentValue += new String(ch, start, length);
+    currentValue.append(ch, start, length);
   }
 
   public ArrayList<IdeaPluginDescriptor> getPluginsList() {
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/DaemonCodeAnalyzerOptionDescription.java b/platform/platform-impl/src/com/intellij/ide/ui/DaemonCodeAnalyzerOptionDescription.java
new file mode 100644
index 0000000..a1ce45d
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/ide/ui/DaemonCodeAnalyzerOptionDescription.java
@@ -0,0 +1,32 @@
+/*
+ * 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.ide.ui;
+
+import com.intellij.codeInsight.daemon.DaemonCodeAnalyzerSettings;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class DaemonCodeAnalyzerOptionDescription extends EditorOptionDescription {
+  public DaemonCodeAnalyzerOptionDescription(String fieldName, String option, String configurableId) {
+    super(fieldName, option, configurableId);
+  }
+
+  @Override
+  public Object getInstance() {
+    return DaemonCodeAnalyzerSettings.getInstance();
+  }
+}
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/EditorOptionDescription.java b/platform/platform-impl/src/com/intellij/ide/ui/EditorOptionDescription.java
new file mode 100644
index 0000000..e19564e
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/ide/ui/EditorOptionDescription.java
@@ -0,0 +1,51 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.ide.ui;
+
+import com.intellij.codeInsight.daemon.DaemonCodeAnalyzer;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.EditorFactory;
+import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.ex.EditorSettingsExternalizable;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.project.ProjectManager;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class EditorOptionDescription extends PublicFieldBasedOptionDescription {
+  public EditorOptionDescription(String fieldName, String option, String configurableId) {
+    super(option, configurableId, fieldName);
+  }
+
+  @Override
+  public Object getInstance() {
+    return EditorSettingsExternalizable.getInstance().getOptions();
+  }
+
+  @Override
+  protected void fireUpdated() {
+    Project[] projects = ProjectManager.getInstance().getOpenProjects();
+    for (Project project : projects) {
+      DaemonCodeAnalyzer.getInstance(project).settingsChanged();
+    }
+
+    Editor[] editors = EditorFactory.getInstance().getAllEditors();
+    for (Editor editor : editors) {
+      ((EditorEx)editor).reinitSettings();
+    }
+  }
+}
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/UISettingsOptionDescription.java b/platform/platform-impl/src/com/intellij/ide/ui/UISettingsOptionDescription.java
new file mode 100644
index 0000000..ab81fe5
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/ide/ui/UISettingsOptionDescription.java
@@ -0,0 +1,35 @@
+/*
+ * 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.ide.ui;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class UISettingsOptionDescription extends PublicFieldBasedOptionDescription {
+  public UISettingsOptionDescription(String fieldName, String option, String configurableId) {
+    super(option, configurableId, fieldName);
+  }
+
+  @Override
+  public Object getInstance() {
+    return UISettings.getInstance();
+  }
+
+  @Override
+  protected void fireUpdated() {
+    UISettings.getInstance().fireUISettingsChanged();
+  }
+}
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/UISimpleSettingsProvider.java b/platform/platform-impl/src/com/intellij/ide/ui/UISimpleSettingsProvider.java
new file mode 100644
index 0000000..d02916f
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/ide/ui/UISimpleSettingsProvider.java
@@ -0,0 +1,74 @@
+/*
+ * 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.ide.ui;
+
+import com.intellij.ide.SearchTopHitProvider;
+import com.intellij.ide.ui.search.OptionDescription;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.Consumer;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class UISimpleSettingsProvider implements SearchTopHitProvider {
+  private static OptionDescription CYCLING_SCROLLING = new UISettingsOptionDescription("CYCLING_SCROLLING", "Cyclic scrolling", "appearance");
+  private static OptionDescription MEMORY_INDICATOR = new UISettingsOptionDescription("SHOW_MEMORY_INDICATOR", "Show Memory Indicator", "appearance");
+  private static OptionDescription SHOW_MAIN_TOOLBAR = new UISettingsOptionDescription("SHOW_MAIN_TOOLBAR", "Show Main Toolbar", "appearance");
+  private static OptionDescription SHOW_NAVIGATION_BAR = new UISettingsOptionDescription("SHOW_NAVIGATION_BAR", "Show Navigation Bar", "appearance");
+  private static OptionDescription HIDE_TOOL_STRIPES = new UISettingsOptionDescription("HIDE_TOOL_STRIPES", "Hide Tool Window Bars", "appearance");
+  private static OptionDescription SHOW_STATUS_BAR = new UISettingsOptionDescription("SHOW_STATUS_BAR", "Show Status Bar", "appearance");
+  private static OptionDescription IS_BLOCK_CURSOR = new EditorOptionDescription("IS_BLOCK_CURSOR", "Show Block Cursor", "appearance");
+  private static OptionDescription IS_WHITESPACES_SHOWN = new EditorOptionDescription("IS_WHITESPACES_SHOWN", "Show Whitespaces", "appearance");
+  private static OptionDescription ARE_LINE_NUMBERS_SHOWN = new EditorOptionDescription("ARE_LINE_NUMBERS_SHOWN", "Show Line Numbers", "appearance");
+  private static OptionDescription SHOW_METHOD_SEPARATORS = new DaemonCodeAnalyzerOptionDescription("SHOW_METHOD_SEPARATORS", "Show Method Separators", "appearance");
+
+
+  @Override
+  public void consumeTopHits(String pattern, Consumer<Object> collector) {
+    pattern = pattern.trim().toLowerCase();
+    if (StringUtil.isBetween(pattern, "cyc", "cyclic ") || StringUtil.isBetween(pattern, "scr", "scroll ")) {
+      collector.consume(CYCLING_SCROLLING);
+    } else if (patternContains(pattern, "memo")) {
+      collector.consume(MEMORY_INDICATOR);
+    } else if (StringUtil.isBetween(pattern, "nav", "navigation bar ") || StringUtil.isBetween(pattern, "navb", "navbar ")) {
+      collector.consume(SHOW_NAVIGATION_BAR);
+    } else if (StringUtil.isBetween(pattern, "tool", "toolbar ")) {
+      collector.consume(SHOW_MAIN_TOOLBAR);
+    } else if (StringUtil.isBetween(pattern, "tool w", "tool window bars") || StringUtil.isBetween(pattern, "toolw", "toolwindow ")) {
+      collector.consume(HIDE_TOOL_STRIPES);
+    } else if (StringUtil.isBetween(pattern, "stat", "status bar ")) {
+      collector.consume(SHOW_STATUS_BAR);
+    } else if (StringUtil.isBetween(pattern, "curs", "cursor ") || StringUtil.isBetween(pattern, "block ", "block cursor ")
+      || StringUtil.isBetween(pattern, "caret", "caret ") || StringUtil.isBetween(pattern, "block ", "block caret ")) {
+      collector.consume(IS_BLOCK_CURSOR);
+    } else if (StringUtil.isBetween(pattern, "whites", "whitespaces ") || StringUtil.isBetween(pattern, "show whi", "show whitespaces ")) {
+      collector.consume(IS_WHITESPACES_SHOWN);
+    } else if (StringUtil.isBetween(pattern, "line ", "line numbers ") || StringUtil.isBetween(pattern, "show li", "show line numbers ")) {
+      collector.consume(ARE_LINE_NUMBERS_SHOWN);
+    } else if (StringUtil.isBetween(pattern, "separa ", "separators ") || StringUtil.isBetween(pattern, "method s", "method separators ")) {
+      collector.consume(SHOW_METHOD_SEPARATORS);
+    }
+  }
+
+  private static boolean patternContains(String pattern, String search) {
+    for (String s : pattern.split(" ")) {
+      if (s.contains(search)) {
+        return true;
+      }
+    }
+    return false;
+  }
+}
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 76eaf9e..97b6745 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
@@ -135,7 +135,12 @@
       }
       for (UIManager.LookAndFeelInfo laf : UIManager.getInstalledLookAndFeels()) {
         String name = laf.getName();
-        if (!"Metal".equalsIgnoreCase(name) && !"CDE/Motif".equalsIgnoreCase(name)) {
+        if (Registry.is("show.all.look.and.feels") ||
+            (   !"Metal".equalsIgnoreCase(name)
+             && !"CDE/Motif".equalsIgnoreCase(name)
+             && !"Nimbus".equalsIgnoreCase(name)
+             && !"Windows Classic".equalsIgnoreCase(name)
+             && !name.startsWith("JGoodies"))) {
           lafList.add(laf);
         }
       }
@@ -150,7 +155,6 @@
     if (!SystemInfo.isMac) {
       // do not sort LaFs on mac - the order is determined as Default, Darcula.
       // when we leave only system LaFs on other OSes, the order also should be determined as Default, Darcula
-      
       Arrays.sort(myLaFs, new Comparator<UIManager.LookAndFeelInfo>() {
         @Override
         public int compare(UIManager.LookAndFeelInfo obj1, UIManager.LookAndFeelInfo obj2) {
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java
index d46bde3..a708844 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/DarculaLaf.java
@@ -110,7 +110,7 @@
       if (SystemInfo.isWindows) {
         //JFrame.setDefaultLookAndFeelDecorated(true);
       }
-
+      defaults.put("EditorPane.font", defaults.getFont("TextField.font"));
       return defaults;
     }
     catch (Exception e) {
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties
index 438b059..b975ff8a 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/darcula.properties
@@ -9,6 +9,7 @@
 darcula.selectionBackgroundInactive=0D293E
 darcula.selectionInactiveBackground=0D293E
 darcula.selectionForegroundInactive=bbbbbb
+darcula.selectionInactiveForeground=bbbbbb
 window=3c3f41
 
 text=bbbbbb
@@ -49,7 +50,7 @@
 TabbedPane.tabInsets=0,4,0,4
 TabbedPane.highlight=292b2d
 TabbedPane.light=444444
-TabbedPane.selected=626262
+TabbedPane.selected=41516D
 TabbedPane.selectHighlight=3c3f41
 TabbedPane.contentBorderInsets=3,1,1,1
 TabbedPane.darkShadow=292b2d
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java
index 7a72ba5..cc09036 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/darcula/ui/DarculaComboBoxUI.java
@@ -79,8 +79,10 @@
 
         final int w = getWidth();
         final int h = getHeight();
-        g.setColor(getArrowButtonFillColor(UIUtil.getControlColor()));
-        g.fillRect(0, 0, w, h);
+        if (!isTableCellEditor(myComboBox)) {
+          g.setColor(getArrowButtonFillColor(UIUtil.getControlColor()));
+          g.fillRect(0, 0, w, h);
+        }
         g.setColor(comboBox.isEnabled() ? new JBColor(Gray._255, getForeground()) : new JBColor(Gray._255, getForeground().darker()));
         g.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
         g.setRenderingHint(RenderingHints.KEY_STROKE_CONTROL, RenderingHints.VALUE_STROKE_NORMALIZE);
@@ -96,8 +98,10 @@
         path.closePath();
         g.fill(path);
         g.translate(-2, 0);
-        g.setColor(getArrowButtonFillColor(getBorderColor()));
-        g.drawLine(0, -1, 0, h);
+        if (!isTableCellEditor(myComboBox)) {
+          g.setColor(getArrowButtonFillColor(getBorderColor()));
+          g.drawLine(0, -1, 0, h);
+        }
         config.restore();
       }
 
@@ -198,18 +202,24 @@
       g.setColor(parent.getBackground());
       g.fillRect(0, 0, c.getWidth(), c.getHeight());
     }
-    paintBorder(c, g, 0, 0, c.getWidth(), c.getHeight());
-    hasFocus = comboBox.hasFocus();
     Rectangle r = rectangleForCurrentValue();
-    paintCurrentValueBackground(g, r, hasFocus);
+    if (!isTableCellEditor(c)) {
+      paintBorder(c, g, 0, 0, c.getWidth(), c.getHeight());
+      hasFocus = comboBox.hasFocus();
+      paintCurrentValueBackground(g, r, hasFocus);
+    }
     paintCurrentValue(g, r, hasFocus);
   }
 
+  private static boolean isTableCellEditor(JComponent c) {
+    return Boolean.TRUE.equals(c.getClientProperty("JComboBox.isTableCellEditor"));
+  }
+
   @Override
   protected Rectangle rectangleForCurrentValue() {
     final Rectangle r = super.rectangleForCurrentValue();
     r.x-=2;
-    r.y-=1;
+    r.y-= isTableCellEditor(myComboBox) ? 0 : 1;
     return r;
   }
 
@@ -241,6 +251,11 @@
           comboBox, this, "ComboBox.disabledBackground", null));
       }
     }
+    // paint selection in table-cell-editor mode correctly
+    boolean changeOpaque = c instanceof JComponent && isTableCellEditor(comboBox) && c.isOpaque();
+    if (changeOpaque) {
+      ((JComponent)c).setOpaque(false);
+    }
 
     boolean shouldValidate = false;
     if (c instanceof JPanel) {
@@ -256,6 +271,10 @@
     }
 
     currentValuePane.paintComponent(g, c, comboBox, r.x, r.y, r.width, r.height, shouldValidate);
+    // return opaque for combobox popup items painting
+    if (changeOpaque) {
+      ((JComponent)c).setOpaque(true);
+    }
   }
 
 
diff --git a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf.properties b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf.properties
index 773bd46..388f9c4 100644
--- a/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf.properties
+++ b/platform/platform-impl/src/com/intellij/ide/ui/laf/intellijlaf.properties
@@ -14,6 +14,7 @@
 window=e8e8e8
 
 text=000000
+textInactiveText=999999
 textText=000000
 infoText=000000
 OptionPane.messageForeground=000000
@@ -30,7 +31,7 @@
 link.foreground=589df6
 ScrollBarUI=com.intellij.ide.ui.laf.darcula.ui.DarculaScrollBarUI
 
-Label.disabledForeground=777777
+Label.disabledForeground=999999
 
 TableHeaderUI=com.intellij.ide.ui.laf.darcula.DarculaTableHeaderUI
 Table.gridColor=dddddd
@@ -52,7 +53,7 @@
 TabbedPane.tabInsets=0,4,0,4
 TabbedPane.highlight=cccccc
 TabbedPane.light=444444
-TabbedPane.selected=93b3ec
+TabbedPane.selected=A2BAE0
 TabbedPane.selectHighlight=d2d2d2
 TabbedPane.contentBorderInsets=3,1,1,1
 TabbedPane.darkShadow=cccccc
diff --git a/platform/platform-impl/src/com/intellij/idea/StartupUtil.java b/platform/platform-impl/src/com/intellij/idea/StartupUtil.java
index 8231874..ef37fd9 100644
--- a/platform/platform-impl/src/com/intellij/idea/StartupUtil.java
+++ b/platform/platform-impl/src/com/intellij/idea/StartupUtil.java
@@ -130,6 +130,12 @@
         Main.showMessage("JDK Required", message, true);
         return false;
       }
+
+      if (StringUtil.containsIgnoreCase(System.getProperty("java.vm.name", ""), "OpenJDK") && !SystemInfo.isJavaVersionAtLeast("1.7")) {
+        String message = "OpenJDK 6 is not supported. Please use Oracle Java or newer OpenJDK.";
+        Main.showMessage("Unsupported JVM", message, true);
+        return false;
+      }
     }
 
     return true;
diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java
index 145a720..c08dfbf 100644
--- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java
+++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionMenu.java
@@ -71,6 +71,9 @@
     if (SystemInfo.isMacSystemMenu) {
       installSynchronizer();
     }
+    if (UIUtil.isUnderIntelliJLaF()) {
+      setOpaque(true);
+    }
   }
 
   public void updateContext(DataContext context) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
index a5fce16..a99994e 100644
--- a/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/actionSystem/impl/ActionToolbarImpl.java
@@ -265,9 +265,9 @@
     }
     for (int i = 0; i < actions.size(); i++) {
       final AnAction action = actions.get(i);
-      if (action instanceof Separator && isNavBar()) {
-        continue;
-      }
+//      if (action instanceof Separator && isNavBar()) {
+//        continue;
+//      }
 
       //if (action instanceof ComboBoxAction) {
       //  ((ComboBoxAction)action).setSmallVariant(true);
diff --git a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java
index 034872a..c1d21ac 100644
--- a/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/application/impl/ApplicationImpl.java
@@ -51,7 +51,7 @@
 import com.intellij.openapi.project.ex.ProjectManagerEx;
 import com.intellij.openapi.project.impl.ProjectManagerImpl;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.MessageBuilder;
+import com.intellij.openapi.ui.MessageDialogBuilder;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.*;
 import com.intellij.openapi.util.io.FileUtil;
@@ -881,7 +881,7 @@
         .message(hasUnsafeBgTasks ? "exit.confirm.prompt.tasks" : "exit.confirm.prompt",
                  ApplicationNamesInfo.getInstance().getFullProductName());
 
-      if (MessageBuilder.yesNo(ApplicationBundle.message("exit.confirm.title"), message).yesText(ApplicationBundle.message("command.exit")).noText(CommonBundle.message("button.cancel"))
+      if (MessageDialogBuilder.yesNo(ApplicationBundle.message("exit.confirm.title"), message).yesText(ApplicationBundle.message("command.exit")).noText(CommonBundle.message("button.cancel"))
             .doNotAsk(option).show() != Messages.YES) {
         return false;
       }
diff --git a/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java b/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java
index 643b6e6..d1e4855 100644
--- a/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java
+++ b/platform/platform-impl/src/com/intellij/openapi/command/impl/EditorChangeAction.java
@@ -27,6 +27,7 @@
 import com.intellij.openapi.vfs.encoding.EncodingManager;
 import com.intellij.testFramework.LightVirtualFile;
 import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
 
 import java.nio.charset.Charset;
 
@@ -39,21 +40,23 @@
   private final Object myNewString;
   private final long myOldTimeStamp;
   private final long myNewTimeStamp;
-  private final Charset myCharset;
+  @NotNull private final Charset myCharset;
 
   public EditorChangeAction(DocumentEvent e) {
     this((DocumentEx)e.getDocument(), e.getOffset(), e.getOldFragment(), e.getNewFragment(), e.getOldTimeStamp());
   }
 
-  public EditorChangeAction(DocumentEx document,
+  public EditorChangeAction(@NotNull DocumentEx document,
                             int offset,
                             CharSequence oldString,
                             CharSequence newString,
                             long oldTimeStamp) {
     super(document);
 
-    Charset charset = EncodingManager.getInstance().getEncoding(FileDocumentManager.getInstance().getFile(document), false);
-    myCharset = charset == null ? Charset.defaultCharset() : charset;
+    Charset charset = EncodingManager.getInstance().getEncoding(FileDocumentManager.getInstance().getFile(document), true);
+    if (charset == null) charset = EncodingManager.getInstance().getDefaultCharset();
+    if (charset == null) charset = Charset.defaultCharset();
+    myCharset = charset;
 
     myOffset = offset;
     myOldString = oldString == null ? "" : compressCharSequence(oldString, myCharset);
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 762aaaa..b34f292 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
@@ -152,7 +152,7 @@
     if (myReportCaretMoves) {
       LogMessageEx.error(LOG, "Unexpected caret move request");
     }
-    if (!myEditor.isStickySelection()) {
+    if (!myEditor.isStickySelection() && !pos.equals(myVisibleCaret)) {
       CopyPasteManager.getInstance().stopKillRings();
     }
 
@@ -441,7 +441,7 @@
     if (myReportCaretMoves) {
       LogMessageEx.error(LOG, "Unexpected caret move request");
     }
-    if (!myEditor.isStickySelection()) {
+    if (!myEditor.isStickySelection() && !pos.equals(myLogicalCaret)) {
       CopyPasteManager.getInstance().stopKillRings();
     }
 
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/ComplementaryFontsRegistry.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/ComplementaryFontsRegistry.java
index 1a9343f..148405d 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/ComplementaryFontsRegistry.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/ComplementaryFontsRegistry.java
@@ -148,7 +148,8 @@
     boolean tryDefaultFont = true;
     List<String> fontFamilies = preferences.getEffectiveFontFamilies();
     FontInfo result;
-    for (String fontFamily : fontFamilies) {
+    for (int i = 0, len = fontFamilies.size(); i < len; ++i) {
+      final String fontFamily = fontFamilies.get(i);
       result = doGetFontAbleToDisplay(c, preferences.getSize(fontFamily), style, fontFamily);
       if (result != null) {
         return result;
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 0452a66..fa9f274 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
@@ -45,7 +45,6 @@
 import com.intellij.openapi.ui.popup.Balloon;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.ProperTextRange;
-import com.intellij.openapi.util.registry.Registry;
 import com.intellij.ui.*;
 import com.intellij.ui.awt.RelativePoint;
 import com.intellij.util.Alarm;
@@ -1106,7 +1105,7 @@
         needDelay = true;
         final JPanel editorFragmentPreviewPanel = new JPanel() {
           private static final int R = 6;
-          private static final int LEFT_INDENT = BalloonImpl.ARC;// + 5;
+          private static final int LEFT_INDENT = 0;//BalloonImpl.ARC;// + 5;
 
           @Override
           public Dimension getPreferredSize() {
@@ -1133,13 +1132,13 @@
               UISettings.setupAntialiasing(cg);
               int lineShift = -myEditor.getLineHeight() * myCacheStartLine;
 
-              AffineTransform translateInstance = AffineTransform.getTranslateInstance(0, lineShift);
+              AffineTransform translateInstance = AffineTransform.getTranslateInstance(-4, lineShift);
               translateInstance.preConcatenate(t);
               cg.setTransform(translateInstance);
 
               cg.setClip(0, -lineShift, gutterWidth, myCacheLevel2.getHeight());
               gutterComponentEx.paint(cg);
-              translateInstance = AffineTransform.getTranslateInstance(gutterWidth, lineShift);
+              translateInstance = AffineTransform.getTranslateInstance(gutterWidth - 4, lineShift);
               translateInstance.preConcatenate(t);
               cg.setTransform(translateInstance);
               EditorComponentImpl contentComponent = myEditor.getContentComponent();
@@ -1261,7 +1260,7 @@
             showEditorHint(hintManager, myPointHolder.get(), myHintHolder.get());
             myDelayed = false;
           }
-        }, Registry.intValue("ide.tooltip.initialDelay"));
+        }, /*Registry.intValue("ide.tooltip.initialDelay")*/300);
       }
       else if (!myDelayed) {
         showEditorHint(hintManager, point, hintInfo);
diff --git a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java
index d3fa3b8..038bc3b 100644
--- a/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java
+++ b/platform/platform-impl/src/com/intellij/openapi/editor/impl/FoldRegionsTree.java
@@ -164,8 +164,15 @@
   boolean addRegion(FoldRegion range) {
     // During batchProcessing elements are inserted in ascending order,
     // binary search find acceptable insertion place first time
-    final boolean canUseCachedValue =
-      myCachedLastIndex != -1 && isBatchFoldingProcessing() && myRegions.get(myCachedLastIndex).getStartOffset() <= range.getStartOffset();
+    final boolean canUseCachedValue;
+    if (myCachedLastIndex >= myRegions.size()) {
+      // todo this happens after removeRegion()... myCachedListIndex must die!
+      canUseCachedValue = false;
+    }
+    else {
+      canUseCachedValue =
+        myCachedLastIndex != -1 && isBatchFoldingProcessing() && myRegions.get(myCachedLastIndex).getStartOffset() <= range.getStartOffset();
+    }
     int fastIndex = canUseCachedValue ? myCachedLastIndex + 1 : Collections.binarySearch(myRegions, range, RangeMarker.BY_START_OFFSET);
     if (fastIndex < 0) fastIndex = -fastIndex - 1;
     
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/BaseRemoteFileEditor.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/BaseRemoteFileEditor.java
new file mode 100644
index 0000000..525e0b1
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/BaseRemoteFileEditor.java
@@ -0,0 +1,161 @@
+package com.intellij.openapi.fileEditor.impl;
+
+import com.intellij.codeHighlighting.BackgroundEditorHighlighter;
+import com.intellij.ide.structureView.StructureViewBuilder;
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.EditorFactory;
+import com.intellij.openapi.editor.impl.DocumentImpl;
+import com.intellij.openapi.fileEditor.FileEditorLocation;
+import com.intellij.openapi.fileEditor.FileEditorState;
+import com.intellij.openapi.fileEditor.FileEditorStateLevel;
+import com.intellij.openapi.fileEditor.TextEditor;
+import com.intellij.openapi.fileEditor.impl.text.TextEditorState;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.UserDataHolderBase;
+import com.intellij.pom.Navigatable;
+import com.intellij.util.EventDispatcher;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.beans.PropertyChangeEvent;
+import java.beans.PropertyChangeListener;
+
+public abstract class BaseRemoteFileEditor implements TextEditor, PropertyChangeListener {
+  protected Editor myMockTextEditor;
+  protected volatile Navigatable myPendingNavigatable;
+
+  protected final Project myProject;
+  private final UserDataHolderBase myUserDataHolder = new UserDataHolderBase();
+  private final EventDispatcher<PropertyChangeListener> myDispatcher = EventDispatcher.create(PropertyChangeListener.class);
+
+  protected BaseRemoteFileEditor(@NotNull Project project) {
+    myProject = project;
+  }
+
+  @Override
+  @Nullable
+  public StructureViewBuilder getStructureViewBuilder() {
+    TextEditor textEditor = getTextEditor();
+    return textEditor == null ? null : textEditor.getStructureViewBuilder();
+  }
+
+  @Override
+  @NotNull
+  public Editor getEditor() {
+    TextEditor fileEditor = getTextEditor();
+    if (fileEditor != null) {
+      return fileEditor.getEditor();
+    }
+    else if (myMockTextEditor == null) {
+      myMockTextEditor = EditorFactory.getInstance().createViewer(new DocumentImpl(""), myProject);
+    }
+    return myMockTextEditor;
+  }
+
+  @Nullable
+  protected abstract TextEditor getTextEditor();
+
+  @Override
+  public FileEditorLocation getCurrentLocation() {
+    TextEditor textEditor = getTextEditor();
+    return textEditor == null ? null : textEditor.getCurrentLocation();
+  }
+
+  @Override
+  public BackgroundEditorHighlighter getBackgroundHighlighter() {
+    TextEditor textEditor = getTextEditor();
+    return textEditor == null ? null : textEditor.getBackgroundHighlighter();
+  }
+
+  @Override
+  @NotNull
+  public FileEditorState getState(@NotNull FileEditorStateLevel level) {
+    TextEditor textEditor = getTextEditor();
+    return textEditor == null ? new TextEditorState() : textEditor.getState(level);
+  }
+
+  @Override
+  public void setState(@NotNull FileEditorState state) {
+    TextEditor textEditor = getTextEditor();
+    if (textEditor != null && state instanceof TextEditorState) {
+      textEditor.setState(state);
+    }
+  }
+
+  @Override
+  public <T> T getUserData(@NotNull Key<T> key) {
+    TextEditor textEditor = getTextEditor();
+    return textEditor == null ? myUserDataHolder.getUserData(key) : textEditor.getUserData(key);
+  }
+
+  @Override
+  public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
+    TextEditor textEditor = getTextEditor();
+    if (textEditor == null) {
+      myUserDataHolder.putUserData(key, value);
+    }
+    else {
+      textEditor.putUserData(key, value);
+    }
+  }
+
+  @Override
+  public boolean isModified() {
+    return false;
+  }
+
+  @Override
+  public boolean isValid() {
+    return true;
+  }
+
+  @Override
+  public void dispose() {
+    if (myMockTextEditor != null) {
+      EditorFactory.getInstance().releaseEditor(myMockTextEditor);
+    }
+  }
+
+  @Override
+  public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
+    myDispatcher.addListener(listener);
+  }
+
+  @Override
+  public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
+    myDispatcher.removeListener(listener);
+  }
+
+  @Override
+  public void propertyChange(PropertyChangeEvent evt) {
+    myDispatcher.getMulticaster().propertyChange(evt);
+  }
+
+  @Override
+  public boolean canNavigateTo(@NotNull Navigatable navigatable) {
+    TextEditor editor = getTextEditor();
+    return editor == null ? isValid() : editor.canNavigateTo(navigatable);
+  }
+
+  @Override
+  public void navigateTo(@NotNull Navigatable navigatable) {
+    TextEditor editor = getTextEditor();
+    if (editor != null) {
+      editor.navigateTo(navigatable);
+    }
+    else if (isValid()) {
+      myPendingNavigatable = navigatable;
+    }
+  }
+
+  protected void checkPendingNavigable() {
+    Navigatable navigatable = myPendingNavigatable;
+    if (navigatable != null) {
+      myPendingNavigatable = null;
+      TextEditor editor = getTextEditor();
+      assert editor != null;
+      editor.navigateTo(navigatable);
+    }
+  }
+}
\ No newline at end of file
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java
index 8d8636c..ed16bb6 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/IdeDocumentHistoryImpl.java
@@ -22,7 +22,6 @@
 import com.intellij.openapi.command.CommandProcessor;
 import com.intellij.openapi.command.impl.CommandMerger;
 import com.intellij.openapi.components.*;
-import com.intellij.openapi.components.StoragePathMacros;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.EditorFactory;
@@ -310,7 +309,7 @@
       }
     }
 
-    return VfsUtil.toVirtualFileArray(files);
+    return VfsUtilCore.toVirtualFileArray(files);
   }
 
   @Override
@@ -521,7 +520,7 @@
     private final VirtualFile myFile;
     private final FileEditorState myNavigationState;
     private final String myEditorTypeId;
-    private WeakReference<EditorWindow> myWindow;
+    private final WeakReference<EditorWindow> myWindow;
 
     public PlaceInfo(@NotNull VirtualFile file, FileEditorState navigationState, String editorTypeId, @Nullable EditorWindow window) {
       myNavigationState = navigationState;
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java
index 956998c..fd7c571 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/HttpFileEditor.java
@@ -15,36 +15,42 @@
  */
 package com.intellij.openapi.fileEditor.impl.http;
 
-import com.intellij.codeHighlighting.BackgroundEditorHighlighter;
-import com.intellij.ide.structureView.StructureViewBuilder;
-import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.editor.EditorFactory;
-import com.intellij.openapi.editor.impl.DocumentImpl;
-import com.intellij.openapi.fileEditor.*;
-import com.intellij.openapi.fileEditor.impl.text.TextEditorState;
+import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.fileEditor.TextEditor;
+import com.intellij.openapi.fileEditor.impl.BaseRemoteFileEditor;
 import com.intellij.openapi.project.Project;
-import com.intellij.openapi.util.Key;
-import com.intellij.openapi.util.UserDataHolderBase;
 import com.intellij.openapi.vfs.impl.http.HttpVirtualFile;
-import com.intellij.pom.Navigatable;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
-import java.beans.PropertyChangeListener;
 
 /**
  * @author nik
  */
-public class HttpFileEditor implements TextEditor {
-  private final UserDataHolderBase myUserDataHolder = new UserDataHolderBase();
+public class HttpFileEditor extends BaseRemoteFileEditor {
   private final RemoteFilePanel myPanel;
-  private Editor myMockTextEditor;
-  private final Project myProject;
 
-  public HttpFileEditor(final Project project, final HttpVirtualFile virtualFile) {
-    myProject = project;
-    myPanel = new RemoteFilePanel(project, virtualFile);
+  public HttpFileEditor(@NotNull Project project, @NotNull HttpVirtualFile virtualFile) {
+    super(project);
+
+    myPanel = new RemoteFilePanel(project, virtualFile, this);
+    virtualFile.getFileInfo().download().doWhenDone(new Runnable() {
+      @Override
+      public void run() {
+        ApplicationManager.getApplication().invokeLater(new Runnable() {
+          @Override
+          public void run() {
+            checkPendingNavigable();
+          }
+        });
+      }
+    }).doWhenRejected(new Runnable() {
+      @Override
+      public void run() {
+        myPendingNavigatable = null;
+      }
+    });
   }
 
   @Override
@@ -69,47 +75,6 @@
   }
 
   @Override
-  @NotNull
-  public Editor getEditor() {
-    final TextEditor fileEditor = myPanel.getFileEditor();
-    if (fileEditor != null) {
-      return fileEditor.getEditor();
-    }
-    if (myMockTextEditor == null) {
-      myMockTextEditor = EditorFactory.getInstance().createViewer(new DocumentImpl(""), myProject);
-    }
-    return myMockTextEditor;
-  }
-
-  @Override
-  @NotNull
-  public FileEditorState getState(@NotNull final FileEditorStateLevel level) {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      return textEditor.getState(level);
-    }
-    return new TextEditorState();
-  }
-
-  @Override
-  public void setState(@NotNull final FileEditorState state) {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      textEditor.setState(state);
-    }
-  }
-
-  @Override
-  public boolean isModified() {
-    return false;
-  }
-
-  @Override
-  public boolean isValid() {
-    return true;
-  }
-
-  @Override
   public void selectNotify() {
     myPanel.selectNotify();
   }
@@ -120,84 +85,14 @@
   }
 
   @Override
-  public void addPropertyChangeListener(@NotNull final PropertyChangeListener listener) {
-    myPanel.addPropertyChangeListener(listener);
-  }
-
-  @Override
-  public void removePropertyChangeListener(@NotNull final PropertyChangeListener listener) {
-    myPanel.removePropertyChangeListener(listener);
-  }
-
-  @Override
-  public BackgroundEditorHighlighter getBackgroundHighlighter() {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      return textEditor.getBackgroundHighlighter();
-    }
-    return null;
-  }
-
-  @Override
-  public boolean canNavigateTo(@NotNull Navigatable navigatable) {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      return textEditor.canNavigateTo(navigatable);
-    }
-    return false;
-  }
-
-  @Override
-  public void navigateTo(@NotNull Navigatable navigatable) {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      textEditor.navigateTo(navigatable);
-    }
-  }
-
-  @Override
-  public <T> T getUserData(@NotNull Key<T> key) {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      return textEditor.getUserData(key);
-    }
-    return myUserDataHolder.getUserData(key);
-  }
-
-  @Override
-  public <T> void putUserData(@NotNull Key<T> key, @Nullable T value) {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      textEditor.putUserData(key, value);
-    }
-    else {
-      myUserDataHolder.putUserData(key, value);
-    }
-  }
-
-  @Override
-  public FileEditorLocation getCurrentLocation() {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      return textEditor.getCurrentLocation();
-    }
-    return null;
-  }
-
-  @Override
-  public StructureViewBuilder getStructureViewBuilder() {
-    final TextEditor textEditor = myPanel.getFileEditor();
-    if (textEditor != null) {
-      return textEditor.getStructureViewBuilder();
-    }
-    return null;
+  @Nullable
+  protected TextEditor getTextEditor() {
+    return myPanel.getFileEditor();
   }
 
   @Override
   public void dispose() {
-    if (myMockTextEditor != null) {
-      EditorFactory.getInstance().releaseEditor(myMockTextEditor);
-    }
+    super.dispose();
     myPanel.dispose();
   }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/LocalFileFinder.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/LocalFileFinder.java
index dfbff75..893f24d 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/LocalFileFinder.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/LocalFileFinder.java
@@ -18,6 +18,7 @@
 import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.Url;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -25,5 +26,5 @@
   public static final ExtensionPointName<LocalFileFinder> EP_NAME = ExtensionPointName.create("com.intellij.http.localFileFinder");
 
   @Nullable 
-  public abstract VirtualFile findLocalFile(@NotNull String url, @NotNull Project project);
+  public abstract VirtualFile findLocalFile(@NotNull Url url, @NotNull Project project);
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java
index b9c1f6f..2b9429c 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileEditor/impl/http/RemoteFilePanel.java
@@ -16,7 +16,10 @@
 package com.intellij.openapi.fileEditor.impl.http;
 
 import com.intellij.icons.AllIcons;
-import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.actionSystem.ActionManager;
+import com.intellij.openapi.actionSystem.ActionPlaces;
+import com.intellij.openapi.actionSystem.ActionToolbar;
+import com.intellij.openapi.actionSystem.DefaultActionGroup;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.fileEditor.TextEditor;
@@ -28,7 +31,6 @@
 import com.intellij.openapi.vfs.impl.http.HttpVirtualFile;
 import com.intellij.openapi.vfs.impl.http.RemoteFileInfo;
 import com.intellij.openapi.vfs.impl.http.RemoteFileState;
-import com.intellij.util.EventDispatcher;
 import com.intellij.util.net.HTTPProxySettingsDialog;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.util.ui.update.MergingUpdateQueue;
@@ -41,13 +43,12 @@
 import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
-import java.beans.PropertyChangeEvent;
 import java.beans.PropertyChangeListener;
 
 /**
  * @author nik
  */
-public class RemoteFilePanel implements PropertyChangeListener {
+public class RemoteFilePanel {
   private static final Logger LOG = Logger.getInstance("#com.intellij.openapi.fileEditor.impl.http.RemoteFilePanel");
   @NonNls private static final String ERROR_CARD = "error";
   @NonNls private static final String DOWNLOADING_CARD = "downloading";
@@ -67,12 +68,13 @@
   private final HttpVirtualFile myVirtualFile;
   private final MergingUpdateQueue myProgressUpdatesQueue;
   private final MyDownloadingListener myDownloadingListener;
-  private final EventDispatcher<PropertyChangeListener> myDispatcher = EventDispatcher.create(PropertyChangeListener.class);
+  private final PropertyChangeListener myPropertyChangeListener;
   private @Nullable TextEditor myFileEditor;
 
-  public RemoteFilePanel(final Project project, final HttpVirtualFile virtualFile) {
+  public RemoteFilePanel(final Project project, final HttpVirtualFile virtualFile, @NotNull PropertyChangeListener propertyChangeListener) {
     myProject = project;
     myVirtualFile = virtualFile;
+    myPropertyChangeListener = propertyChangeListener;
     myErrorLabel.setIcon(AllIcons.RunConfigurations.ConfigurationWarning);
     myUrlTextField.setText(virtualFile.getUrl());
     myProgressUpdatesQueue = new MergingUpdateQueue("downloading progress updates", 300, false, myMainPanel);
@@ -134,7 +136,7 @@
       @Override
       public void run() {
         final TextEditor textEditor = (TextEditor)TextEditorProvider.getInstance().createEditor(myProject, myVirtualFile);
-        textEditor.addPropertyChangeListener(RemoteFilePanel.this);
+        textEditor.addPropertyChangeListener(myPropertyChangeListener);
         myEditorPanel.removeAll();
         myEditorPanel.add(textEditor.getComponent(), BorderLayout.CENTER);
         myFileEditor = textEditor;
@@ -185,19 +187,6 @@
     }
   }
 
-  public void addPropertyChangeListener(PropertyChangeListener listener) {
-    myDispatcher.addListener(listener);
-  }
-
-  public void removePropertyChangeListener(PropertyChangeListener listener) {
-    myDispatcher.removeListener(listener);
-  }
-
-  @Override
-  public void propertyChange(PropertyChangeEvent evt) {
-    myDispatcher.getMulticaster().propertyChange(evt);
-  }
-
   private class MyDownloadingListener implements FileDownloadingListener {
     @Override
     public void fileDownloaded(final VirtualFile localFile) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java
index 155f06a..9821e94 100644
--- a/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java
+++ b/platform/platform-impl/src/com/intellij/openapi/fileTypes/ex/FileTypeChooser.java
@@ -57,7 +57,7 @@
     super(true);
     myFileName = fileName;
 
-    myOpenInIdea.setText("Open matching files in " + ApplicationNamesInfo.getInstance().getProductName() + ":");
+    myOpenInIdea.setText("Open matching files in " + ApplicationNamesInfo.getInstance().getFullProductName() + ":");
 
     FileType[] fileTypes = FileTypeManager.getInstance().getRegisteredFileTypes();
     Arrays.sort(fileTypes, new Comparator<FileType>() {
diff --git a/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java b/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java
index 3f0f574..7e23854 100644
--- a/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java
+++ b/platform/platform-impl/src/com/intellij/openapi/ui/FrameWrapper.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -74,6 +74,9 @@
   private boolean myIsDialog;
   private boolean myImageWasChanged;
 
+  //Skip restoration of MAXIMIZED_BOTH_PROPERTY
+  private static final boolean WORKAROUND_FOR_JDK_8007219 = SystemInfo.isMac && SystemInfo.isOracleJvm;
+
   public FrameWrapper(Project project) {
     this(project, null);
   }
@@ -163,7 +166,7 @@
     }
     if (myImageWasChanged) {
       frame.setIconImage(myImage);
-    } 
+    }
     else {
       AppUIUtil.updateWindowIcon(myFrame);
     }
@@ -318,7 +321,7 @@
       }
     }
 
-    if (extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) {
+    if (!WORKAROUND_FOR_JDK_8007219 && extendedState == Frame.MAXIMIZED_BOTH && frame instanceof JFrame) {
       ((JFrame)frame).setExtendedState(extendedState);
     }
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java
index ad2b119..319ad85 100644
--- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java
+++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/AbstractUpdateDialog.java
@@ -76,7 +76,7 @@
       css += "<style>body {background: #" + ColorUtil.toHex(UIUtil.getPanelBackground()) + ";}</style>";
     }
     updateLinkPane.setBorder(IdeBorderFactory.createEmptyBorder());
-    updateLinkPane.setText(IdeBundle.message("updates.configure.label", css));
+    updateLinkPane.setText(IdeBundle.message("updates.configure.label", css, ShowSettingsUtil.getSettingsMenuName()));
     updateLinkPane.setEditable(false);
     LabelTextReplacingUtil.replaceText(panel);
 
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 839b9da..21fcae1 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
@@ -367,7 +367,7 @@
             "&build=" + buildNumber + "&uuid=" + URLEncoder.encode(uuid, "UTF8");
     }
 
-    PluginDownloader downloader = new PluginDownloader(descriptor.getPluginId().getIdString(), url, null, null, descriptor.getName());
+    PluginDownloader downloader = new PluginDownloader(descriptor.getPluginId().getIdString(), url, descriptor.getVersion(), null, descriptor.getName());
     downloader.setDescriptor(descriptor);
     return downloader;
   }
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java
index 1fd3b6d..22cb0e9 100644
--- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java
+++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginAdvertiserEditorNotificationProvider.java
@@ -138,8 +138,7 @@
           });
         }
       });
-    } else {
-
+    } else if (PluginsAdvertiser.hasBundledNotInstalledPlugin(plugins)){
       if (PropertiesComponent.getInstance().isTrueValue(PluginsAdvertiser.IGNORE_ULTIMATE_EDITION)) {
         return null;
       }
@@ -159,6 +158,8 @@
           myNotifications.updateAllNotifications();
         }
       });
+    } else {
+      return null;
     }
     panel.createActionLabel("Ignore extension", new Runnable() {
       @Override
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java
index 509de13..3a0a040 100644
--- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java
+++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiser.java
@@ -105,9 +105,9 @@
   }
 
   private static Map<String, Set<Plugin>> loadSupportedExtensions(@NotNull List<IdeaPluginDescriptor> allPlugins) {
-    final Set<String> availableIds = new HashSet<String>();
+    final Map<String, IdeaPluginDescriptor> availableIds = new HashMap<String, IdeaPluginDescriptor>();
     for (IdeaPluginDescriptor plugin : allPlugins) {
-      availableIds.add(plugin.getPluginId().getIdString());
+      availableIds.put(plugin.getPluginId().getIdString(), plugin);
     }
     final String pluginRepositoryUrl = FEATURE_IMPLEMENTATIONS_URL + "featureType=" + FileTypeFactory.FILE_TYPE_FACTORY_EP.getName();
     try {
@@ -125,10 +125,14 @@
           final String pluginId = StringUtil.unquoteString(jsonObject.get("pluginId").toString());
           final JsonElement bundledExt = jsonObject.get("bundled");
           boolean isBundled = Boolean.parseBoolean(bundledExt.toString());
-          if (!availableIds.contains(pluginId) && !isBundled) continue;
+          final IdeaPluginDescriptor fromServerPluginDescription = availableIds.get(pluginId);
+          if (fromServerPluginDescription == null && !isBundled) continue;
 
-          final IdeaPluginDescriptor plugin = PluginManager.getPlugin(PluginId.getId(pluginId));
-          if (plugin != null && plugin.isEnabled()) continue;
+          final IdeaPluginDescriptor loadedPlugin = PluginManager.getPlugin(PluginId.getId(pluginId));
+          if (loadedPlugin != null && loadedPlugin.isEnabled()) continue;
+
+          if (loadedPlugin != null && fromServerPluginDescription != null && 
+              StringUtil.compareVersionNumbers(loadedPlugin.getVersion(), fromServerPluginDescription.getVersion()) >= 0) continue;
 
           final JsonElement ext = jsonObject.get("implementationName");
           final String extension = StringUtil.unquoteString(ext.toString());
@@ -210,6 +214,15 @@
     return null;
   }
 
+  static boolean hasBundledNotInstalledPlugin(Collection<Plugin> plugins) {
+    for (Plugin plugin : plugins) {
+      if (plugin.myBundled && PluginManager.getPlugin(PluginId.getId(plugin.myPluginId)) == null) {
+        return true;
+      }
+    }
+    return false;
+  }
+
   @Override
   public void runActivity(@NotNull final Project project) {
     if (!UpdateSettings.getInstance().CHECK_NEEDED) return;
@@ -258,13 +271,11 @@
                   if (pluginDescriptor != null) {
                     myDisabledPlugins.put(plugin, pluginDescriptor);
                   }
-                } else {
-                  if (plugin.myBundled) {
-                    myBundledPlugins = true;
-                  }
-                }
+                } 
               }
 
+              myBundledPlugins = hasBundledNotInstalledPlugin(ids.values());
+
               for (IdeaPluginDescriptor loadedPlugin : myAllPlugins) {
                 final PluginId pluginId = loadedPlugin.getPluginId();
                 if (ids.containsKey(pluginId.getIdString()) && !disabledPlugins.contains(pluginId.getIdString())) {
diff --git a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java
index c749111..dd702b1 100644
--- a/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java
+++ b/platform/platform-impl/src/com/intellij/openapi/updateSettings/impl/pluginsAdvertisement/PluginsAdvertiserDialog.java
@@ -74,14 +74,13 @@
 
   @Override
   protected void doOKAction() {
-    final Set<IdeaPluginDescriptor> pluginsToEnable = new HashSet<IdeaPluginDescriptor>();
+    final Set<String> pluginsToEnable = new HashSet<String>();
     final List<PluginNode> nodes = new ArrayList<PluginNode>();
     for (PluginDownloader downloader : myUploadedPlugins) {
-      if (!mySkippedPlugins.contains(downloader.getPluginId())) {
-        final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(PluginId.getId(downloader.getPluginId()));
-        if (descriptor != null) {
-          pluginsToEnable.add(descriptor);
-        } else {
+      String pluginId = downloader.getPluginId();
+      if (!mySkippedPlugins.contains(pluginId)) {
+        pluginsToEnable.add(pluginId);
+        if (!PluginManagerCore.getDisabledPlugins().contains(pluginId)) {
           final PluginNode pluginNode = PluginDownloader.createPluginNode(null, downloader);
           if (pluginNode != null) {
             nodes.add(pluginNode);
@@ -95,8 +94,8 @@
         PluginManagerMain.notifyPluginsWereInstalled(null, myProject);
       }
     };
-    for (IdeaPluginDescriptor pluginDescriptor : pluginsToEnable) {
-      PluginManagerCore.enablePlugin(pluginDescriptor.getPluginId().getIdString());
+    for (String pluginId : pluginsToEnable) {
+      PluginManagerCore.enablePlugin(pluginId);
     }
     if (!nodes.isEmpty()) {
       try {
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java
index 30f585a..16034e1 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/DefaultRemoteContentProvider.java
@@ -19,10 +19,13 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.fileTypes.FileType;
+import com.intellij.openapi.fileTypes.FileTypeRegistry;
+import com.intellij.openapi.fileTypes.FileTypes;
 import com.intellij.openapi.progress.EmptyProgressIndicator;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VfsBundle;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.PathUtil;
 import com.intellij.util.io.UrlConnectionUtil;
 import org.jetbrains.annotations.NotNull;
 
@@ -76,8 +79,13 @@
       if (size != -1) {
         callback.setProgressFraction(0);
       }
-      String contentType = connection.getContentType();
-      FileType fileType = RemoteFileUtil.getFileType(contentType);
+      FileType fileType = RemoteFileUtil.getFileType(connection.getContentType());
+      if (fileType == FileTypes.PLAIN_TEXT) {
+        FileType fileTypeByFileName = FileTypeRegistry.getInstance().getFileTypeByFileName(PathUtil.getFileName(url));
+        if (fileTypeByFileName != FileTypes.UNKNOWN) {
+          fileType = fileTypeByFileName;
+        }
+      }
 
       int len;
       final byte[] buf = new byte[1024];
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfoImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfoImpl.java
index 5775d21..59293f2 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfoImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/RemoteFileInfoImpl.java
@@ -19,10 +19,11 @@
 import com.intellij.openapi.application.WriteAction;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.fileTypes.FileType;
+import com.intellij.openapi.util.AsyncResult;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VfsBundle;
-import com.intellij.openapi.vfs.VfsUtil;
+import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
@@ -142,7 +143,7 @@
 
     VirtualFile localFile = new WriteAction<VirtualFile>() {
       @Override
-      protected void run(final Result<VirtualFile> result) {
+      protected void run(@NotNull final Result<VirtualFile> result) {
         final VirtualFile file = LocalFileSystem.getInstance().refreshAndFindFileByIoFile(localIOFile);
         if (file != null) {
           file.refresh(false, false);
@@ -234,7 +235,7 @@
       myCancelled.set(true);
       if (myPrevLocalFile != null) {
         myLocalVirtualFile = myPrevLocalFile;
-        myLocalFile = VfsUtil.virtualToIoFile(myLocalVirtualFile);
+        myLocalFile = VfsUtilCore.virtualToIoFile(myLocalVirtualFile);
         myState = RemoteFileState.DOWNLOADED;
         myErrorMessage = null;
       }
@@ -291,4 +292,60 @@
       }
     }
   }
+
+  @NotNull
+  @Override
+  public AsyncResult<VirtualFile> download() {
+    synchronized (myLock) {
+      switch (getState()) {
+        case DOWNLOADING_NOT_STARTED:
+          startDownloading();
+          return createDownloadedCallback(this);
+        case DOWNLOADING_IN_PROGRESS:
+          return createDownloadedCallback(this);
+        case DOWNLOADED:
+          return new AsyncResult.Done<VirtualFile>(myLocalVirtualFile);
+
+        case ERROR_OCCURRED:
+        default:
+          return new AsyncResult.Rejected<VirtualFile>();
+      }
+    }
+  }
+
+  private static AsyncResult<VirtualFile> createDownloadedCallback(@NotNull final RemoteFileInfo remoteFileInfo) {
+    final AsyncResult<VirtualFile> callback = new AsyncResult<VirtualFile>();
+    remoteFileInfo.addDownloadingListener(new FileDownloadingAdapter() {
+      @Override
+      public void fileDownloaded(VirtualFile localFile) {
+        try {
+          remoteFileInfo.removeDownloadingListener(this);
+        }
+        finally {
+          callback.setDone(localFile);
+        }
+      }
+
+      @Override
+      public void errorOccurred(@NotNull String errorMessage) {
+        try {
+          remoteFileInfo.removeDownloadingListener(this);
+        }
+        finally {
+          callback.reject(errorMessage);
+        }
+      }
+
+      @Override
+      public void downloadingCancelled() {
+        try {
+          remoteFileInfo.removeDownloadingListener(this);
+        }
+        finally {
+          callback.setRejected();
+        }
+      }
+    });
+    return callback;
+  }
 }
diff --git a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/VirtualFileImpl.java b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/VirtualFileImpl.java
index ceb4bc4..fc32ae9 100644
--- a/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/VirtualFileImpl.java
+++ b/platform/platform-impl/src/com/intellij/openapi/vfs/impl/http/VirtualFileImpl.java
@@ -18,7 +18,6 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileTypes.FileType;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.vfs.VirtualFileManager;
 import com.intellij.openapi.vfs.VirtualFileSystem;
@@ -65,7 +64,7 @@
         }
       });
 
-      path = StringUtil.trimEnd(UriUtil.trimParameters(path), "/");
+      path = UriUtil.trimLastSlash(UriUtil.trimParameters(path));
       int lastSlash = path.lastIndexOf('/');
       if (lastSlash == -1) {
         myParentPath = null;
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 30ca7fe..4f6793a 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
@@ -23,21 +23,18 @@
 import com.intellij.openapi.util.ShutDownTracker;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.util.io.*;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.*;
 import com.intellij.openapi.vfs.newvfs.*;
 import com.intellij.openapi.vfs.newvfs.events.*;
 import com.intellij.openapi.vfs.newvfs.impl.FakeVirtualFile;
 import com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl;
 import com.intellij.openapi.vfs.newvfs.impl.VirtualFileSystemEntry;
-import com.intellij.util.ArrayUtil;
-import com.intellij.util.Function;
-import com.intellij.util.IncorrectOperationException;
-import com.intellij.util.SmartList;
+import com.intellij.util.*;
 import com.intellij.util.containers.ConcurrentIntObjectMap;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.StripedLockIntObjectConcurrentHashMap;
 import com.intellij.util.io.ReplicatorInputStream;
+import com.intellij.util.io.URLUtil;
 import com.intellij.util.messages.MessageBus;
 import gnu.trove.*;
 import org.jetbrains.annotations.NonNls;
@@ -942,8 +939,7 @@
   @NotNull
   private static String normalizeRootUrl(@NotNull String basePath, @NotNull NewVirtualFileSystem fs) {
     // need to protect against relative path of the form "/x/../y"
-    String url = fs.getProtocol() + "://" + VfsImplUtil.normalize(fs, FileUtil.toCanonicalPath(basePath));
-    return StringUtil.trimEnd(url, "/");
+    return UriUtil.trimLastSlash(fs.getProtocol() + URLUtil.SCHEME_SEPARATOR + VfsImplUtil.normalize(fs, FileUtil.toCanonicalPath(basePath)));
   }
 
   @Override
@@ -979,10 +975,13 @@
       LOG.error(sb);
       return null;
     }
-    if (visited == null) visited = new TIntArrayList(DEPTH_LIMIT);
-    visited.add(id);
 
     int parentId = getParent(id);
+    if (parentId >= id) {
+      if (visited == null) visited = new TIntArrayList(DEPTH_LIMIT);
+    }
+    if (visited != null)  visited.add(id);
+
     VirtualFileSystemEntry result;
     if (parentId == 0) {
       myRootsLock.readLock().lock();
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java
index 9e51608..e7dbaef 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/IdeMenuBar.java
@@ -161,8 +161,13 @@
 
   @Override
   public void menuSelectionChanged(boolean isIncluded) {
-    if (!getSelectionModel().isSelected()) return;
-    if (myState == State.COLLAPSED) {
+    if (!isIncluded && myState == State.TEMPORARY_EXPANDED) {
+      myActivated = false;
+      setState(State.COLLAPSING);
+      restartAnimator();
+      return;
+    }
+    if (isIncluded && myState == State.COLLAPSED) {
       myActivated = true;
       setState(State.TEMPORARY_EXPANDED);
       revalidate();
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java
index 5bfe217..9c863e4 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/StripeButtonUI.java
@@ -16,7 +16,6 @@
 package com.intellij.openapi.wm.impl;
 
 import com.intellij.openapi.wm.ToolWindowAnchor;
-import com.intellij.ui.ColorUtil;
 import com.intellij.ui.Gray;
 import com.intellij.util.ui.UIUtil;
 
@@ -26,7 +25,6 @@
 import javax.swing.plaf.metal.MetalToggleButtonUI;
 import java.awt.*;
 import java.awt.geom.AffineTransform;
-import java.awt.geom.RoundRectangle2D;
 
 /**
  * @author Vladimir Kondratyev
@@ -51,7 +49,7 @@
     final Dimension dim=super.getPreferredSize(button);
 
     dim.width=(int)(4+dim.width*1.1f);
-    dim.height+=4;
+    dim.height+=2;
 
     final ToolWindowAnchor anchor=button.getAnchor();
     if(ToolWindowAnchor.LEFT==anchor||ToolWindowAnchor.RIGHT==anchor){
@@ -108,21 +106,17 @@
 
     final ButtonModel model=button.getModel();
     final Color background = button.getBackground();
-    final boolean vertical = anchor == ToolWindowAnchor.LEFT || anchor == ToolWindowAnchor.RIGHT;
-
-//    if (ApplicationManager.getApplication().isInternal()) {
-      ourIconRect.x-=2;
-      ourTextRect.x-=2;
+    ourIconRect.x -= 2;
+    ourTextRect.x -= 2;
+    if (model.isArmed() && model.isPressed() || model.isSelected() || model.isRollover()) {
       if (anchor == ToolWindowAnchor.LEFT) g2.translate(-1, 0);
       if (anchor.isHorizontal()) g2.translate(0, -1);
-      paintNewDecoration(g2, button, model, vertical);
+      final boolean dark = UIUtil.isUnderDarcula();
+      g2.setColor(dark ? Gray._15.withAlpha(85) : Gray._85.withAlpha(85));
+      g2.fillRect(0, 0, button.getWidth(), button.getHeight());
       if (anchor == ToolWindowAnchor.LEFT) g2.translate(1, 0);
       if (anchor.isHorizontal()) g2.translate(0, 1);
-//    } else {
-//      if (anchor == ToolWindowAnchor.RIGHT) g2.translate(1, 0);
-//      paintLegacyDecoration(g2, button, model, vertical);
-//      if (anchor == ToolWindowAnchor.RIGHT) g2.translate(-1, 0);
-//    }
+    }
 
 
     AffineTransform tr=null;
@@ -163,7 +157,7 @@
       /* Draw the Text */
       if(model.isEnabled()){
         /*** paint the text normally */
-        g2.setColor(button.getForeground());
+        g2.setColor(UIUtil.isUnderDarcula() && (model.isSelected() || model.isRollover()) ? button.getForeground().brighter() : button.getForeground());
         BasicGraphicsUtils.drawString(g2,clippedText,button.getMnemonic2(),ourTextRect.x,ourTextRect.y+fm.getAscent());
       } else{
         /*** paint the text disabled ***/
@@ -182,25 +176,6 @@
     g2.dispose();
   }
 
-  private static void paintNewDecoration(Graphics2D g2, AnchoredButton button, ButtonModel model, boolean vertical) {
-    final boolean dark = UIUtil.isUnderDarcula();
-    Color toBorder = model.isRollover() ? dark ? Gray._90 : new Color(0, 0, 0, 50) : null;
-    double gap = 2;
-    double r = (((vertical? button.getWidth() : button.getHeight()) - 2 * gap) - 1)/4;
-    Shape shape = new RoundRectangle2D.Double(gap, gap, button.getWidth() - 2 * gap, button.getHeight() - 2 * gap, r, r);
-
-    if (model.isArmed() && model.isPressed() || model.isSelected()) {
-      g2.setColor(ColorUtil.mix(dark ? Gray._85.withAlpha(85) : new Color(0, 0, 0, 30), new Color(100, 150, 230, 50), .5));
-      g2.fill(shape);
-      g2.setColor(dark ? Gray._40 : new Color(0, 0, 0, 120));
-      g2.draw(shape);
-      toBorder = null;
-    }
-    if (toBorder != null) {
-      g2.setColor(toBorder);
-      g2.draw(shape);
-    }
-  }
 
   private static void paintLegacyDecoration(Graphics2D g2, AnchoredButton button, ButtonModel model, boolean vertical) {
     final boolean dark = UIUtil.isUnderDarcula();
diff --git a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java
index a84ec5f..08504b9 100644
--- a/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java
+++ b/platform/platform-impl/src/com/intellij/openapi/wm/impl/status/ToolWindowsWidget.java
@@ -189,6 +189,7 @@
     super.addNotify();
     final String key = "toolwindow.stripes.buttons.info.shown";
     if (UISettings.getInstance().HIDE_TOOL_STRIPES && !PropertiesComponent.getInstance().isTrueValue(key)) {
+      PropertiesComponent.getInstance().setValue(key, String.valueOf(true));
       final Alarm alarm = new Alarm();
       alarm.addRequest(new Runnable() {
         @Override
@@ -197,10 +198,9 @@
             "tool.window.quick.access.message"))
             .setDisposable(ToolWindowsWidget.this)
             .show(new RelativePoint(ToolWindowsWidget.this, new Point(10, 0)), Balloon.Position.above);
-            PropertiesComponent.getInstance().setValue(key, String.valueOf(true));
           Disposer.dispose(alarm);
         }
-      }, 30000);
+      }, 20000);
     }
   }
 
diff --git a/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java b/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java
index ab780d3..72676d8 100644
--- a/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java
+++ b/platform/platform-impl/src/com/intellij/platform/DefaultPlatformTopHitProvider.java
@@ -28,6 +28,16 @@
      {"new c", "new class ", "NewClass"},
      {"new i", "new interface ", "NewClass"},
      {"new e", "new enum ", "NewClass"},
+     {"line", "line numbers ", "EditorToggleShowLineNumbers"},
+     {"show li", "show line numbers ", "EditorToggleShowLineNumbers"},
+     {"ann", "annotate ", "Annotate"},
+     {"wrap", "wraps ", "EditorToggleUseSoftWraps"},
+     {"soft w", "soft wraps ", "EditorToggleUseSoftWraps"},
+     {"use sof", "use soft wraps ", "EditorToggleUseSoftWraps"},
+     {"use wr", "use wraps ", "EditorToggleUseSoftWraps"},
+     {"ref", "refactor ", "Refactorings.QuickListPopupAction"},
+     {"mov", "move ", "Move"},
+     {"ren", "rename  ", "RenameElement"},
    };
 
   @Override
diff --git a/platform/platform-impl/src/com/intellij/remotesdk/RemoteCredentialsHolder.java b/platform/platform-impl/src/com/intellij/remotesdk/RemoteCredentialsHolder.java
index 5dab18e..a55478e 100644
--- a/platform/platform-impl/src/com/intellij/remotesdk/RemoteCredentialsHolder.java
+++ b/platform/platform-impl/src/com/intellij/remotesdk/RemoteCredentialsHolder.java
@@ -25,6 +25,16 @@
  */
 public class RemoteCredentialsHolder implements RemoteCredentials {
 
+  public static final String HOST = "HOST";
+  public static final String PORT = "PORT";
+  public static final String ANONYMOUS = "ANONYMOUS";
+  public static final String USERNAME = "USERNAME";
+  public static final String PASSWORD = "PASSWORD";
+  public static final String USE_KEY_PAIR = "USE_KEY_PAIR";
+  public static final String PRIVATE_KEY_FILE = "PRIVATE_KEY_FILE";
+  public static final String KNOWN_HOSTS_FILE = "MY_KNOWN_HOSTS_FILE";
+  public static final String PASSPHRASE = "PASSPHRASE";
+
   private String myHost;
   private int myPort;
   private boolean myAnonymous;
diff --git a/platform/platform-impl/src/com/intellij/remotesdk/RemoteSdkDataHolder.java b/platform/platform-impl/src/com/intellij/remotesdk/RemoteSdkDataHolder.java
index 184f0b2..1cb2cb2 100644
--- a/platform/platform-impl/src/com/intellij/remotesdk/RemoteSdkDataHolder.java
+++ b/platform/platform-impl/src/com/intellij/remotesdk/RemoteSdkDataHolder.java
@@ -15,15 +15,6 @@
 public class RemoteSdkDataHolder extends RemoteCredentialsHolder implements RemoteSdkData {
 
   public static final String SSH_PREFIX = "ssh://";
-  private static final String HOST = "HOST";
-  private static final String PORT = "PORT";
-  private static final String ANONYMOUS = "ANONYMOUS";
-  private static final String USERNAME = "USERNAME";
-  private static final String PASSWORD = "PASSWORD";
-  private static final String USE_KEY_PAIR = "USE_KEY_PAIR";
-  private static final String PRIVATE_KEY_FILE = "PRIVATE_KEY_FILE";
-  private static final String KNOWN_HOSTS_FILE = "MY_KNOWN_HOSTS_FILE";
-  private static final String PASSPHRASE = "PASSPHRASE";
   private static final String INTERPRETER_PATH = "INTERPRETER_PATH";
   private static final String HELPERS_PATH = "HELPERS_PATH";
   private static final String REMOTE_ROOTS = "REMOTE_ROOTS";
diff --git a/platform/platform-impl/src/com/intellij/ui/AppUIUtil.java b/platform/platform-impl/src/com/intellij/ui/AppUIUtil.java
index 7ae9fb6..c0bfb6f 100644
--- a/platform/platform-impl/src/com/intellij/ui/AppUIUtil.java
+++ b/platform/platform-impl/src/com/intellij/ui/AppUIUtil.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.ui.popup.Balloon;
 import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.ToolWindowManager;
 import com.intellij.util.PlatformUtils;
@@ -123,9 +124,11 @@
   }
 
   public static void registerBundledFonts() {
-    registerFont("/fonts/Inconsolata.ttf");
-    registerFont("/fonts/SourceCodePro-Regular.ttf");
-    registerFont("/fonts/SourceCodePro-Bold.ttf");
+    if (Registry.is("ide.register.bundled.fonts")) {
+      registerFont("/fonts/Inconsolata.ttf");
+      registerFont("/fonts/SourceCodePro-Regular.ttf");
+      registerFont("/fonts/SourceCodePro-Bold.ttf");
+    }
   }
 
   private static void registerFont(@NonNls String name) {
diff --git a/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java b/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java
index 101db7b..ec53597 100644
--- a/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java
+++ b/platform/platform-impl/src/com/intellij/ui/ComboboxEditorTextField.java
@@ -111,7 +111,7 @@
   @Override
   public Dimension getPreferredSize() {
     final Dimension preferredSize = super.getPreferredSize();
-    return new Dimension(preferredSize.width, (SystemInfo.isMac && UIUtil.isUnderAquaLookAndFeel() ? 28 : preferredSize.height));
+    return new Dimension(preferredSize.width, UIUtil.fixComboBoxHeight(preferredSize.height));
   }
 
   @Override
diff --git a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java
index 37ebcc4..4797051 100644
--- a/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java
+++ b/platform/platform-impl/src/com/intellij/ui/FinderRecursivePanel.java
@@ -427,10 +427,12 @@
               @Override
               public void run() {
                 try {
+                  final List<T> listItems = getListItems();
+
                   SwingUtilities.invokeLater(new Runnable() {
                     @Override
                     public void run() {
-                      mergeListItems(myListModel, getListItems());
+                      mergeListItems(myListModel, listItems);
 
                       if (myList.getSelectedIndex() < 0) {
                         myList.setSelectedIndex(myListModel.getSize() > oldIndex ? oldIndex : 0);
diff --git a/platform/platform-impl/src/com/intellij/ui/GotItPanel.form b/platform/platform-impl/src/com/intellij/ui/GotItPanel.form
index 2c6f5d7..e26061e 100644
--- a/platform/platform-impl/src/com/intellij/ui/GotItPanel.form
+++ b/platform/platform-impl/src/com/intellij/ui/GotItPanel.form
@@ -54,7 +54,7 @@
               <opaque value="false"/>
             </properties>
             <border type="empty">
-              <size top="2" left="10" bottom="2" right="8"/>
+              <size top="4" left="10" bottom="4" right="8"/>
             </border>
             <children>
               <component id="366a9" class="javax.swing.JLabel">
diff --git a/platform/platform-impl/src/com/intellij/ui/GotItPanel.java b/platform/platform-impl/src/com/intellij/ui/GotItPanel.java
index a2bb792..d07b42f 100644
--- a/platform/platform-impl/src/com/intellij/ui/GotItPanel.java
+++ b/platform/platform-impl/src/com/intellij/ui/GotItPanel.java
@@ -42,8 +42,9 @@
         GraphicsUtil.setupAAPainting(g);
         ((Graphics2D)g).setPaint(new GradientPaint(0, 0, new JBColor(new Color(77, 143, 253), new Color(52, 74, 100)), 0, getHeight(),
                                                    new JBColor(new Color(71, 135, 237), new Color(38, 53, 73))));
-        g.fillRoundRect(0,0,getWidth()-1, getHeight()-1, 5,5);
-        g.setColor(new JBColor(new Color(48, 121, 237), new Color(87, 93, 101)));
+        g.fillRoundRect(0, 0, getWidth() - 1, getHeight() - 1, 5, 5);
+        ((Graphics2D)g).setStroke(new BasicStroke(UIUtil.isUnderDarcula() ? 2f : 1f));
+        g.setColor(new JBColor(new Color(71, 91, 167), new Color(78, 120, 161)));
         g.drawRoundRect(0,0,getWidth()-1, getHeight()-1, 5,5);
       }
     };
diff --git a/platform/platform-impl/src/com/intellij/ui/JBTabsPaneImpl.java b/platform/platform-impl/src/com/intellij/ui/JBTabsPaneImpl.java
index 503a947..39c8aaf 100644
--- a/platform/platform-impl/src/com/intellij/ui/JBTabsPaneImpl.java
+++ b/platform/platform-impl/src/com/intellij/ui/JBTabsPaneImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,6 +21,7 @@
 import com.intellij.openapi.wm.IdeFocusManager;
 import com.intellij.ui.tabs.*;
 import com.intellij.ui.tabs.impl.JBTabsImpl;
+import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -43,7 +44,12 @@
       public void selectionChanged(TabInfo oldSelection, TabInfo newSelection) {
         fireChanged(new ChangeEvent(myTabs));
       }
-    }).getPresentation().setPaintBorder(1, 1, 1, 1).setTabSidePaintBorder(2).setPaintFocus(false).setGhostsAlwaysVisible(true);
+    }).getPresentation()
+      .setPaintBorder(1, 1, 1, 1)
+      .setTabSidePaintBorder(2)
+      .setPaintFocus(UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF())
+      .setAlwaysPaintSelectedTab(UIUtil.isUnderDarcula() || UIUtil.isUnderIntelliJLaF())
+      .setGhostsAlwaysVisible(true);
 
     setTabPlacement(tabPlacement);
   }
diff --git a/platform/platform-impl/src/com/intellij/ui/mac/JDK7WindowReorderingWorkaround.java b/platform/platform-impl/src/com/intellij/ui/mac/JDK7WindowReorderingWorkaround.java
new file mode 100644
index 0000000..267e0e7
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/ui/mac/JDK7WindowReorderingWorkaround.java
@@ -0,0 +1,71 @@
+/*
+ * 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.ui.mac;
+
+import com.intellij.openapi.util.SystemInfo;
+import com.intellij.ui.mac.foundation.Foundation;
+import com.intellij.ui.mac.foundation.ID;
+import com.sun.jna.Callback;
+import com.sun.jna.Pointer;
+
+import java.util.concurrent.atomic.AtomicInteger;
+
+import static com.intellij.ui.mac.foundation.Foundation.invoke;
+
+/**
+ * @author Denis Fokin
+ */
+public class JDK7WindowReorderingWorkaround {
+
+  private static AtomicInteger requestorCount = new AtomicInteger();
+
+  private static final Callback windowDidBecomeMainCallback = new Callback() {
+    @SuppressWarnings("UnusedDeclaration") // this is a native up-call
+    public void callback(ID self,
+                         ID nsNotification)
+    {
+      if (requestorCount.intValue() == 0) {
+        invoke(self, "oldWindowDidBecomeMain:", nsNotification);
+      }
+    }
+  };
+
+  static {
+    if (SystemInfo.isJavaVersionAtLeast("1.7")) {
+      ID awtWindow = Foundation.getObjcClass("AWTWindow");
+
+      Pointer windowWillEnterFullScreenMethod = Foundation.createSelector("windowDidBecomeMain:");
+      ID originalWindowWillEnterFullScreen = Foundation.class_replaceMethod(awtWindow, windowWillEnterFullScreenMethod,
+                                                                            windowDidBecomeMainCallback, "v@::@");
+
+      Foundation.addMethodByID(awtWindow, Foundation.createSelector("oldWindowDidBecomeMain:"),
+                               originalWindowWillEnterFullScreen, "v@::@");
+    }
+  }
+
+  static void disableReordering() {
+    if (SystemInfo.isJavaVersionAtLeast("1.7")) {
+      requestorCount.incrementAndGet();
+    }
+  }
+
+  static void enableReordering () {
+    if (SystemInfo.isJavaVersionAtLeast("1.7")) {
+      requestorCount.decrementAndGet();
+    }
+  }
+
+}
diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java b/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java
index 80c214e..76bf9b3 100644
--- a/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java
+++ b/platform/platform-impl/src/com/intellij/ui/mac/MacFileChooserDialogImpl.java
@@ -137,6 +137,7 @@
       finally {
         Foundation.cfRelease(self);
         Foundation.cfRelease(contextInfo);
+        JDK7WindowReorderingWorkaround.enableReordering();
       }
     }
   };
@@ -323,6 +324,7 @@
     ourImplMap.put(delegate, impl);
 
     final ID select = toSelect == null ? null : Foundation.nsString(toSelect);
+    JDK7WindowReorderingWorkaround.disableReordering();
     invoke(delegate, "performSelectorOnMainThread:withObject:waitUntilDone:", Foundation.createSelector("showOpenPanel:"), select, false);
   }
 
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 8fd02ce..c563f9b 100644
--- a/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java
+++ b/platform/platform-impl/src/com/intellij/ui/mac/MacMainFrameDecorator.java
@@ -328,7 +328,7 @@
 
   @Override
   public void toggleFullScreen(final boolean state) {
-    if (!SystemInfo.isMacOSLion || myFrame == null) return;
+    if (!SystemInfo.isMacOSLion || myFrame == null || myInFullScreen == state) return;
 
     myFullscreenQueue.runOrEnqueue( new Runnable() {
       @Override
@@ -343,7 +343,7 @@
           catch (InvocationTargetException e) {
             LOG.error(e);
           }
-        } else if (myInFullScreen != state) {
+        } else {
           final ID window = MacUtil.findWindowForTitle(myFrame.getTitle());
           if (window == null) return;
           Foundation.executeOnMainThread(new Runnable() {
diff --git a/platform/platform-impl/src/com/intellij/ui/mac/MacMessagesImpl.java b/platform/platform-impl/src/com/intellij/ui/mac/MacMessagesImpl.java
index de16a2d..a4e5dce 100644
--- a/platform/platform-impl/src/com/intellij/ui/mac/MacMessagesImpl.java
+++ b/platform/platform-impl/src/com/intellij/ui/mac/MacMessagesImpl.java
@@ -19,14 +19,17 @@
 import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.IdeFocusManager;
 import com.intellij.openapi.wm.WindowManager;
 import com.intellij.openapi.wm.impl.ModalityHelper;
+import com.intellij.ui.mac.foundation.Foundation;
 import com.intellij.ui.mac.foundation.ID;
 import com.intellij.ui.mac.foundation.MacUtil;
 import com.intellij.util.ui.UIUtil;
 import com.sun.jna.Callback;
+import com.sun.jna.Pointer;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -68,6 +71,7 @@
         resultsFromDocumentRoot.put(documentRoot, new MessageResult(returnCode.intValue(), suppressState.intValue() == 1));
         queuesFromDocumentRoot.get(windowFromId.get(contextInfo.longValue())).runFromQueue();
       }
+      JDK7WindowReorderingWorkaround.enableReordering();
       cfRelease(self);
     }
   };
@@ -198,6 +202,20 @@
 
   private MacMessagesImpl() {}
 
+  private static final Callback windowDidBecomeMainCallback = new Callback() {
+    @SuppressWarnings("UnusedDeclaration") // this is a native up-call
+    public void callback(ID self,
+                         ID nsNotification)
+    {
+      synchronized (lock) {
+        if (!windowFromId.keySet().contains(self.longValue())) {
+          return;
+        }
+      }
+      invoke(self, "oldWindowDidBecomeMain:", nsNotification);
+    }
+  };
+
   static {
     if (SystemInfo.isMac) {
       final ID delegateClass = allocateObjcClassPair(getObjcClass("NSObject"), "NSAlertDelegate_");
@@ -211,6 +229,19 @@
         throw new RuntimeException("Unable to add method to objective-c delegate class!");
       }
       registerObjcClassPair(delegateClass);
+
+      if (SystemInfo.isJavaVersionAtLeast("1.7")) {
+
+        ID awtWindow = Foundation.getObjcClass("AWTWindow");
+
+        Pointer windowWillEnterFullScreenMethod = Foundation.createSelector("windowDidBecomeMain:");
+        ID originalWindowWillEnterFullScreen = Foundation.class_replaceMethod(awtWindow, windowWillEnterFullScreenMethod,
+                                                                              windowDidBecomeMainCallback, "v@::@");
+
+        Foundation.addMethodByID(awtWindow, Foundation.createSelector("oldWindowDidBecomeMain:"),
+                                 originalWindowWillEnterFullScreen, "v@::@");
+
+      }
     }
   }
 
@@ -325,8 +356,10 @@
   }
 
   private static void startModal(final Window w, ID windowId) {
+    long windowPtr = windowId.longValue();
     synchronized (lock) {
-      windowFromId.put(windowId.longValue(), w);
+      JDK7WindowReorderingWorkaround.disableReordering();
+      windowFromId.put(windowPtr, w);
       if (blockedDocumentRoots.keySet().contains(w)) {
         blockedDocumentRoots.put(w, blockedDocumentRoots.get(w) + 1);
       } else {
@@ -335,6 +368,9 @@
     }
 
     pumpEventsDocumentExclusively(w);
+    synchronized (lock) {
+      windowFromId.remove(windowPtr);
+    }
   }
 
   private enum COMMON_DIALOG_PARAM_TYPE {
@@ -453,8 +489,8 @@
                                                                           : doNotAskDialogOption.getDoNotShowMessage()));
       params.put(COMMON_DIALOG_PARAM_TYPE.doNotAskDialogOption2, nsString(doNotAskDialogOption != null
                                                                           && !doNotAskDialogOption.isToBeShown() ? "checked" : "-1"));
-      MessageResult result = resultsFromDocumentRoot.remove(showDialog(window, "showSheet:",
-                                                                       new DialogParamsWrapper(DialogParamsWrapper.DialogType.alert, params)));
+      MessageResult result = resultsFromDocumentRoot.remove(
+        showDialog(window, "showSheet:", new DialogParamsWrapper(DialogParamsWrapper.DialogType.alert, params)));
 
       int convertedResult = convertReturnCodeFromNativeAlertDialog(result.myReturnCode, alternateText);
 
@@ -528,13 +564,11 @@
   //title, message, errorStyle, window, paramsArray, doNotAskDialogOption, "showVariableButtonsSheet:"
   private static Window showDialog(@Nullable Window window, final String methodName, DialogParamsWrapper paramsWrapper) {
 
-    Window foremostWindow = getForemostWindow(window);
+    final Window foremostWindow = getForemostWindow(window);
 
-    String foremostWindowTitle = getWindowTitle(foremostWindow);
+    final Window documentRoot = getDocumentRootFromWindow(foremostWindow);
 
-    Window documentRoot = getDocumentRootFromWindow(foremostWindow);
-
-    final ID nativeFocusedWindow = MacUtil.findWindowForTitle(foremostWindowTitle);
+    final ID nativeFocusedWindow = MacUtil.findWindowFromJavaWindow(foremostWindow);
 
     paramsWrapper.setNativeWindow(nativeFocusedWindow);
 
@@ -563,18 +597,6 @@
     return result - 1000;
   }
 
-  private static String getWindowTitle(Window documentRoot) {
-    String windowTitle;
-    if (documentRoot instanceof Frame) {
-      windowTitle = ((Frame)documentRoot).getTitle();
-    } else if (documentRoot instanceof Dialog) {
-      windowTitle = ((Dialog)documentRoot).getTitle();
-    } else {
-      throw new RuntimeException("The window is not a frame and not a dialog!");
-    }
-    return windowTitle;
-  }
-
   @Messages.YesNoCancelResult
   private static int convertReturnCodeFromNativeAlertDialog(int returnCode, String alternateText) {
     // DEFAULT = 1
@@ -680,12 +702,16 @@
     }
 
     //Actually can, but not in this implementation. If you know a reasonable scenario, please ask Denis Fokin for the improvement.
-    LOG.assertTrue(getWindowTitle(_window) != null, "A window without a title should not be used for showing MacMessages");
-    while (_window != null && getWindowTitle(_window) == null) {
+    LOG.assertTrue(MacUtil.getWindowTitle(_window) != null, "A window without a title should not be used for showing MacMessages");
+    while (_window != null && MacUtil.getWindowTitle(_window) == null) {
       _window = _window.getOwner();
       //At least our frame should have a title
     }
 
+    while (Registry.is("skip.untitled.windows.for.mac.messages") && _window != null && _window instanceof JDialog && !((JDialog)_window).isModal()) {
+      _window = _window.getOwner();
+    }
+
     return _window;
   }
 
diff --git a/platform/platform-impl/src/com/intellij/util/LocalFileUrl.java b/platform/platform-impl/src/com/intellij/util/LocalFileUrl.java
new file mode 100644
index 0000000..0ac07b5
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/util/LocalFileUrl.java
@@ -0,0 +1,81 @@
+package com.intellij.util;
+
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public final class LocalFileUrl implements Url {
+  private final String path;
+
+  public LocalFileUrl(@NotNull String path) {
+    this.path = path;
+  }
+
+  @NotNull
+  @Override
+  public String getPath() {
+    return path;
+  }
+
+  @Override
+  public boolean isInLocalFileSystem() {
+    return true;
+  }
+
+  @Override
+  public String toDecodedForm() {
+    return path;
+  }
+
+  @NotNull
+  @Override
+  public String toExternalForm() {
+    return path;
+  }
+
+  @Nullable
+  @Override
+  public String getScheme() {
+    return null;
+  }
+
+  @Nullable
+  @Override
+  public String getAuthority() {
+    return null;
+  }
+
+  @Nullable
+  @Override
+  public String getParameters() {
+    return null;
+  }
+
+  @NotNull
+  @Override
+  public Url trimParameters() {
+    return this;
+  }
+
+  @Override
+  public String toString() {
+    return toExternalForm();
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    return o instanceof LocalFileUrl && path.equals(((LocalFileUrl)o).path);
+  }
+
+  @Override
+  public boolean equalsIgnoreParameters(@Nullable Url url) {
+    return equals(url);
+  }
+
+  @Override
+  public int hashCode() {
+    return path.hashCode();
+  }
+}
\ No newline at end of file
diff --git a/platform/platform-impl/src/com/intellij/util/UriUtil.java b/platform/platform-impl/src/com/intellij/util/UriUtil.java
index 3a77c87..7ee1634 100644
--- a/platform/platform-impl/src/com/intellij/util/UriUtil.java
+++ b/platform/platform-impl/src/com/intellij/util/UriUtil.java
@@ -34,15 +34,17 @@
 
 public final class UriUtil {
   public static final CharMatcher PARAM_CHAR_MATCHER = CharMatcher.anyOf("?#;");
+  public static final CharMatcher SLASH_MATCHER = CharMatcher.is('/');
 
   private static final Pattern DATA_URI_PATTERN = Pattern.compile("data:([^,;]+/[^,;]+)(;charset=[^,;]+)?(;base64)?,(.+)");
 
   private UriUtil() {
   }
 
-  /**
-   * must be synchronized with trimUrlParameters in utils.js
-   */
+  public static String trimLastSlash(@NotNull String url) {
+    return SLASH_MATCHER.trimTrailingFrom(url);
+  }
+
   public static String trimParameters(@NotNull String url) {
     int end = PARAM_CHAR_MATCHER.indexIn(url);
     return end != -1 ? url.substring(0, end) : url;
diff --git a/platform/platform-impl/src/com/intellij/util/UrlImpl.java b/platform/platform-impl/src/com/intellij/util/UrlImpl.java
new file mode 100644
index 0000000..0c9cc83
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/util/UrlImpl.java
@@ -0,0 +1,171 @@
+/*
+ * 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;
+
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.StandardFileSystems;
+import com.intellij.util.io.URLUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+public final class UrlImpl implements Url {
+  private final String scheme;
+  private final String authority;
+
+  private final String path;
+  private String decodedPath;
+
+  private final String parameters;
+
+  private String externalForm;
+  private UrlImpl withoutParameters;
+
+  public UrlImpl(@Nullable String path) {
+    this(null, null, path, null);
+  }
+
+  UrlImpl(@NotNull String scheme, @Nullable String authority, @Nullable String path) {
+    this(scheme, authority, path, null);
+  }
+
+  public UrlImpl(@Nullable String scheme, @Nullable String authority, @Nullable String path, @Nullable String parameters) {
+    this.scheme = scheme;
+    this.authority = StringUtil.nullize(authority);
+    this.path = StringUtil.isEmpty(path) ? "/" : path;
+    this.parameters = StringUtil.nullize(parameters);
+  }
+
+  @NotNull
+  @Override
+  public String getPath() {
+    if (decodedPath == null) {
+      decodedPath = URLUtil.unescapePercentSequences(path);
+    }
+    return decodedPath;
+  }
+
+  @Nullable
+  @Override
+  public String getScheme() {
+    return scheme;
+  }
+
+  @Override
+  @Nullable
+  public String getAuthority() {
+    return authority;
+  }
+
+  @Override
+  public boolean isInLocalFileSystem() {
+    return StandardFileSystems.FILE_PROTOCOL.equals(scheme);
+  }
+
+  @Nullable
+  @Override
+  public String getParameters() {
+    return parameters;
+  }
+
+  @Override
+  public String toDecodedForm() {
+    StringBuilder builder = new StringBuilder();
+    if (scheme != null) {
+      builder.append(scheme);
+      if (authority != null || isInLocalFileSystem()) {
+        builder.append(URLUtil.SCHEME_SEPARATOR);
+      }
+      else {
+        builder.append(':');
+      }
+
+      if (authority != null) {
+        builder.append(authority);
+      }
+    }
+    builder.append(getPath());
+    if (parameters != null) {
+      builder.append(parameters);
+    }
+    return builder.toString();
+  }
+
+  @Override
+  @NotNull
+  public String toExternalForm() {
+    if (externalForm != null) {
+      return externalForm;
+    }
+
+    // relative path - special url, encoding is not required
+    // authority is null in case of URI or file URL
+    if ((path.charAt(0) != '/' || authority == null) && !isInLocalFileSystem()) {
+      return toDecodedForm();
+    }
+
+    String result = Urls.toUriWithoutParameters(this).toASCIIString();
+    if (parameters != null) {
+      result += parameters;
+    }
+    externalForm = result;
+    return result;
+  }
+
+  @Override
+  @NotNull
+  public Url trimParameters() {
+    if (parameters == null) {
+      return this;
+    }
+    else if (withoutParameters == null) {
+      withoutParameters = new UrlImpl(scheme, authority, path, null);
+    }
+    return withoutParameters;
+  }
+
+  @Override
+  public String toString() {
+    return toExternalForm();
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) {
+      return true;
+    }
+    if (!(o instanceof UrlImpl)) {
+      return false;
+    }
+
+    UrlImpl url = (UrlImpl)o;
+    return StringUtil.equals(scheme, url.scheme) && StringUtil.equals(authority, url.authority) && getPath().equals(url.getPath()) && StringUtil.equals(parameters, url.parameters);
+  }
+
+  @Override
+  public boolean equalsIgnoreParameters(@Nullable Url url) {
+    return url != null && equals(url.trimParameters());
+  }
+
+  @Override
+  public int hashCode() {
+    int result = scheme == null ? 0 : scheme.hashCode();
+    result = 31 * result + (authority == null ? 0 : authority.hashCode());
+    String decodedPath = getPath();
+    result = 31 * result + decodedPath.hashCode();
+    result = 31 * result + (parameters == null ? 0 : parameters.hashCode());
+    return result;
+  }
+}
\ No newline at end of file
diff --git a/platform/platform-impl/src/com/intellij/util/Urls.java b/platform/platform-impl/src/com/intellij/util/Urls.java
new file mode 100644
index 0000000..6a1ee01
--- /dev/null
+++ b/platform/platform-impl/src/com/intellij/util/Urls.java
@@ -0,0 +1,189 @@
+/*
+ * 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;
+
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.openapi.vfs.StandardFileSystems;
+import com.intellij.openapi.vfs.VfsUtilCore;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.io.URLUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+public final class Urls {
+  private static final Logger LOG = Logger.getInstance(Urls.class);
+
+  // about ";" see WEB-100359
+  private static final Pattern URI_PATTERN = Pattern.compile("^([^:/?#]+):(//)?([^/?#]*)([^?#;]*)(.*)");
+
+  @NotNull
+  public static Url newUri(@NotNull String scheme, @NotNull String path) {
+    return new UrlImpl(scheme, null, path);
+  }
+
+  @NotNull
+  public static Url newFromEncoded(@NotNull String url) {
+    Url result = parseEncoded(url);
+    LOG.assertTrue(result != null, url);
+    return result;
+  }
+
+  @Nullable
+  public static Url parseEncoded(@NotNull String url) {
+    return parse(url, false);
+  }
+
+  @NotNull
+  public static Url newHttpUrl(@NotNull String authority, @Nullable String path) {
+    return newUrl("http", authority, path);
+  }
+
+  @NotNull
+  public static Url newUrl(@NotNull String scheme, @NotNull String authority, @Nullable String path) {
+    return new UrlImpl(scheme, authority, path);
+  }
+
+  @NotNull
+  /**
+   * Url will not be normalized (see {@link VfsUtilCore#toIdeaUrl(String)}), parsed as is
+   */
+  public static Url newFromIdea(@NotNull String url) {
+    Url result = parseFromIdea(url);
+    LOG.assertTrue(result != null, url);
+    return result;
+  }
+
+  // java.net.URI.create cannot parse "file:///Test Stuff" - but you don't need to worry about it - this method is aware
+  @Nullable
+  public static Url parseFromIdea(@NotNull String url) {
+    return URLUtil.containsScheme(url) ? parseUrl(url) : new LocalFileUrl(url);
+  }
+
+  @Nullable
+  public static Url parse(@NotNull String url, boolean asLocalIfNoScheme) {
+    if (asLocalIfNoScheme && !URLUtil.containsScheme(url)) {
+      // nodejs debug — files only in local filesystem
+      return new LocalFileUrl(url);
+    }
+    return parseUrl(VfsUtilCore.toIdeaUrl(url));
+  }
+
+  @Nullable
+  public static URI parseAsJavaUriWithoutParameters(@NotNull String url) {
+    Url asUrl = parseUrl(url);
+    if (asUrl == null) {
+      return null;
+    }
+
+    try {
+      return toUriWithoutParameters(asUrl);
+    }
+    catch (Exception e) {
+      LOG.info("Can't parse " + url, e);
+      return null;
+    }
+  }
+
+  @Nullable
+  private static Url parseUrl(@NotNull String url) {
+    String urlToParse;
+    if (url.startsWith("jar:file://")) {
+      urlToParse = url.substring("jar:".length());
+    }
+    else {
+      urlToParse = url;
+    }
+
+    Matcher matcher = URI_PATTERN.matcher(urlToParse);
+    if (!matcher.matches()) {
+      LOG.warn("Cannot parse url " + url);
+      return null;
+    }
+    String scheme = matcher.group(1);
+    if (urlToParse != url) {
+      scheme = "jar:" + scheme;
+    }
+
+    String authority = StringUtil.nullize(matcher.group(3));
+
+    String path = StringUtil.nullize(matcher.group(4));
+    if (path != null) {
+      path = FileUtil.toCanonicalUriPath(path);
+    }
+
+    if (authority != null && (StandardFileSystems.FILE_PROTOCOL.equals(scheme) || StringUtil.isEmpty(matcher.group(2)))) {
+      path = path == null ? authority : (authority + path);
+      authority = null;
+    }
+    return new UrlImpl(scheme, authority, path, matcher.group(5));
+  }
+
+  @NotNull
+  public static Url newFromVirtualFile(@NotNull VirtualFile file) {
+    if (file.isInLocalFileSystem()) {
+      return newUri(file.getFileSystem().getProtocol(), file.getPath());
+    }
+    else {
+      Url url = parseUrl(file.getUrl());
+      return url == null ? new UrlImpl(file.getPath()) : url;
+    }
+  }
+
+  public static boolean equalsIgnoreParameters(@NotNull Url url, @NotNull List<Url> urls) {
+    for (Url otherUrl : urls) {
+      if (url.equalsIgnoreParameters(otherUrl)) {
+        return true;
+      }
+    }
+    return false;
+  }
+
+  public static boolean equalsIgnoreParameters(@NotNull Url url, @NotNull VirtualFile file) {
+    if (file.isInLocalFileSystem()) {
+      return url.isInLocalFileSystem() && url.getPath().equals(file.getPath());
+    }
+    else if (url.isInLocalFileSystem()) {
+      return false;
+    }
+
+    Url fileUrl = parseUrl(file.getUrl());
+    return fileUrl != null && fileUrl.equalsIgnoreParameters(url);
+  }
+
+  @NotNull
+  public static URI toUriWithoutParameters(@NotNull Url url) {
+    try {
+      String externalPath = url.getPath();
+      boolean inLocalFileSystem = url.isInLocalFileSystem();
+      if (inLocalFileSystem && SystemInfo.isWindows && externalPath.charAt(0) != '/') {
+        externalPath = '/' + externalPath;
+      }
+      return new URI(inLocalFileSystem ? "file" : url.getScheme(), inLocalFileSystem ? "" : url.getAuthority(), externalPath, null, null);
+    }
+    catch (URISyntaxException e) {
+      throw new RuntimeException(e);
+    }
+  }
+}
\ No newline at end of file
diff --git a/platform/platform-impl/src/org/jetbrains/io/BuiltInServer.java b/platform/platform-impl/src/org/jetbrains/io/BuiltInServer.java
index a1bfcc0..08e3aa8 100644
--- a/platform/platform-impl/src/org/jetbrains/io/BuiltInServer.java
+++ b/platform/platform-impl/src/org/jetbrains/io/BuiltInServer.java
@@ -94,7 +94,7 @@
         int customPortServerManagerPort = customPortServerManager.getPort();
         SubServer subServer = new SubServer(customPortServerManager, eventLoopGroup);
         Disposer.register(this, subServer);
-        if (customPortServerManagerPort != firstPort && customPortServerManagerPort != port) {
+        if (customPortServerManager.isAvailableExternally() || (customPortServerManagerPort != firstPort && customPortServerManagerPort != port)) {
           subServer.bind(customPortServerManagerPort);
         }
       }
diff --git a/platform/platform-impl/src/org/jetbrains/io/SubServer.java b/platform/platform-impl/src/org/jetbrains/io/SubServer.java
index 9f14762..e5e3597 100644
--- a/platform/platform-impl/src/org/jetbrains/io/SubServer.java
+++ b/platform/platform-impl/src/org/jetbrains/io/SubServer.java
@@ -37,7 +37,7 @@
   }
 
   public boolean bind(int port) {
-    if (port == BuiltInServerManager.getInstance().getPort()) {
+    if (!user.isAvailableExternally() && port == BuiltInServerManager.getInstance().getPort()) {
       return true;
     }
 
diff --git a/platform/platform-main/src/com/intellij/idea/MainImpl.java b/platform/platform-main/src/com/intellij/idea/MainImpl.java
index 32269af..afaf62e 100644
--- a/platform/platform-main/src/com/intellij/idea/MainImpl.java
+++ b/platform/platform-main/src/com/intellij/idea/MainImpl.java
@@ -29,18 +29,24 @@
    * Called from PluginManager via reflection.
    */
   protected static void start(final String[] args) {
-    System.setProperty(PlatformUtilsCore.PLATFORM_PREFIX_KEY, PlatformUtils.getPlatformPrefix(PlatformUtils.COMMUNITY_PREFIX));
+    System.setProperty(PlatformUtilsCore.PLATFORM_PREFIX_KEY, PlatformUtils.getPlatformPrefix(PlatformUtilsCore.COMMUNITY_PREFIX));
 
     StartupUtil.prepareAndStart(args, new StartupUtil.AppStarter() {
       @Override
       public void start(boolean newConfigFolder) {
-        final IdeaApplication app = new IdeaApplication(args);
         //noinspection SSBasedInspection
         SwingUtilities.invokeLater(new Runnable() {
           @Override
           public void run() {
             PluginManager.installExceptionHandler();
-            app.run();
+            final IdeaApplication app = new IdeaApplication(args);
+            //noinspection SSBasedInspection
+            SwingUtilities.invokeLater(new Runnable() {
+              @Override
+              public void run() {
+                app.run();
+              }
+            });
           }
         });
       }
diff --git a/platform/platform-resources-en/src/messages/IdeBundle.properties b/platform/platform-resources-en/src/messages/IdeBundle.properties
index e5852f2..1bdb05e 100644
--- a/platform/platform-resources-en/src/messages/IdeBundle.properties
+++ b/platform/platform-resources-en/src/messages/IdeBundle.properties
@@ -889,7 +889,7 @@
 
 updates.info.dialog.title=Update Info
 updates.no.updates.message=<html><h4>You are using the latest version of $FULLNAME$.</h4></html>
-updates.configure.label=<html><head>{0}</head><br>To configure automatic update settings, see the <b><a href=\"updates\">Updates</a></b> dialog of your IDE settings</html>
+updates.configure.label=<html><head>{0}</head><br>To configure automatic update settings, see the <b><a href=\"updates\">Updates</a></b> dialog of your IDE {1}</html>
 updates.timeout.error=Connection timed out
 updates.download.and.install.patch.button=&Download Patch and Shutdown
 updates.download.and.install.patch.button.restart=Up&date and Restart
diff --git a/platform/platform-resources-en/src/messages/InspectionsBundle.properties b/platform/platform-resources-en/src/messages/InspectionsBundle.properties
index 1387cab..0665e5c 100644
--- a/platform/platform-resources-en/src/messages/InspectionsBundle.properties
+++ b/platform/platform-resources-en/src/messages/InspectionsBundle.properties
@@ -123,6 +123,8 @@
 inspection.local.can.be.final.display.name=Local variable or parameter can be final
 inspection.local.can.be.final.option=Report local variables
 inspection.local.can.be.final.option1=Report method parameters
+inspection.local.can.be.final.option2=Report catch parameters
+inspection.local.can.be.final.option3=Report foreach parameters
 inspection.can.be.local.parameter.problem.descriptor=Parameter <code>#ref</code> can have <code>final</code> modifier
 inspection.can.be.local.variable.problem.descriptor=Variable <code>#ref</code> can have <code>final</code> modifier
 
diff --git a/platform/platform-resources-en/src/misc/registry.properties b/platform/platform-resources-en/src/misc/registry.properties
index 3ce8884..caaef0b 100644
--- a/platform/platform-resources-en/src/misc/registry.properties
+++ b/platform/platform-resources-en/src/misc/registry.properties
@@ -1,3 +1,18 @@
+#
+# 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.
+#
 localHistory.daysToKeep=5
 # suppress inspection "UnusedProperty"
 localHistory.daysToKeep.description=Specify how many working days changes should be remembered.\n\
@@ -7,7 +22,7 @@
 
 actionSystem.fixLostTyping=true
 # suppress inspection "UnusedProperty"
-actionSystem.fixLostTyping.descrinonRegistry.isption=Redispatch events, lost between actions and dialog show/close.
+actionSystem.fixLostTyping.description=Redispatch events, lost between actions and dialog show/close.
 actionSystem.fixStickyFocusedWindows=true
 actionSystem.fixNullFocusedComponent=true
 actionSystem.noDefaultComponent=true
@@ -41,7 +56,7 @@
 actionSystem.win.suppressAlt=true
 actionSystem.mouseGesturesEnabled=true
 actionSystem.assertFocusAccessFromEdt=true
-actionSystem.enableAbbreviations=false
+actionSystem.enableAbbreviations=true
 
 ide.firstStartup=true
 ide.debugMode=false
@@ -107,6 +122,8 @@
 ide.balloon.shadowEnabled=true
 ide.balloon.shadow.size=15
 ide.expansion.hints.enabled=true
+ide.register.bundled.fonts=true
+ide.register.bundled.fonts.description=Disables automatic registration of bundled fonts: SourceCodePro, Inconsolata
 
 editor.balloonHints=true
 editor.mouseSelectionStateResetTimeout=1000
@@ -126,6 +143,8 @@
 ide.mac.file.chooser.native=true
 ide.mac.message.dialogs.as.sheets=true
 ide.mac.mountain.lion.notifications.enabled=true
+skip.untitled.windows.for.mac.messages=true
+skip.untitled.windows.for.mac.messages.description=Temporary key to test a fix for MacMessages
 ide.mac.inplaceDialogMnemonicsFix=true
 ide.mac.fix.dialog.showing=false
 ide.mac.hide.cursor.when.typing=true
@@ -332,4 +351,8 @@
 darcula.use.native.fonts.on.linux=true
 darcula.use.native.fonts.on.linux.description=If false, uses DejaVu Sans 13pt
 idea.4.5.laf.enabled=false
+show.all.look.and.feels=false
+show.all.look.and.feels.description=Make accessible all available Look and Feels
+cvs.roots.refresh.uses.vfs=true
+cvs.roots.refresh.uses.vfs.description=Should CVS roots refresh after update use VFS
 
diff --git a/platform/platform-resources-en/src/tips/EnterDirectoryInGotoFile.html b/platform/platform-resources-en/src/tips/EnterDirectoryInGotoFile.html
index 019b551..9d4739f 100644
--- a/platform/platform-resources-en/src/tips/EnterDirectoryInGotoFile.html
+++ b/platform/platform-resources-en/src/tips/EnterDirectoryInGotoFile.html
@@ -8,7 +8,7 @@
 <p>You can jump directly to any deeply buried file, if you press <span class="shortcut">&shortcut:GotoFile;</span>, and type just a couple
 of characters of the enclosing directories and file names: </p>
 
-      <p class="image"><img width="745" height="131" src="images_white/enterDirectory.png"></p>
+      <p class="image"><img width="745" height="131" src="images/enterDirectory.png"></p>
 
 <p>Use either a slash or a backslash as a delimiter.</p>
 
diff --git a/platform/platform-resources-en/src/tips/ImagesLookup.html b/platform/platform-resources-en/src/tips/ImagesLookup.html
index cb09ad4..1fa74ee 100644
--- a/platform/platform-resources-en/src/tips/ImagesLookup.html
+++ b/platform/platform-resources-en/src/tips/ImagesLookup.html
@@ -8,7 +8,7 @@
     <p>You can quickly view the image referenced at caret by using the
       <span class="">Quick Definition</span>
       (<span class="shortcut">&shortcut:QuickImplementations;</span>). The underlying image will be opened in a popup instead of a separate editor tab.</p>
-      <p class="image"><img width="365" height="208" src="images_white/image_lookup.png"></p>
+      <p class="image"><img width="365" height="208" src="images/image_lookup.png"></p>
 
 
 
diff --git a/platform/platform-resources-en/src/tips/RenameCssSelector.html b/platform/platform-resources-en/src/tips/RenameCssSelector.html
index 6c377a9..12e4b7a 100644
--- a/platform/platform-resources-en/src/tips/RenameCssSelector.html
+++ b/platform/platform-resources-en/src/tips/RenameCssSelector.html
@@ -8,7 +8,6 @@
     <p>It is possible to rename CSS selectors directly from HTML. Position the caret at
       the selector to be renamed and press <span class="shortcut">&shortcut:RenameElement;</span>
       (<span class="control">Refactor | Rename</span>).</p>
-      <p class="image"><img src="images/rename_css_selector.gif"></p>
 
 
 
diff --git a/platform/platform-resources-en/src/tips/ShowUsages.html b/platform/platform-resources-en/src/tips/ShowUsages.html
index e85caa8..29b96f9a 100644
--- a/platform/platform-resources-en/src/tips/ShowUsages.html
+++ b/platform/platform-resources-en/src/tips/ShowUsages.html
@@ -9,7 +9,7 @@
         project, and quickly jump to the selected usage. To do that, place the caret at the symbol's name or at its usage
         in code and press <span class="shortcut">&shortcut:ShowUsages;</span> (<span class="control">Edit | Find | Show Usages</span>
       in the main menu), scroll the list and click the desired usage.</p>
-        <p class="image"><img width="957" height="139" src="images_white/showUsages.png"/></p>
+        <p class="image"><img width="957" height="139" src="images/showUsages.png"/></p>
 
 
 
diff --git a/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates.png b/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates.png
index cb058f4..0ccfd1a 100644
--- a/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates.png
+++ b/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index 8e9f756a..b9ce98c 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates@2x_dark.png b/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates@2x_dark.png
index 5e520b9..9eb4c3b 100644
--- a/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates_dark.png b/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates_dark.png
index 51a1ef2..5be7045 100644
--- a/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates_dark.png
+++ b/platform/platform-resources-en/src/tips/images/SpeedSearchInLiveTemplates_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup.png b/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup.png
index a8a2cd1..28eb2ce 100644
--- a/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup.png
+++ b/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index 5ae110e..421f7d4 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup@2x_dark.png b/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup@2x_dark.png
index 601ba4d..9c5bf3b 100644
--- a/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup_dark.png b/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup_dark.png
index 25550a4..c2e8c4d 100644
--- a/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup_dark.png
+++ b/platform/platform-resources-en/src/tips/images/ctrl_shift_in_lookup_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/dragToOpen.png b/platform/platform-resources-en/src/tips/images/dragToOpen.png
index ff22c9e..21d6a9d 100644
--- a/platform/platform-resources-en/src/tips/images/dragToOpen.png
+++ b/platform/platform-resources-en/src/tips/images/dragToOpen.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..bb37b81
--- /dev/null
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/dragToOpen@2x_dark.png b/platform/platform-resources-en/src/tips/images/dragToOpen@2x_dark.png
new file mode 100644
index 0000000..20afd75
--- /dev/null
+++ b/platform/platform-resources-en/src/tips/images/dragToOpen@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/dragToOpen_dark.png b/platform/platform-resources-en/src/tips/images/dragToOpen_dark.png
new file mode 100644
index 0000000..76e5239
--- /dev/null
+++ b/platform/platform-resources-en/src/tips/images/dragToOpen_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/editregexp.png b/platform/platform-resources-en/src/tips/images/editregexp.png
index eddda9d..b9ce19d 100644
--- a/platform/platform-resources-en/src/tips/images/editregexp.png
+++ b/platform/platform-resources-en/src/tips/images/editregexp.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index c21a69b..45aa9b2 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/editregexp@2x_dark.png b/platform/platform-resources-en/src/tips/images/editregexp@2x_dark.png
index 9333c34..844e248 100644
--- a/platform/platform-resources-en/src/tips/images/editregexp@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/editregexp@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/editregexp_dark.png b/platform/platform-resources-en/src/tips/images/editregexp_dark.png
index 2f674fc..0fe4836 100644
--- a/platform/platform-resources-en/src/tips/images/editregexp_dark.png
+++ b/platform/platform-resources-en/src/tips/images/editregexp_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/gotoFileLineNumber.png b/platform/platform-resources-en/src/tips/images/gotoFileLineNumber.png
index 974b994..f9774a83 100644
--- a/platform/platform-resources-en/src/tips/images/gotoFileLineNumber.png
+++ b/platform/platform-resources-en/src/tips/images/gotoFileLineNumber.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index 5edf20a..ff17198 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/gotoFileLineNumber@2x_dark.png b/platform/platform-resources-en/src/tips/images/gotoFileLineNumber@2x_dark.png
index 99d6cf0..774aced 100644
--- a/platform/platform-resources-en/src/tips/images/gotoFileLineNumber@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/gotoFileLineNumber@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/gotoFileLineNumber_dark.png b/platform/platform-resources-en/src/tips/images/gotoFileLineNumber_dark.png
index 7b3eb7d..450172d 100644
--- a/platform/platform-resources-en/src/tips/images/gotoFileLineNumber_dark.png
+++ b/platform/platform-resources-en/src/tips/images/gotoFileLineNumber_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/goto_class.png b/platform/platform-resources-en/src/tips/images/goto_class.png
index 2e26922..5b8f5f3 100644
--- a/platform/platform-resources-en/src/tips/images/goto_class.png
+++ b/platform/platform-resources-en/src/tips/images/goto_class.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index b7109b4..4a94ad7 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/goto_class@2x_dark.png b/platform/platform-resources-en/src/tips/images/goto_class@2x_dark.png
index 2542a09..4de50db 100644
--- a/platform/platform-resources-en/src/tips/images/goto_class@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/goto_class@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/goto_class_dark.png b/platform/platform-resources-en/src/tips/images/goto_class_dark.png
index 7b4172b..1b79f39 100644
--- a/platform/platform-resources-en/src/tips/images/goto_class_dark.png
+++ b/platform/platform-resources-en/src/tips/images/goto_class_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/param_info.png b/platform/platform-resources-en/src/tips/images/param_info.png
index a787e9c..62331d9 100644
--- a/platform/platform-resources-en/src/tips/images/param_info.png
+++ b/platform/platform-resources-en/src/tips/images/param_info.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index 6b8da11..7dc0d13 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/param_info@2x_dark.png b/platform/platform-resources-en/src/tips/images/param_info@2x_dark.png
index 5a1455c..1c34eab 100644
--- a/platform/platform-resources-en/src/tips/images/param_info@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/param_info@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/param_info_dark.png b/platform/platform-resources-en/src/tips/images/param_info_dark.png
index 537f5cf..5f254cf 100644
--- a/platform/platform-resources-en/src/tips/images/param_info_dark.png
+++ b/platform/platform-resources-en/src/tips/images/param_info_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/rename.png b/platform/platform-resources-en/src/tips/images/rename.png
index 46c1249..f289bcc 100644
--- a/platform/platform-resources-en/src/tips/images/rename.png
+++ b/platform/platform-resources-en/src/tips/images/rename.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index b529161..1fbb78b 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/rename@2x_dark.png b/platform/platform-resources-en/src/tips/images/rename@2x_dark.png
index ba31382..a4b1204 100644
--- a/platform/platform-resources-en/src/tips/images/rename@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/rename@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/rename_dark.png b/platform/platform-resources-en/src/tips/images/rename_dark.png
index c4ddde2..1462047 100644
--- a/platform/platform-resources-en/src/tips/images/rename_dark.png
+++ b/platform/platform-resources-en/src/tips/images/rename_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/showUsages.png b/platform/platform-resources-en/src/tips/images/showUsages.png
index 7b2429d..496d8b2 100644
--- a/platform/platform-resources-en/src/tips/images/showUsages.png
+++ b/platform/platform-resources-en/src/tips/images/showUsages.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index c1bba73..ffb9756 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/showUsages@2x_dark.png b/platform/platform-resources-en/src/tips/images/showUsages@2x_dark.png
index dd9ae78..1258f42 100644
--- a/platform/platform-resources-en/src/tips/images/showUsages@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/showUsages@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/showUsages_dark.png b/platform/platform-resources-en/src/tips/images/showUsages_dark.png
index dd96a29..0503897 100644
--- a/platform/platform-resources-en/src/tips/images/showUsages_dark.png
+++ b/platform/platform-resources-en/src/tips/images/showUsages_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/speed_search.png b/platform/platform-resources-en/src/tips/images/speed_search.png
index 38e761b..6b33443 100644
--- a/platform/platform-resources-en/src/tips/images/speed_search.png
+++ b/platform/platform-resources-en/src/tips/images/speed_search.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index 1b5b9007..1cbb40c 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/speed_search@2x_dark.png b/platform/platform-resources-en/src/tips/images/speed_search@2x_dark.png
index 5c33c82..4a00def 100644
--- a/platform/platform-resources-en/src/tips/images/speed_search@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/speed_search@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/speed_search_dark.png b/platform/platform-resources-en/src/tips/images/speed_search_dark.png
index 3a0f0ec..86642ce 100644
--- a/platform/platform-resources-en/src/tips/images/speed_search_dark.png
+++ b/platform/platform-resources-en/src/tips/images/speed_search_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/switcher.png b/platform/platform-resources-en/src/tips/images/switcher.png
index 416d387..569bb20 100644
--- a/platform/platform-resources-en/src/tips/images/switcher.png
+++ b/platform/platform-resources-en/src/tips/images/switcher.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
index a4c85c09..052e8af 100644
--- a/platform/platform-resources-en/src/tips/images/[email protected]
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/switcher@2x_dark.png b/platform/platform-resources-en/src/tips/images/switcher@2x_dark.png
index 6d3af7b..dacb855 100644
--- a/platform/platform-resources-en/src/tips/images/switcher@2x_dark.png
+++ b/platform/platform-resources-en/src/tips/images/switcher@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/switcher_dark.png b/platform/platform-resources-en/src/tips/images/switcher_dark.png
index dafdde8..b320d0a 100644
--- a/platform/platform-resources-en/src/tips/images/switcher_dark.png
+++ b/platform/platform-resources-en/src/tips/images/switcher_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/tagNameCompletion.png b/platform/platform-resources-en/src/tips/images/tagNameCompletion.png
index f934f53..e711aa8 100644
--- a/platform/platform-resources-en/src/tips/images/tagNameCompletion.png
+++ b/platform/platform-resources-en/src/tips/images/tagNameCompletion.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/[email protected] b/platform/platform-resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..2942719
--- /dev/null
+++ b/platform/platform-resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/tagNameCompletion@2x_dark.png b/platform/platform-resources-en/src/tips/images/tagNameCompletion@2x_dark.png
new file mode 100644
index 0000000..71bd316
--- /dev/null
+++ b/platform/platform-resources-en/src/tips/images/tagNameCompletion@2x_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/images/tagNameCompletion_dark.png b/platform/platform-resources-en/src/tips/images/tagNameCompletion_dark.png
new file mode 100644
index 0000000..1e6971d
--- /dev/null
+++ b/platform/platform-resources-en/src/tips/images/tagNameCompletion_dark.png
Binary files differ
diff --git a/platform/platform-resources-en/src/tips/moveFileToChangelist.html b/platform/platform-resources-en/src/tips/moveFileToChangelist.html
index 6d893f2..a4fc64a 100644
--- a/platform/platform-resources-en/src/tips/moveFileToChangelist.html
+++ b/platform/platform-resources-en/src/tips/moveFileToChangelist.html
@@ -10,7 +10,7 @@
 <span class="control">Move to Changelist</span> on the file context menu in the Changes tool window:
 </p>
 
-<p class="image"><img width="406" height="78" src="images_white/move_to_changelist.png"></p>
+<p class="image"><img width="406" height="78" src="images/move_to_changelist.png"></p>
 
 </body>
 </html>
diff --git a/platform/platform-resources/src/META-INF/VcsExtensions.xml b/platform/platform-resources/src/META-INF/VcsExtensions.xml
index fcc2dce..b2d0320 100644
--- a/platform/platform-resources/src/META-INF/VcsExtensions.xml
+++ b/platform/platform-resources/src/META-INF/VcsExtensions.xml
@@ -39,6 +39,7 @@
                         serviceImplementation="com.intellij.openapi.vcs.impl.CheckinHandlersManagerImpl"/>
     <pathMacroFilter implementation="com.intellij.openapi.vcs.VcsPathMacroFilter"/>
     <search.topHitProvider implementation="com.intellij.openapi.vcs.actions.VcsTopHitProvider"/>
+    <actionPromoter implementation="com.intellij.openapi.vcs.actions.VcsActionPromoter"/>
   </extensions>
 </idea-plugin>
 
diff --git a/platform/platform-resources/src/fonts/SourceCodePro-Bold.ttf b/platform/platform-resources/src/fonts/SourceCodePro-Bold.ttf
index 5f39b69..a56f1fa 100644
--- a/platform/platform-resources/src/fonts/SourceCodePro-Bold.ttf
+++ b/platform/platform-resources/src/fonts/SourceCodePro-Bold.ttf
Binary files differ
diff --git a/platform/platform-resources/src/fonts/SourceCodePro-Regular.ttf b/platform/platform-resources/src/fonts/SourceCodePro-Regular.ttf
index 6cbdd36..b2cff92 100644
--- a/platform/platform-resources/src/fonts/SourceCodePro-Regular.ttf
+++ b/platform/platform-resources/src/fonts/SourceCodePro-Regular.ttf
Binary files differ
diff --git a/platform/platform-resources/src/idea/LangActions.xml b/platform/platform-resources/src/idea/LangActions.xml
index 2fdff09..bdaf6c8 100644
--- a/platform/platform-resources/src/idea/LangActions.xml
+++ b/platform/platform-resources/src/idea/LangActions.xml
@@ -353,10 +353,14 @@
       <add-to-group group-id="MainToolBar" relative-to-action="Forward" anchor="after"/>
     </group>
 
+    <group id="NavBarToolBarOthers"/>
     <group id="NavBarToolBar">
       <reference ref="ToolbarRunGroup"/>
       <separator/>
-      <reference ref="MainToolBarSettings"/>
+      <reference ref="NavBarVcsGroup"/>
+      <separator/>
+      <reference id="NavBarToolBarOthers"/>
+      <separator/>
     </group>
 
     <group id="Bookmarks">
diff --git a/platform/platform-resources/src/idea/PlatformActions.xml b/platform/platform-resources/src/idea/PlatformActions.xml
index 2549f24..f5ac0d5 100644
--- a/platform/platform-resources/src/idea/PlatformActions.xml
+++ b/platform/platform-resources/src/idea/PlatformActions.xml
@@ -444,6 +444,8 @@
       <reference ref="HelpTopics"/>
     </group>
 
+    <group id="NavBarVcsGroup"/>
+
     <group id="EditorPopupMenu" configurable="true">
       <reference ref="$Cut"/>
       <reference ref="$Copy"/>
diff --git a/platform/platform-resources/src/idea/VcsActions.xml b/platform/platform-resources/src/idea/VcsActions.xml
index d816472..724b7eb 100644
--- a/platform/platform-resources/src/idea/VcsActions.xml
+++ b/platform/platform-resources/src/idea/VcsActions.xml
@@ -232,6 +232,15 @@
       <add-to-group group-id="MainToolBarSettings" relative-to-action="ShowSettings" anchor="before"/>
     </group>
 
+    <group id="VcsNavBarToobarActions">
+      <reference ref="Vcs.UpdateProject"/>
+      <reference ref="CheckinProject"/>
+      <reference ref="Vcs.ShowTabbedFileHistory"/>
+      <reference ref="ChangesView.Rollback"/>
+      <separator/>
+      <add-to-group group-id="NavBarVcsGroup" anchor="first"/>
+    </group>
+
     <!-- Window -->
     <action id="CloseAllUnmodifiedEditors" class="com.intellij.ide.actions.CloseAllUnmodifiedEditorsAction">
       <add-to-group group-id="CloseEditorsGroup" anchor="before" relative-to-action="CloseAllUnpinnedEditors"/>
diff --git a/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/KillToWordEndActionTest.java b/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/KillToWordEndActionTest.java
index 83340d0..31b8aaa 100644
--- a/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/KillToWordEndActionTest.java
+++ b/platform/platform-tests/testSrc/com/intellij/openapi/editor/actions/KillToWordEndActionTest.java
@@ -108,4 +108,17 @@
     Object string = contents.getTransferData(DataFlavor.stringFlavor);
     assertEquals(" second", string);
   }
+
+  public void testSubsequentKills() throws Exception {
+    String text = "<caret>first second third";
+    configureFromFileText(getTestName(false) + ".txt", text);
+    killToWordEnd();
+    killToWordEnd();
+    checkResultByText(" third");
+
+    Transferable contents = CopyPasteManager.getInstance().getContents();
+    assertTrue(contents instanceof KillRingTransferable);
+    Object string = contents.getTransferData(DataFlavor.stringFlavor);
+    assertEquals("first second", string);
+  }
 }
diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java
index 721c6d1..80998a0 100644
--- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java
+++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/GeneralIdBasedToSMTRunnerEventsConvertor.java
@@ -51,7 +51,7 @@
   public GeneralIdBasedToSMTRunnerEventsConvertor(@NotNull SMTestProxy.SMRootTestProxy testsRootProxy,
                                                   @NotNull String testFrameworkName) {
     myTestsRootProxy = testsRootProxy;
-    myTestsRootNode = new Node(0, null, testsRootProxy);
+    myTestsRootNode = new Node(0, null, testsRootProxy, State.RUNNING);
     myTestFrameworkName = testFrameworkName;
     myNodeByIdMap.put(myTestsRootNode.getId(), myTestsRootNode);
     myRunningNodes.add(myTestsRootNode);
@@ -133,6 +133,23 @@
   }
 
   private void doStartNode(@NotNull BaseStartedNodeEvent startedNodeEvent, boolean suite) {
+    Node node = findNode(startedNodeEvent);
+    if (node != null) {
+      if (node.getState() == State.REGISTERED && startedNodeEvent.isRunning()) {
+        node.setState(State.RUNNING);
+        node.getProxy().setStarted();
+        if (suite) {
+          fireOnSuiteStarted(node.getProxy());
+        } else {
+          fireOnTestStarted(node.getProxy());
+        }
+      }
+      else {
+        logProblem(startedNodeEvent + " has been already started: " + node + "!");
+      }
+      return;
+    }
+
     Node parentNode = findValidParentNode(startedNodeEvent);
     if (parentNode == null) {
       return;
@@ -141,12 +158,6 @@
     if (!validateNodeId(startedNodeEvent)) {
       return;
     }
-    int nodeId = startedNodeEvent.getId();
-    Node childNode = myNodeByIdMap.get(nodeId);
-    if (childNode != null) {
-      logProblem(startedNodeEvent + " has been already started: " + childNode + "!");
-      return;
-    }
 
     String nodeName = startedNodeEvent.getName();
     SMTestProxy childProxy = new SMTestProxy(nodeName, suite, startedNodeEvent.getLocationUrl(), true);
@@ -158,20 +169,23 @@
         childProxy.setPreferredPrinter(printer);
       }
     }
-    childNode = new Node(startedNodeEvent.getId(), parentNode, childProxy);
-    myNodeByIdMap.put(nodeId, childNode);
-    myRunningNodes.add(childNode);
+    State initialState = startedNodeEvent.isRunning() ? State.RUNNING : State.REGISTERED;
+    node = new Node(startedNodeEvent.getId(), parentNode, childProxy, initialState);
+    myNodeByIdMap.put(startedNodeEvent.getId(), node);
+    myRunningNodes.add(node);
     if (myLocator != null) {
       childProxy.setLocator(myLocator);
     }
     parentNode.getProxy().addChild(childProxy);
 
-    // progress started
-    childProxy.setStarted();
-    if (suite) {
-      fireOnSuiteStarted(childProxy);
-    } else {
-      fireOnTestStarted(childProxy);
+    if (node.getState() == State.RUNNING) {
+      // progress started
+      childProxy.setStarted();
+      if (suite) {
+        fireOnSuiteStarted(childProxy);
+      } else {
+        fireOnTestStarted(childProxy);
+      }
     }
   }
 
@@ -179,16 +193,16 @@
   private Node findValidParentNode(@NotNull BaseStartedNodeEvent startedNodeEvent) {
     int parentId = startedNodeEvent.getParentId();
     if (parentId < 0) {
-      logProblem("Parent node id should be non-negative: " + startedNodeEvent + ".");
+      logProblem("Parent node id should be non-negative: " + startedNodeEvent + ".", true);
       return null;
     }
     Node parentNode = myNodeByIdMap.get(startedNodeEvent.getParentId());
     if (parentNode == null) {
-      logProblem("Parent node is undefined for " + startedNodeEvent + ".");
+      logProblem("Parent node is undefined for " + startedNodeEvent + ".", true);
       return null;
     }
-    if (parentNode.getState() != State.RUNNING) {
-      logProblem("Parent node should be running: " + parentNode + ", " + startedNodeEvent);
+    if (parentNode.getState() != State.REGISTERED && parentNode.getState() != State.RUNNING) {
+      logProblem("Parent node should be registered or running: " + parentNode + ", " + startedNodeEvent);
       return null;
     }
     return parentNode;
@@ -367,7 +381,7 @@
   private boolean validateNodeId(@NotNull TreeNodeEvent treeNodeEvent) {
     int nodeId = treeNodeEvent.getId();
     if (nodeId <= 0) {
-      logProblem("Node id should be positive: " + treeNodeEvent + ".");
+      logProblem("Node id should be positive: " + treeNodeEvent + ".", true);
       return false;
     }
     return true;
@@ -535,43 +549,36 @@
     return pathToRoot1.subList(pathToRoot1.size() - commonSize, pathToRoot1.size());
   }
 
-  private static String getTestFrameworkPrefix(@NotNull String testFrameworkName) {
-    return "[" + testFrameworkName + "] ";
-  }
-
   private void logProblem(@NotNull String msg) {
-    logProblem(LOG, msg, myTestFrameworkName);
+    logProblem(msg, SMTestRunnerConnectionUtil.isInDebugMode());
   }
 
-  private static void logProblem(@NotNull Logger log, @NotNull String msg, @NotNull String testFrameworkName) {
-    logProblem(log, msg, SMTestRunnerConnectionUtil.isInDebugMode(), testFrameworkName);
-  }
-
-  private static void logProblem(@NotNull Logger log, @NotNull String msg, boolean throwError, @NotNull String testFrameworkName) {
-    final String text = getTestFrameworkPrefix(testFrameworkName) + msg;
+  private void logProblem(@NotNull String msg, boolean throwError) {
+    final String text = "[" + myTestFrameworkName + "] " + msg;
     if (throwError) {
-      log.error(text);
+      LOG.error(text);
     }
     else {
-      log.warn(text);
+      LOG.warn(text);
     }
   }
 
   private enum State {
-    RUNNING, FINISHED, FAILED, IGNORED
+    REGISTERED, RUNNING, FINISHED, FAILED, IGNORED
   }
 
   private static class Node {
     private final int myId;
     private final Node myParentNode;
     private final SMTestProxy myProxy;
-    private State myState = State.RUNNING;
+    private State myState;
     private int myRunningChildCount = 0;
 
-    Node(int id, @Nullable Node parentNode, @NotNull SMTestProxy proxy) {
+    Node(int id, @Nullable Node parentNode, @NotNull SMTestProxy proxy, @NotNull State initialState) {
       myId = id;
       myParentNode = parentNode;
       myProxy = proxy;
+      myState = initialState;
       if (myParentNode != null) {
         myParentNode.myRunningChildCount++;
       }
@@ -596,15 +603,21 @@
       return myState;
     }
 
-    public void setState(@NotNull State state) {
-      if (myState == State.RUNNING && state != State.RUNNING) {
-        if (myParentNode != null) {
-          myParentNode.myRunningChildCount--;
-        }
-      } else {
-        throw new RuntimeException("Attempt to change state from " + myState + " to " + state + ":" + toString());
+    public void setState(@NotNull State newState) {
+      boolean accepted = false;
+      if (myState == State.REGISTERED) {
+        accepted = newState != State.REGISTERED;
       }
-      myState = state;
+      else if (myState == State.RUNNING) {
+        accepted = newState != State.REGISTERED && newState != State.RUNNING;
+      }
+      if (myParentNode != null && newState != State.REGISTERED && newState != State.RUNNING) {
+        myParentNode.myRunningChildCount--;
+      }
+      if (!accepted) {
+        throw new RuntimeException("Attempt to change state from " + myState + " to " + newState + ":" + toString());
+      }
+      myState = newState;
     }
 
     @Override
diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/BaseStartedNodeEvent.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/BaseStartedNodeEvent.java
index 8d597ec..0146405 100644
--- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/BaseStartedNodeEvent.java
+++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/BaseStartedNodeEvent.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.execution.testframework.sm.runner.events;
 
+import com.intellij.openapi.util.text.StringUtil;
 import jetbrains.buildServer.messages.serviceMessages.MessageWithAttributes;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -28,28 +29,21 @@
   private final String myLocationUrl;
   private final String myNodeType;
   private final String myNodeArgs;
+  private final boolean myRunning;
 
-  protected BaseStartedNodeEvent(@NotNull String name,
+  protected BaseStartedNodeEvent(@Nullable String name,
                                  int id,
                                  int parentId,
                                  @Nullable final String locationUrl,
                                  @Nullable String nodeType,
-                                 @Nullable String nodeArgs) {
+                                 @Nullable String nodeArgs,
+                                 boolean running) {
     super(name, id);
     myParentId = parentId;
     myLocationUrl = locationUrl;
     myNodeType = nodeType;
     myNodeArgs = nodeArgs;
-    validate();
-  }
-
-  private void validate() {
-    if (myParentId < -1) {
-      fail("parentId should be greater than -2");
-    }
-    if (getId() == -1 ^ myParentId == -1) {
-      fail("id and parentId should be -1 or non-negative");
-    }
+    myRunning = running;
   }
 
   /**
@@ -74,10 +68,15 @@
     return myNodeArgs;
   }
 
+  public boolean isRunning() {
+    return myRunning;
+  }
+
   @Override
   protected void appendToStringInfo(@NotNull StringBuilder buf) {
     append(buf, "parentId", myParentId);
     append(buf, "locationUrl", myLocationUrl);
+    append(buf, "running", myRunning);
   }
 
   public static int getParentNodeId(@NotNull MessageWithAttributes message) {
@@ -94,4 +93,13 @@
     return message.getAttributes().get("nodeArgs");
   }
 
+  public static boolean isRunning(@NotNull MessageWithAttributes message) {
+    String runningStr = message.getAttributes().get("running");
+    if (StringUtil.isEmpty(runningStr)) {
+      // old behavior preserved
+      return true;
+    }
+    return Boolean.parseBoolean(runningStr);
+  }
+
 }
diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestStartedEvent.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestStartedEvent.java
index c1e15f8..2182a35 100644
--- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestStartedEvent.java
+++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestStartedEvent.java
@@ -31,10 +31,11 @@
           getParentNodeId(testStarted),
           locationUrl,
           BaseStartedNodeEvent.getNodeType(testStarted),
-          BaseStartedNodeEvent.getNodeArgs(testStarted));
+          BaseStartedNodeEvent.getNodeArgs(testStarted),
+          BaseStartedNodeEvent.isRunning(testStarted));
   }
 
   public TestStartedEvent(@NotNull String name, @Nullable String locationUrl) {
-    super(name, -1, -1, locationUrl, null, null);
+    super(name, -1, -1, locationUrl, null, null, true);
   }
 }
diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestSuiteStartedEvent.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestSuiteStartedEvent.java
index 89b279e7a..c9f5008e 100644
--- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestSuiteStartedEvent.java
+++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/events/TestSuiteStartedEvent.java
@@ -31,11 +31,12 @@
           getParentNodeId(suiteStarted),
           locationUrl,
           BaseStartedNodeEvent.getNodeType(suiteStarted),
-          BaseStartedNodeEvent.getNodeArgs(suiteStarted));
+          BaseStartedNodeEvent.getNodeArgs(suiteStarted),
+          BaseStartedNodeEvent.isRunning(suiteStarted));
   }
 
   public TestSuiteStartedEvent(@NotNull String name, @Nullable String locationUrl) {
-    super(name, -1, -1, locationUrl, null, null);
+    super(name, -1, -1, locationUrl, null, null, true);
   }
 
 }
diff --git a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java
index a590feb..b2ea380 100644
--- a/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java
+++ b/platform/smRunner/src/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsForm.java
@@ -77,10 +77,11 @@
 
   private final Project myProject;
 
-  private int myTestsCurrentCount;
-  private int myTestsTotal = 0;
-  private int myTestsFailuresCount;
-  private boolean myContainsIgnoredTests;
+  private int myTotalTestCount = 0;
+  private int myStartedTestCount = 0;
+  private int myFinishedTestCount = 0;
+  private int myFailedTestCount = 0;
+  private int myIgnoredTestCount = 0;
   private long myStartTime;
   private long myEndTime;
   private StatisticsPanel myStatisticsPane;
@@ -230,8 +231,8 @@
   public void onTestingFinished(@NotNull SMTestProxy.SMRootTestProxy testsRoot) {
     myEndTime = System.currentTimeMillis();
 
-    if (myTestsTotal == 0) {
-      myTestsTotal = myTestsCurrentCount;
+    if (myTotalTestCount == 0) {
+      myTotalTestCount = myStartedTestCount;
       myStatusLine.setFraction(1);
     }
 
@@ -262,15 +263,13 @@
    * @param testProxy Proxy
    */
   public void onTestStarted(@NotNull final SMTestProxy testProxy) {
-    updateCountersAndProgressOnTestStarted(false);
-
+    updateOnTestStarted(false);
     _addTestOrSuite(testProxy);
-
     fireOnTestNodeAdded(testProxy);
   }
 
   public void onTestFailed(@NotNull final SMTestProxy test) {
-    updateCountersAndProgressOnTestFailed(false);
+    updateOnTestFailed(false);
     updateIconProgress();
   }
 
@@ -295,15 +294,15 @@
   }
 
   public void onCustomProgressTestStarted() {
-    updateCountersAndProgressOnTestStarted(true);
+    updateOnTestStarted(true);
   }
 
   public void onCustomProgressTestFailed() {
-    updateCountersAndProgressOnTestFailed(true);
+    updateOnTestFailed(true);
   }
 
   public void onTestFinished(@NotNull final SMTestProxy test) {
-    //Do nothing
+    updateOnTestFinished(false);
     updateIconProgress();
   }
 
@@ -406,22 +405,30 @@
     }
   }
 
-  protected int getTestsCurrentCount() {
-    return myTestsCurrentCount;
+  protected int getTotalTestCount() {
+    return myTotalTestCount;
   }
 
-  protected int getTestsFailuresCount() {
-    return myTestsFailuresCount;
+  protected int getStartedTestCount() {
+    return myStartedTestCount;
+  }
+
+  protected int getFinishedTestCount() {
+    return myFinishedTestCount;
+  }
+
+  protected int getFailedTestCount() {
+    return myFailedTestCount;
+  }
+
+  protected int getIgnoredTestCount() {
+    return myIgnoredTestCount;
   }
 
   protected Color getTestsStatusColor() {
     return myStatusLine.getStatusColor();
   }
 
-  protected int getTestsTotal() {
-    return myTestsTotal;
-  }
-
   public Set<String> getMentionedCategories() {
     return myMentionedCategories;
   }
@@ -480,15 +487,15 @@
   }
 
   private void updateStatusLabel(final boolean testingFinished) {
-    if (myTestsFailuresCount > 0) {
+    if (myFailedTestCount > 0) {
       myStatusLine.setStatusColor(ColorProgressBar.RED);
     }
-    else if (myContainsIgnoredTests) {
+    else if (myIgnoredTestCount > 0) {
       myStatusLine.setStatusColor(DARK_YELLOW);
     }
 
     if (testingFinished) {
-      if (myTestsTotal == 0) {
+      if (myTotalTestCount == 0) {
         myStatusLine.setStatusColor(myTestsRootNode.wasLaunched() || !myTestsRootNode.isTestsReporterAttached()
                                     ? JBColor.LIGHT_GRAY
                                     : ColorProgressBar.RED);
@@ -500,8 +507,8 @@
     // initializing will be "launchedAndFinished"
     final boolean launchedAndFinished = myTestsRootNode.wasLaunched() && !myTestsRootNode.isInProgress();
     myStatusLine.setText(TestsPresentationUtil.getProgressStatus_Text(myStartTime, myEndTime,
-                                                                      myTestsTotal, myTestsCurrentCount,
-                                                                      myTestsFailuresCount, myMentionedCategories,
+                                                                      myTotalTestCount, myFinishedTestCount,
+                                                                      myFailedTestCount, myMentionedCategories,
                                                                       launchedAndFinished));
   }
 
@@ -513,10 +520,16 @@
   }
 
   private void updateIconProgress() {
-    final boolean isIndeterminate = myTestsTotal == 0;
-    final int total = isIndeterminate ? 2 : myTestsTotal;
-    final int count = isIndeterminate ? 1 : myTestsCurrentCount;
-    TestsUIUtil.showIconProgress(myProject, count, total, myTestsFailuresCount);
+    final int totalTestCount, doneTestCount;
+    if (myTotalTestCount == 0) {
+      totalTestCount = 2;
+      doneTestCount = 1;
+    }
+    else {
+      totalTestCount = myTotalTestCount;
+      doneTestCount = myFinishedTestCount + myFailedTestCount + myIgnoredTestCount;
+    }
+    TestsUIUtil.showIconProgress(myProject, doneTestCount, totalTestCount, myFailedTestCount);
   }
 
   /**
@@ -557,47 +570,57 @@
 
     //This is for better support groups of TestSuites
     //Each group notifies about it's size
-    myTestsTotal += count;
+    myTotalTestCount += count;
     updateStatusLabel(false);
   }
 
-  private void updateCountersAndProgressOnTestStarted(final boolean isCustomMessage) {
+  private void updateOnTestStarted(final boolean isCustomMessage) {
     if (!isModeConsistent(isCustomMessage)) return;
 
     // for mixed tests results : mention category only if it contained tests
     myMentionedCategories
       .add(myCurrentCustomProgressCategory != null ? myCurrentCustomProgressCategory : TestsPresentationUtil.DEFAULT_TESTS_CATEGORY);
 
-    // Counters
-    myTestsCurrentCount++;
+    myStartedTestCount++;
 
     // fix total count if it is corrupted
     // but if test count wasn't set at all let's process such case separately
-    if (myTestsCurrentCount > myTestsTotal && myTestsTotal != 0) {
-      myTestsTotal = myTestsCurrentCount;
+    if (myStartedTestCount > myTotalTestCount && myTotalTestCount != 0) {
+      myTotalTestCount = myStartedTestCount;
     }
 
+    updateStatusLabel(false);
+  }
+
+  private void updateProgressOnTestDone() {
+    int doneTestCount = myFinishedTestCount + myFailedTestCount + myIgnoredTestCount;
     // update progress
-    if (myTestsTotal != 0) {
+    if (myTotalTestCount != 0) {
       // if total is set
-      myStatusLine.setFraction((double)myTestsCurrentCount / myTestsTotal);
+      myStatusLine.setFraction((double) doneTestCount / myTotalTestCount);
     }
     else {
       // if at least one test was launcher than just set progress in the middle to show user that tests are running
-      myStatusLine.setFraction(myTestsCurrentCount > 1 ? 0.5 : 0); // > 1 because count already ++
+      myStatusLine.setFraction(doneTestCount > 0 ? 0.5 : 0);
     }
+  }
+
+  private void updateOnTestFailed(final boolean isCustomMessage) {
+    if (!isModeConsistent(isCustomMessage)) return;
+    myFailedTestCount++;
+    updateProgressOnTestDone();
     updateStatusLabel(false);
   }
 
-  private void updateCountersAndProgressOnTestFailed(final boolean isCustomMessage) {
+  private void updateOnTestFinished(final boolean isCustomMessage) {
     if (!isModeConsistent(isCustomMessage)) return;
-
-    myTestsFailuresCount++;
-    updateStatusLabel(false);
+    myFinishedTestCount++;
+    updateProgressOnTestDone();
   }
 
   private void updateOnTestIgnored() {
-    myContainsIgnoredTests = true;
+    myIgnoredTestCount++;
+    updateProgressOnTestDone();
     updateStatusLabel(false);
   }
 
diff --git a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java
index 499b2e4..430ac8f 100644
--- a/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java
+++ b/platform/smRunner/testSrc/com/intellij/execution/testframework/sm/runner/ui/SMTestRunnerResultsFormTest.java
@@ -85,41 +85,41 @@
     myResultsViewer.onTestingStarted(myTestsRootNode);
 
     assertTrue(myResultsViewer.getStartTime() > 0);
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getFinishedTestCount());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
   }
 
   public void testOnTestStarted() {
     myResultsViewer.onTestStarted(createTestProxy("some_test", myTestsRootNode));
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
   }
 
   public void testCount() {
     myResultsViewer.onTestsCountInSuite(1);
 
-    assertEquals(1, myResultsViewer.getTestsTotal());
+    assertEquals(1, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test", myTestsRootNode));
-    assertEquals(1, myResultsViewer.getTestsTotal());
+    assertEquals(1, myResultsViewer.getTotalTestCount());
 
     // if exceeds - will be incremented
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
   }
 
   public void testCount_UnSet() {
     myResultsViewer.onTestStarted(createTestProxy("some_test", myTestsRootNode));
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
 
     // count will be updated only on tests finished if wasn't set
     myResultsViewer.onTestingFinished(myTestsRootNode);
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
   }
 
   public void testOnTestFailure() {
@@ -128,48 +128,49 @@
     myResultsViewer.onTestStarted(test);
     myResultsViewer.onTestFailed(test);
 
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getFailedTestCount());
+    assertEquals(1, myResultsViewer.getFailedTestCount());
   }
 
   public void testOnTestFinished() {
     final SMTestProxy test = createTestProxy("some_test", myTestsRootNode);
 
     myResultsViewer.onTestStarted(test);
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
 
     myResultsViewer.onTestFinished(test);
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getFinishedTestCount());
   }
 
   public void testOnTestsCountInSuite() {
     myResultsViewer.onTestsCountInSuite(200);
 
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
-    assertEquals(200, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getFinishedTestCount());
+    assertEquals(200, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestsCountInSuite(50);
-    assertEquals(250, myResultsViewer.getTestsTotal());
+    assertEquals(250, myResultsViewer.getTotalTestCount());
   }
 
   public void testOnTestStart_ChangeTotal() {
     myResultsViewer.onTestsCountInSuite(2);
 
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test3", myTestsRootNode));
-    assertEquals(3, myResultsViewer.getTestsTotal());
+    assertEquals(3, myResultsViewer.getTotalTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test4", myTestsRootNode));
-    assertEquals(4, myResultsViewer.getTestsTotal());
+    assertEquals(4, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestsCountInSuite(2);
     myResultsViewer.onTestStarted(createTestProxy("another_test1", myTestsRootNode));
-    assertEquals(6, myResultsViewer.getTestsTotal());
+    assertEquals(6, myResultsViewer.getTotalTestCount());
     myResultsViewer.onTestStarted(createTestProxy("another_test2", myTestsRootNode));
-    assertEquals(6, myResultsViewer.getTestsTotal());
+    assertEquals(6, myResultsViewer.getTotalTestCount());
     myResultsViewer.onTestStarted(createTestProxy("another_test3", myTestsRootNode));
-    assertEquals(7, myResultsViewer.getTestsTotal());
+    assertEquals(7, myResultsViewer.getTotalTestCount());
   }
 
   public void testOnFinishTesting_EndTime() {
@@ -178,9 +179,9 @@
   }
 
   public void testOnSuiteStarted() {
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
+    assertEquals(0, myResultsViewer.getFinishedTestCount());
     myResultsViewer.onSuiteStarted(createSuiteProxy(myTestsRootNode));
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
+    assertEquals(0, myResultsViewer.getFinishedTestCount());
   }
 
   public void testChangeSelectionAction() {
@@ -290,14 +291,14 @@
     myResultsViewer.onCustomProgressTestsCategory("foo", 4);
 
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
+    assertEquals(0, myResultsViewer.getFinishedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
   }
 
   public void testCustomProgress_MixedMde() {
@@ -305,29 +306,29 @@
     myResultsViewer.onCustomProgressTestsCategory("foo", 4);
 
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
+    assertEquals(0, myResultsViewer.getFinishedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
 
     // disable custom mode
     myResultsViewer.onCustomProgressTestsCategory(null, 0);
 
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(3, myResultsViewer.getTestsCurrentCount());
+    assertEquals(3, myResultsViewer.getStartedTestCount());
 
-    assertEquals(3, myResultsViewer.getTestsCurrentCount());
+    assertEquals(3, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(3, myResultsViewer.getTestsCurrentCount());
+    assertEquals(3, myResultsViewer.getStartedTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(4, myResultsViewer.getTestsCurrentCount());
+    assertEquals(4, myResultsViewer.getStartedTestCount());
   }
 
   public void testCustomProgress_EmptySuite() {
@@ -345,7 +346,7 @@
     myResultsViewer.onSuiteFinished(myTestsRootNode);
     
     myResultsViewer.onTestingFinished(myTestsRootNode);
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
     assertEquals(Color.LIGHT_GRAY, myResultsViewer.getTestsStatusColor());
   }
 
@@ -357,10 +358,10 @@
     myResultsViewer.onCustomProgressTestStarted();
 
     myResultsViewer.onTestFailed(test1);
-    assertEquals(0, myResultsViewer.getTestsFailuresCount());
+    assertEquals(0, myResultsViewer.getFailedTestCount());
 
     myResultsViewer.onCustomProgressTestFailed();
-    assertEquals(1, myResultsViewer.getTestsFailuresCount());
+    assertEquals(1, myResultsViewer.getFailedTestCount());
 
     assertEquals(ColorProgressBar.RED, myResultsViewer.getTestsStatusColor());
   }
@@ -371,8 +372,8 @@
     myResultsViewer.performUpdate();
     myResultsViewer.onTestIgnored(test1);
     myResultsViewer.performUpdate();
-    assertEquals(0, myResultsViewer.getTestsFailuresCount());
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(0, myResultsViewer.getFailedTestCount());
+    assertEquals(1, myResultsViewer.getIgnoredTestCount());
 
     assertEquals(SMTestRunnerResultsForm.DARK_YELLOW, myResultsViewer.getTestsStatusColor());
   }
@@ -421,55 +422,55 @@
   public void testCustomProgress_UnSetCount() {
     myResultsViewer.onCustomProgressTestsCategory("foo", 0);
 
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(0, myResultsViewer.getTestsTotal());
+    assertEquals(0, myResultsViewer.getTotalTestCount());
 
     // count will be updated only on tests finished if wasn't set
     myResultsViewer.onTestingFinished(myTestsRootNode);
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
   }
 
   public void testCustomProgress_IncreaseCount() {
     myResultsViewer.onCustomProgressTestsCategory("foo", 1);
 
-    assertEquals(1, myResultsViewer.getTestsTotal());
+    assertEquals(1, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(1, myResultsViewer.getTestsTotal());
+    assertEquals(1, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
   }
 
   public void testCustomProgress_IncreaseCount_MixedMode() {
     // custom mode
     myResultsViewer.onCustomProgressTestsCategory("foo", 1);
 
-    assertEquals(1, myResultsViewer.getTestsTotal());
+    assertEquals(1, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(1, myResultsViewer.getTestsTotal());
+    assertEquals(1, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
 
     // disable custom mode
     myResultsViewer.onCustomProgressTestsCategory(null, 0);
-    assertEquals(2, myResultsViewer.getTestsTotal());
+    assertEquals(2, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestsCountInSuite(1);
-    assertEquals(3, myResultsViewer.getTestsTotal());
+    assertEquals(3, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(3, myResultsViewer.getTestsTotal());
+    assertEquals(3, myResultsViewer.getTotalTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(4, myResultsViewer.getTestsTotal());
+    assertEquals(4, myResultsViewer.getTotalTestCount());
   }
 
   //TODO categories - mized
@@ -536,28 +537,28 @@
     myResultsViewer.onCustomProgressTestsCategory("foo", 4);
 
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(0, myResultsViewer.getTestsCurrentCount());
+    assertEquals(0, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
 
     myResultsViewer.onTestStarted(createTestProxy("some_test2", myTestsRootNode));
-    assertEquals(1, myResultsViewer.getTestsCurrentCount());
+    assertEquals(1, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
 
     // disable custom mode
     myResultsViewer.onCustomProgressTestsCategory(null, 0);
 
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(2, myResultsViewer.getTestsCurrentCount());
+    assertEquals(2, myResultsViewer.getStartedTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(3, myResultsViewer.getTestsCurrentCount());
+    assertEquals(3, myResultsViewer.getStartedTestCount());
 
-    assertEquals(3, myResultsViewer.getTestsCurrentCount());
+    assertEquals(3, myResultsViewer.getStartedTestCount());
     myResultsViewer.onCustomProgressTestStarted();
-    assertEquals(3, myResultsViewer.getTestsCurrentCount());
+    assertEquals(3, myResultsViewer.getStartedTestCount());
     myResultsViewer.onTestStarted(createTestProxy("some_test1", myTestsRootNode));
-    assertEquals(4, myResultsViewer.getTestsCurrentCount());
+    assertEquals(4, myResultsViewer.getStartedTestCount());
   }
 }
diff --git a/platform/testFramework/src/com/intellij/mock/Mock.java b/platform/testFramework/src/com/intellij/mock/Mock.java
index 9e2a14b..87e13ad 100644
--- a/platform/testFramework/src/com/intellij/mock/Mock.java
+++ b/platform/testFramework/src/com/intellij/mock/Mock.java
@@ -78,12 +78,7 @@
     @Override
     @NotNull
     public FileEditorState getState(@NotNull FileEditorStateLevel level) {
-      return new FileEditorState() {
-            @Override
-            public boolean canBeMergedWith(FileEditorState fileEditorState, FileEditorStateLevel fileEditorStateLevel) {
-                return false;
-            }
-        };
+      return FileEditorState.INSTANCE;
     }
 
     @Override
@@ -316,10 +311,10 @@
 
     @Override
     @NotNull
-    public Pair<FileEditor[],FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file,
-                                                                         boolean focusEditor,
-                                                                         boolean searchForSplitter) {
-      return Pair.create (new FileEditor[0], new FileEditorProvider [0]);
+    public Pair<FileEditor[], FileEditorProvider[]> openFileWithProviders(@NotNull VirtualFile file,
+                                                                          boolean focusEditor,
+                                                                          boolean searchForSplitter) {
+      return Pair.create(new FileEditor[0], new FileEditorProvider[0]);
     }
 
     @Override
@@ -387,11 +382,11 @@
     }
 
     @Override
-    public void removeEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComoponent) {
+    public void removeEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComponent) {
     }
 
     @Override
-    public void showEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComoponent) {
+    public void showEditorAnnotation(@NotNull FileEditor editor, @NotNull JComponent annotationComponent) {
     }
 
     @Override
diff --git a/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestUtil.java b/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestUtil.java
index dd06c0d..d73a4d8 100644
--- a/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestUtil.java
+++ b/platform/testFramework/src/com/intellij/testFramework/fixtures/CodeInsightTestUtil.java
@@ -72,7 +72,7 @@
     return null;
   }
 
-  public static void doIntentionTest(CodeInsightTestFixture fixture, @NonNls String file, @NonNls String actionText) throws Throwable {
+  public static void doIntentionTest(CodeInsightTestFixture fixture, @NonNls String file, @NonNls String actionText) {
     doIntentionTest(fixture, actionText, file + ".xml", file + "_after.xml");
   }
 
diff --git a/platform/testFramework/src/com/intellij/testFramework/utils/parameterInfo/MockParameterInfoUIContext.java b/platform/testFramework/src/com/intellij/testFramework/utils/parameterInfo/MockParameterInfoUIContext.java
index 5855db6..e57fb4f 100644
--- a/platform/testFramework/src/com/intellij/testFramework/utils/parameterInfo/MockParameterInfoUIContext.java
+++ b/platform/testFramework/src/com/intellij/testFramework/utils/parameterInfo/MockParameterInfoUIContext.java
@@ -27,6 +27,7 @@
   private boolean enabled;
   private String text;
   private int highlightStart;
+  private int highlightEnd;
   private final T myFunction;
   private int parameterIndex;
 
@@ -40,6 +41,7 @@
                                              final Color background) {
     text = _text;
     highlightStart = highlightStartOffset;
+    highlightEnd = highlightEndOffset;
     return _text;
   }
 
@@ -79,4 +81,8 @@
   public int getHighlightStart() {
     return highlightStart;
   }
+
+  public int getHighlightEnd() {
+    return highlightEnd;
+  }
 }
diff --git a/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java b/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java
index 1a6f98f..72df634 100644
--- a/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java
+++ b/platform/testRunner/src/com/intellij/execution/testframework/TestsUIUtil.java
@@ -218,8 +218,8 @@
           myType = MessageType.ERROR;
         }
         else if (notStartedCount > 0) {
-          myTitle = ExecutionBundle.message("junit.runing.info.failed.to.start.error.message");
-          myText = passedCount + " passed, " + notStartedCount + " not started" ;
+          myTitle = !notStarted.isEmpty() ? ExecutionBundle.message("junit.runing.info.failed.to.start.error.message") : "Tests Ignored";
+          myText = passedCount + " passed, " + notStartedCount + (!notStarted.isEmpty() ? " not started" : " ignored");
           myType = MessageType.ERROR;
         }
         else {
diff --git a/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java b/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java
index a44d8f7..463708e1 100644
--- a/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java
+++ b/platform/util/src/com/intellij/execution/process/BaseOSProcessHandler.java
@@ -20,6 +20,7 @@
 import com.intellij.openapi.util.Key;
 import com.intellij.util.ConcurrencyUtil;
 import com.intellij.util.Consumer;
+import com.intellij.util.io.BaseDataReader;
 import com.intellij.util.io.BaseOutputReader;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -28,7 +29,7 @@
 import java.nio.charset.Charset;
 import java.util.concurrent.*;
 
-import static com.intellij.util.io.BaseOutputReader.AdaptiveSleepingPolicy;
+import static com.intellij.util.io.BaseDataReader.AdaptiveSleepingPolicy;
 
 public class BaseOSProcessHandler extends ProcessHandler implements TaskExecutor {
   private static final Logger LOG = Logger.getInstance("#com.intellij.execution.process.OSProcessHandlerBase");
@@ -82,13 +83,10 @@
       @Override
       public void startNotified(final ProcessEvent event) {
         try {
-          BaseOutputReader.SleepingPolicy sleepingPolicy =
-            useAdaptiveSleepingPolicyWhenReadingOutput() ? new AdaptiveSleepingPolicy() : BaseOutputReader.SleepingPolicy.SIMPLE;
-          final BaseOutputReader stdoutReader = new SimpleOutputReader(createProcessOutReader(), ProcessOutputTypes.STDOUT, sleepingPolicy);
-          final BaseOutputReader stderrReader = processHasSeparateErrorStream()
-                                                ? new SimpleOutputReader(createProcessErrReader(), ProcessOutputTypes.STDERR,
-                                                                         sleepingPolicy)
-                                                : null;
+          BaseDataReader.SleepingPolicy sleepingPolicy =
+            useAdaptiveSleepingPolicyWhenReadingOutput() ? new AdaptiveSleepingPolicy() : BaseDataReader.SleepingPolicy.SIMPLE;
+          final BaseDataReader stdoutReader = createOutputDataReader(sleepingPolicy);
+          final BaseDataReader stderrReader = processHasSeparateErrorStream() ? createErrorDataReader(sleepingPolicy) : null;
 
           myWaitFor.setTerminationCallback(new Consumer<Integer>() {
             @Override
@@ -120,6 +118,17 @@
     super.startNotify();
   }
 
+  @NotNull
+  protected BaseDataReader createErrorDataReader(BaseDataReader.SleepingPolicy sleepingPolicy) {
+    return new SimpleOutputReader(createProcessErrReader(), ProcessOutputTypes.STDERR,
+                             sleepingPolicy);
+  }
+
+  @NotNull
+  protected BaseDataReader createOutputDataReader(BaseDataReader.SleepingPolicy sleepingPolicy) {
+    return new SimpleOutputReader(createProcessOutReader(), ProcessOutputTypes.STDOUT, sleepingPolicy);
+  }
+
   protected void onOSProcessTerminated(final int exitCode) {
     notifyProcessTerminated(exitCode);
   }
diff --git a/platform/util/src/com/intellij/icons/AllIcons.java b/platform/util/src/com/intellij/icons/AllIcons.java
index 4b1718e..35f60df 100644
--- a/platform/util/src/com/intellij/icons/AllIcons.java
+++ b/platform/util/src/com/intellij/icons/AllIcons.java
@@ -346,7 +346,7 @@
     public static final Icon AutoscrollFromSource = IconLoader.getIcon("/general/autoscrollFromSource.png"); // 16x16
     public static final Icon AutoscrollToSource = IconLoader.getIcon("/general/autoscrollToSource.png"); // 16x16
     public static final Icon Balloon = IconLoader.getIcon("/general/balloon.png"); // 16x16
-    public static final Icon BalloonClose = IconLoader.getIcon("/general/balloonClose.png"); // 30x30
+    public static final Icon BalloonClose = IconLoader.getIcon("/general/balloonClose.png"); // 32x32
     public static final Icon BalloonError = IconLoader.getIcon("/general/balloonError.png"); // 16x16
     public static final Icon BalloonInformation = IconLoader.getIcon("/general/balloonInformation.png"); // 16x16
     public static final Icon BalloonWarning = IconLoader.getIcon("/general/balloonWarning.png"); // 16x16
@@ -689,6 +689,8 @@
     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 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
     public static final Icon Merge = IconLoader.getIcon("/modules/merge.png"); // 16x16
     public static final Icon ModulesNode = IconLoader.getIcon("/modules/modulesNode.png"); // 16x16
diff --git a/platform/util/src/com/intellij/ide/ClassUtilCore.java b/platform/util/src/com/intellij/ide/ClassUtilCore.java
index b1e8dc4..ac57409 100644
--- a/platform/util/src/com/intellij/ide/ClassUtilCore.java
+++ b/platform/util/src/com/intellij/ide/ClassUtilCore.java
@@ -33,9 +33,7 @@
       clearMap(jarFileFactory.getDeclaredField(FILE_CACHE));
       clearMap(jarFileFactory.getDeclaredField(URL_CACHE));
     }
-    catch (Exception e) {
-      System.out.println("Failed to clear URL cache");
-      e.printStackTrace();
+    catch (Exception ignore) {
       // Do nothing.
     }
   }
diff --git a/platform/util/src/com/intellij/openapi/application/PathManager.java b/platform/util/src/com/intellij/openapi/application/PathManager.java
index 2f2418b..4001fd0 100644
--- a/platform/util/src/com/intellij/openapi/application/PathManager.java
+++ b/platform/util/src/com/intellij/openapi/application/PathManager.java
@@ -79,7 +79,8 @@
     else {
       ourHomePath = getHomePathFor(PathManager.class);
       if (ourHomePath == null) {
-        String advice = SystemInfo.isMac ? "reinstall the software." : "make sure bin/idea.properties is present in the installation directory.";
+        String advice = SystemInfo.isMac ? "reinstall the software."
+                                         : "make sure bin/idea.properties is present in the installation directory.";
         throw new RuntimeException("Could not find installation home path. Please " + advice);
       }
     }
@@ -186,8 +187,8 @@
     if (System.getProperty(PROPERTY_PLUGINS_PATH) != null) {
       ourPluginsPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_PLUGINS_PATH)));
     }
-    else if (PATHS_SELECTOR != null) {
-      ourPluginsPath = platformPath(PATHS_SELECTOR, "Library/Application Support", CONFIG_FOLDER + File.separatorChar + PLUGINS_FOLDER);
+    else if (SystemInfo.isMac && PATHS_SELECTOR != null) {
+      ourPluginsPath = getUserHome() + File.separator + "Library/Application Support" + File.separator + PATHS_SELECTOR;
     }
     else {
       ourPluginsPath = getConfigPath() + File.separatorChar + PLUGINS_FOLDER;
@@ -235,8 +236,8 @@
     if (System.getProperty(PROPERTY_LOG_PATH) != null) {
       ourLogPath = getAbsolutePath(trimPathQuotes(System.getProperty(PROPERTY_LOG_PATH)));
     }
-    else if (PATHS_SELECTOR != null) {
-      ourLogPath = platformPath(PATHS_SELECTOR, "Library/Logs", SYSTEM_FOLDER + File.separatorChar + LOG_DIRECTORY);
+    else if (SystemInfo.isMac && PATHS_SELECTOR != null) {
+      ourLogPath = getUserHome() + File.separator + "Library/Logs" + File.separator + PATHS_SELECTOR;
     }
     else {
       ourLogPath = getSystemPath() + File.separatorChar + LOG_DIRECTORY;
@@ -319,19 +320,19 @@
 
     if (propFile != null) {
       try {
-        InputStream fis = new BufferedInputStream(new FileInputStream(propFile));
+        Reader fis = new BufferedReader(new FileReader(propFile));
         try {
-          final PropertyResourceBundle bundle = new PropertyResourceBundle(fis);
-          final Enumeration keys = bundle.getKeys();
-          String home = (String)bundle.handleGetObject("idea.home");
+          Map<String, String> properties = FileUtil.loadProperties(fis);
+
+          String home = properties.get("idea.home");
           if (home != null && ourHomePath == null) {
             ourHomePath = getAbsolutePath(substituteVars(home));
           }
-          final Properties sysProperties = System.getProperties();
-          while (keys.hasMoreElements()) {
-            String key = (String)keys.nextElement();
+
+          Properties sysProperties = System.getProperties();
+          for (String key : properties.keySet()) {
             if (sysProperties.getProperty(key, null) == null) { // load the property from the property file only if it is not defined yet
-              final String value = substituteVars(bundle.getString(key));
+              String value = substituteVars(properties.get(key));
               sysProperties.setProperty(key, value);
             }
           }
diff --git a/platform/util/src/com/intellij/openapi/diagnostic/FrequentEventDetector.java b/platform/util/src/com/intellij/openapi/diagnostic/FrequentEventDetector.java
index e7b3254..42ae6a3 100644
--- a/platform/util/src/com/intellij/openapi/diagnostic/FrequentEventDetector.java
+++ b/platform/util/src/com/intellij/openapi/diagnostic/FrequentEventDetector.java
@@ -37,14 +37,16 @@
   public void eventHappened() {
     if (myEventsPosted.incrementAndGet() > myEventCountThreshold) {
       synchronized (myEventsPosted) {
+        boolean shouldLog = false;
         if (myEventsPosted.get() > myEventCountThreshold) {
           long timeNow = System.currentTimeMillis();
-          if (timeNow - myStartedCounting < myTimeSpanMs) {
-            LOG.info("Too many events posted\n" + ExceptionUtil.getThrowableText(new Throwable()));
-          }
+          shouldLog = timeNow - myStartedCounting < myTimeSpanMs;
           myEventsPosted.set(0);
           myStartedCounting = timeNow;
         }
+        if (shouldLog) {
+          LOG.info("Too many events posted\n" + ExceptionUtil.getThrowableText(new Throwable()));
+        }
       }
     }
 
diff --git a/platform/util/src/com/intellij/openapi/util/Disposer.java b/platform/util/src/com/intellij/openapi/util/Disposer.java
index bb999e5..4ddf027 100644
--- a/platform/util/src/com/intellij/openapi/util/Disposer.java
+++ b/platform/util/src/com/intellij/openapi/util/Disposer.java
@@ -108,8 +108,8 @@
     ourTree.executeAll(disposable, true, ourDisposeAction, processUnregistered);
   }
 
-  public static void disposeChildAndReplace(@NotNull Disposable toDipose, @NotNull Disposable toReplace) {
-    ourTree.executeChildAndReplace(toDipose, toReplace, true, ourDisposeAction);
+  public static void disposeChildAndReplace(@NotNull Disposable toDispose, @NotNull Disposable toReplace) {
+    ourTree.executeChildAndReplace(toDispose, toReplace, true, ourDisposeAction);
   }
 
   @NotNull
diff --git a/platform/util/src/com/intellij/openapi/util/IconLoader.java b/platform/util/src/com/intellij/openapi/util/IconLoader.java
index d0ce5bc..1830cee 100644
--- a/platform/util/src/com/intellij/openapi/util/IconLoader.java
+++ b/platform/util/src/com/intellij/openapi/util/IconLoader.java
@@ -22,7 +22,7 @@
 import com.intellij.util.ImageLoader;
 import com.intellij.util.ReflectionUtil;
 import com.intellij.util.RetinaImage;
-import com.intellij.util.containers.ConcurrentHashMap;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.WeakHashMap;
 import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
@@ -49,7 +49,7 @@
   private static boolean USE_DARK_ICONS = UIUtil.isUnderDarcula();
 
   @SuppressWarnings("MismatchedQueryAndUpdateOfCollection")
-  private static final ConcurrentMap<URL, CachedImageIcon> ourIconsCache = new ConcurrentHashMap<URL, CachedImageIcon>(100, 0.9f,2);
+  private static final ConcurrentMap<URL, CachedImageIcon> ourIconsCache = ContainerUtil.newConcurrentMap(100, 0.9f, 2);
 
   /**
    * This cache contains mapping between icons and disabled icons.
diff --git a/platform/util/src/com/intellij/openapi/util/KeyWithDefaultValue.java b/platform/util/src/com/intellij/openapi/util/KeyWithDefaultValue.java
index 7377840..13894d1 100644
--- a/platform/util/src/com/intellij/openapi/util/KeyWithDefaultValue.java
+++ b/platform/util/src/com/intellij/openapi/util/KeyWithDefaultValue.java
@@ -28,4 +28,14 @@
   }
 
   public abstract T getDefaultValue();
+
+  @NotNull
+  public static <T> KeyWithDefaultValue<T> create(@NotNull @NonNls String name, final T defValue) {
+    return new KeyWithDefaultValue<T>(name) {
+      @Override
+      public T getDefaultValue() {
+        return defValue;
+      }
+    };
+  }
 }
diff --git a/platform/util/src/com/intellij/openapi/util/SystemInfo.java b/platform/util/src/com/intellij/openapi/util/SystemInfo.java
index a1daffc..c5ce5bb 100644
--- a/platform/util/src/com/intellij/openapi/util/SystemInfo.java
+++ b/platform/util/src/com/intellij/openapi/util/SystemInfo.java
@@ -42,6 +42,7 @@
 
   public static final boolean isAppleJvm = isAppleJvm();
   public static final boolean isOracleJvm = isOracleJvm();
+  public static final boolean isSunJvm = isSunJvm();
 
   public static boolean isOsVersionAtLeast(@NotNull String version) {
     return StringUtil.compareVersionNumbers(OS_VERSION, version) >= 0;
@@ -169,6 +170,11 @@
     return vendor != null && StringUtil.containsIgnoreCase(vendor, "Oracle");
   }
 
+  private static boolean isSunJvm() {
+    final String vendor = SystemProperties.getJavaVmVendor();
+    return vendor != null && StringUtil.containsIgnoreCase(vendor, "Sun") && StringUtil.containsIgnoreCase(vendor, "Microsystems");
+  }
+
   private static boolean isAppleJvm() {
     final String vendor = SystemProperties.getJavaVmVendor();
     return vendor != null && StringUtil.containsIgnoreCase(vendor, "Apple");
diff --git a/platform/util/src/com/intellij/openapi/util/io/FileUtil.java b/platform/util/src/com/intellij/openapi/util/io/FileUtil.java
index ca86631..8e9ae27 100644
--- a/platform/util/src/com/intellij/openapi/util/io/FileUtil.java
+++ b/platform/util/src/com/intellij/openapi/util/io/FileUtil.java
@@ -1419,4 +1419,23 @@
 
     return true;
   }
+
+  /**
+   * Like {@link Properties#load(java.io.Reader)}, but preserves the order of key/value pairs.
+   */
+  @NotNull
+  public static Map<String, String> loadProperties(@NotNull Reader reader) throws IOException {
+    final Map<String, String> map = ContainerUtil.newLinkedHashMap();
+
+    new Properties() {
+      @Override
+      public synchronized Object put(Object key, Object value) {
+        map.put(String.valueOf(key), String.valueOf(value));
+        //noinspection UseOfPropertiesAsHashtable
+        return super.put(key, value);
+      }
+    }.load(reader);
+
+    return map;
+  }
 }
diff --git a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java
index 45695b7..34c9cc2 100644
--- a/platform/util/src/com/intellij/openapi/util/text/StringUtil.java
+++ b/platform/util/src/com/intellij/openapi/util/text/StringUtil.java
@@ -44,6 +44,7 @@
   @NonNls private static final String VOWELS = "aeiouy";
   @NonNls private static final Pattern EOL_SPLIT_PATTERN = Pattern.compile(" *(\r|\n|\r\n)+ *");
   @NonNls private static final Pattern EOL_SPLIT_PATTERN_WITH_EMPTY = Pattern.compile(" *(\r|\n|\r\n) *");
+  @NonNls private static final Pattern EOL_SPLIT_DONT_TRIM_PATTERN = Pattern.compile("(\r|\n|\r\n)+");
 
   public static final NotNullFunction<String, String> QUOTER = new NotNullFunction<String, String>() {
     @Override
@@ -307,9 +308,14 @@
     for (int i = 0; i < text.length(); i++) {
       char c = text.charAt(i);
       switch (c) {
-        case '\n': buffer.append("\\n"); break;
-        case '\r': buffer.append("\\r"); break;
-        default: buffer.append(c);
+        case '\n':
+          buffer.append("\\n");
+          break;
+        case '\r':
+          buffer.append("\\r");
+          break;
+        default:
+          buffer.append(c);
       }
     }
     return buffer.toString();
@@ -814,13 +820,17 @@
     return true;
   }
 
-  /** @deprecated use {@link #startsWithConcatenation(String, String...)} (to remove in IDEA 14). */
+  /**
+   * @deprecated use {@link #startsWithConcatenation(String, String...)} (to remove in IDEA 14).
+   */
   @SuppressWarnings("UnusedDeclaration")
   public static boolean startsWithConcatenationOf(@NotNull String string, @NotNull String firstPrefix, @NotNull String secondPrefix) {
     return startsWithConcatenation(string, firstPrefix, secondPrefix);
   }
 
-  /** @deprecated use {@link #startsWithConcatenation(String, String...)} (to remove in IDEA 14). */
+  /**
+   * @deprecated use {@link #startsWithConcatenation(String, String...)} (to remove in IDEA 14).
+   */
   @SuppressWarnings("UnusedDeclaration")
   public static boolean startsWithConcatenationOf(@NotNull String string,
                                                   @NotNull String firstPrefix,
@@ -947,11 +957,11 @@
 
   @Contract("null -> true")
   public static boolean isEmptyOrSpaces(@Nullable final String s) {
-    if(s == null || s.isEmpty()) {
+    if (s == null || s.isEmpty()) {
       return true;
     }
-    for(int i = 0; i < s.length(); i++) {
-      if(s.charAt(i) > ' ') {
+    for (int i = 0; i < s.length(); i++) {
+      if (s.charAt(i) > ' ') {
         return false;
       }
     }
@@ -992,7 +1002,7 @@
 
   @NotNull
   public static String repeat(@NotNull String s, int count) {
-    assert count >=0 : count;
+    assert count >= 0 : count;
     StringBuilder sb = new StringBuilder(s.length() * count);
     for (int i = 0; i < count; i++) {
       sb.append(s);
@@ -1214,7 +1224,9 @@
   }
 
   @NotNull
-  public static <T> String join(@NotNull Collection<? extends T> items, @NotNull Function<? super T, String> f, @NotNull @NonNls String separator) {
+  public static <T> String join(@NotNull Collection<? extends T> items,
+                                @NotNull Function<? super T, String> f,
+                                @NotNull @NonNls String separator) {
     if (items.isEmpty()) return "";
     return join((Iterable<? extends T>)items, f, separator);
   }
@@ -1231,7 +1243,9 @@
   }
 
   @NotNull
-  public static <T> String join(@NotNull Iterable<? extends T> items, @NotNull Function<? super T, String> f, @NotNull @NonNls String separator) {
+  public static <T> String join(@NotNull Iterable<? extends T> items,
+                                @NotNull Function<? super T, String> f,
+                                @NotNull @NonNls String separator) {
     final StringBuilder result = new StringBuilder();
     for (T item : items) {
       String string = f.fun(item);
@@ -1587,7 +1601,7 @@
    * @param end   end offset to use within the given char sequence (exclusive)
    * @param c     target symbol to check
    * @return <code>true</code> if given symbol is contained at the target range of the given char sequence;
-   *         <code>false</code> otherwise
+   * <code>false</code> otherwise
    */
   public static boolean contains(@NotNull CharSequence s, int start, int end, char c) {
     return indexOf(s, c, start, end) >= 0;
@@ -1640,6 +1654,7 @@
   public static int indexOfAny(@NotNull final String s, @NotNull final String chars) {
     return indexOfAny(s, chars, 0, s.length());
   }
+
   public static int indexOfAny(@NotNull final CharSequence s, @NotNull final String chars) {
     return indexOfAny(s, chars, 0, s.length());
   }
@@ -1647,6 +1662,7 @@
   public static int indexOfAny(@NotNull final String s, @NotNull final String chars, final int start, final int end) {
     return indexOfAny((CharSequence)s, chars, start, end);
   }
+
   public static int indexOfAny(@NotNull final CharSequence s, @NotNull final String chars, final int start, final int end) {
     for (int i = start; i < end; i++) {
       if (containsChar(chars, s.charAt(i))) return i;
@@ -1669,7 +1685,7 @@
    * @param start start offset of the target text (inclusive)
    * @param end   end offset of the target text (exclusive)
    * @return index of the last occurrence of the given symbol at the target sub-sequence of the given text if any;
-   *         <code>-1</code> otherwise
+   * <code>-1</code> otherwise
    */
   public static int lastIndexOf(@NotNull CharSequence s, char c, int start, int end) {
     for (int i = end - 1; i >= start; i--) {
@@ -2186,6 +2202,11 @@
   }
 
   @NotNull
+  public static String[] splitByLinesDontTrim(@NotNull String string) {
+    return EOL_SPLIT_DONT_TRIM_PATTERN.split(string);
+  }
+
+  @NotNull
   public static List<Pair<String, Integer>> getWordsWithOffset(@NotNull String s) {
     List<Pair<String, Integer>> res = ContainerUtil.newArrayList();
     s += " ";
@@ -2213,11 +2234,22 @@
    * Implementation of "Sorting for Humans: Natural Sort Order":
    * http://www.codinghorror.com/blog/2007/12/sorting-for-humans-natural-sort-order.html
    */
-  public static int naturalCompare(@NotNull String string1, @NotNull String string2) {
+  public static int naturalCompare(@Nullable String string1, @Nullable String string2) {
     return naturalCompare(string1, string2, false);
   }
 
-  private static int naturalCompare(@NotNull String string1, @NotNull String string2, boolean caseSensitive) {
+  private static int naturalCompare(@Nullable String string1, @Nullable String string2, boolean caseSensitive) {
+    //noinspection StringEquality
+    if (string1 == string2) {
+      return 0;
+    }
+    if (string1 == null) {
+      return -1;
+    }
+    if (string2 == null) {
+      return 1;
+    }
+
     final int string1Length = string1.length();
     final int string2Length = string2.length();
     int i = 0, j = 0;
@@ -2345,7 +2377,7 @@
       return false;
     }
     for (int i = 0; i < s1.length(); i++) {
-      if (!charsMatch(s1.charAt(i),s2.charAt(i), true)) {
+      if (!charsMatch(s1.charAt(i), s2.charAt(i), true)) {
         return false;
       }
     }
@@ -2376,7 +2408,7 @@
   }
 
   public static boolean charsMatch(char c1, char c2, boolean ignoreCase) {
-    return compare(c1,c2,ignoreCase) == 0;
+    return compare(c1, c2, ignoreCase) == 0;
   }
 
   @NotNull
@@ -2410,7 +2442,10 @@
   }
 
   @NotNull
-  public static String shortenTextWithEllipsis(@NotNull final String text, final int maxLength, final int suffixLength, boolean useEllipsisSymbol) {
+  public static String shortenTextWithEllipsis(@NotNull final String text,
+                                               final int maxLength,
+                                               final int suffixLength,
+                                               boolean useEllipsisSymbol) {
     final int textLength = text.length();
     if (textLength > maxLength) {
       String symbol = useEllipsisSymbol ? "\u2026" : "...";
@@ -2436,6 +2471,7 @@
   public static boolean charsEqual(char a, char b, boolean ignoreCase) {
     return ignoreCase ? charsEqualIgnoreCase(a, b) : a == b;
   }
+
   public static boolean charsEqualIgnoreCase(char a, char b) {
     return StringUtilRt.charsEqualIgnoreCase(a, b);
   }
diff --git a/platform/util/src/com/intellij/ui/Gradient.java b/platform/util/src/com/intellij/ui/Gradient.java
new file mode 100644
index 0000000..511fff9
--- /dev/null
+++ b/platform/util/src/com/intellij/ui/Gradient.java
@@ -0,0 +1,39 @@
+/*
+ * 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.ui;
+
+import java.awt.*;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class Gradient {
+  private final Color myStartColor;
+  private final Color myEndColor;
+
+  public Gradient(Color startColor, Color endColor) {
+    myStartColor = startColor;
+    myEndColor = endColor;
+  }
+
+  public Color getStartColor() {
+    return myStartColor;
+  }
+
+  public Color getEndColor() {
+    return myEndColor;
+  }
+}
diff --git a/platform/util/src/com/intellij/ui/mac/foundation/MacUtil.java b/platform/util/src/com/intellij/ui/mac/foundation/MacUtil.java
index f2afa03..64aa444 100644
--- a/platform/util/src/com/intellij/ui/mac/foundation/MacUtil.java
+++ b/platform/util/src/com/intellij/ui/mac/foundation/MacUtil.java
@@ -16,9 +16,11 @@
 package com.intellij.ui.mac.foundation;
 
 import com.intellij.openapi.Disposable;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.util.SystemInfo;
+import com.intellij.openapi.util.registry.Registry;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -27,6 +29,8 @@
 import java.awt.*;
 import java.awt.event.AWTEventListener;
 import java.awt.event.KeyEvent;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
 
 import static com.intellij.ui.mac.foundation.Foundation.invoke;
 import static com.intellij.ui.mac.foundation.Foundation.toStringViaUTF8;
@@ -35,8 +39,9 @@
  * @author pegov
  */
 public class MacUtil {
+  private static final Logger LOG = Logger.getInstance("#com.intellij.ui.mac.foundation.MacUtil");
   public static final String MAC_NATIVE_WINDOW_SHOWING = "MAC_NATIVE_WINDOW_SHOWING";
-  
+
   private MacUtil() {
   }
 
@@ -72,7 +77,7 @@
 
     return focusedWindow;
   }
-  
+
   public static synchronized void startModal(JComponent component, String key) {
     try {
       if (SwingUtilities.isEventDispatchThread()) {
@@ -91,7 +96,7 @@
             ((MenuComponent)source).dispatchEvent(event);
           }
           else {
-            System.err.println("Unable to dispatch: " + event);
+            LOG.debug("Unable to dispatch: " + event);
           }
         }
       }
@@ -106,7 +111,7 @@
     catch (InterruptedException ignored) {
     }
   }
-  
+
   public static synchronized void startModal(JComponent component) {
     startModal(component, MAC_NATIVE_WINDOW_SHOWING);
   }
@@ -137,4 +142,47 @@
     });
     Toolkit.getDefaultToolkit().addAWTEventListener(listener, AWTEvent.KEY_EVENT_MASK);
   }
+
+  @SuppressWarnings("deprecation")
+  public static ID findWindowFromJavaWindow(final Window w) {
+    ID windowId = null;
+    if (SystemInfo.isJavaVersionAtLeast("1.7") && Registry.is("skip.untitled.windows.for.mac.messages")) {
+      try {
+        //noinspection deprecation
+        Class <?> cWindowPeerClass  = w.getPeer().getClass();
+        Method getPlatformWindowMethod = cWindowPeerClass.getDeclaredMethod("getPlatformWindow");
+        Object cPlatformWindow = getPlatformWindowMethod.invoke(w.getPeer());
+        Class <?> cPlatformWindowClass = cPlatformWindow.getClass();
+        Method getNSWindowPtrMethod = cPlatformWindowClass.getDeclaredMethod("getNSWindowPtr");
+        windowId = new ID((Long)getNSWindowPtrMethod.invoke(cPlatformWindow));
+      }
+      catch (NoSuchMethodException e) {
+        LOG.debug(e);
+      }
+      catch (InvocationTargetException e) {
+        LOG.debug(e);
+      }
+      catch (IllegalAccessException e) {
+        LOG.debug(e);
+      }
+
+    } else {
+      String foremostWindowTitle = getWindowTitle(w);
+      windowId = findWindowForTitle(foremostWindowTitle);
+    }
+    return windowId;
+  }
+
+
+  public static String getWindowTitle(Window documentRoot) {
+    String windowTitle;
+    if (documentRoot instanceof Frame) {
+      windowTitle = ((Frame)documentRoot).getTitle();
+    } else if (documentRoot instanceof Dialog) {
+      windowTitle = ((Dialog)documentRoot).getTitle();
+    } else {
+      throw new RuntimeException("The window is not a frame and not a dialog!");
+    }
+    return windowTitle;
+  }
 }
diff --git a/platform/util/src/com/intellij/util/PathMappingSettings.java b/platform/util/src/com/intellij/util/PathMappingSettings.java
index 699c605..438ae23 100644
--- a/platform/util/src/com/intellij/util/PathMappingSettings.java
+++ b/platform/util/src/com/intellij/util/PathMappingSettings.java
@@ -213,6 +213,23 @@
     myPathMappings.addAll(settings.getPathMappings());
   }
 
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    PathMappingSettings settings = (PathMappingSettings)o;
+
+    if (!myPathMappings.equals(settings.myPathMappings)) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    return myPathMappings.hashCode();
+  }
+
   @Tag("mapping")
   public static class PathMapping {
     private String myLocalRoot;
@@ -309,5 +326,25 @@
     public PathMapping clone() {
       return new PathMapping(myLocalRoot, myRemoteRoot);
     }
+
+    @Override
+    public boolean equals(Object o) {
+      if (this == o) return true;
+      if (o == null || getClass() != o.getClass()) return false;
+
+      PathMapping mapping = (PathMapping)o;
+
+      if (myLocalRoot != null ? !myLocalRoot.equals(mapping.myLocalRoot) : mapping.myLocalRoot != null) return false;
+      if (myRemoteRoot != null ? !myRemoteRoot.equals(mapping.myRemoteRoot) : mapping.myRemoteRoot != null) return false;
+
+      return true;
+    }
+
+    @Override
+    public int hashCode() {
+      int result = myLocalRoot != null ? myLocalRoot.hashCode() : 0;
+      result = 31 * result + (myRemoteRoot != null ? myRemoteRoot.hashCode() : 0);
+      return result;
+    }
   }
 }
diff --git a/platform/util/src/com/intellij/util/SharedProcessingContext.java b/platform/util/src/com/intellij/util/SharedProcessingContext.java
index 16f1c81..cb7c4cf 100644
--- a/platform/util/src/com/intellij/util/SharedProcessingContext.java
+++ b/platform/util/src/com/intellij/util/SharedProcessingContext.java
@@ -1,7 +1,7 @@
 package com.intellij.util;
 
 import com.intellij.openapi.util.Key;
-import com.intellij.util.containers.ConcurrentHashMap;
+import com.intellij.util.containers.ContainerUtil;
 import gnu.trove.THashMap;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -13,7 +13,7 @@
  * @author peter
  */
 public class SharedProcessingContext {
-  private final Map<Object, Object> myMap = new ConcurrentHashMap<Object, Object>();
+  private final Map<Object, Object> myMap = ContainerUtil.newConcurrentMap();
 
   public Object get(@NotNull @NonNls final String key) {
     return myMap.get(key);
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentClassMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentClassMap.java
index 813f495..d86f28d 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentClassMap.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentClassMap.java
@@ -20,6 +20,6 @@
  */
 public class ConcurrentClassMap<T> extends ClassMap<T> {
   public ConcurrentClassMap() {
-    super(new ConcurrentHashMap<Class,T>());
+    super(ContainerUtil.<Class, T>newConcurrentMap());
   }
 }
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentFactoryMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentFactoryMap.java
index 84cf70b..cf58572 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentFactoryMap.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentFactoryMap.java
@@ -21,8 +21,9 @@
  * @author peter
  */
 public abstract class ConcurrentFactoryMap<T,V> extends FactoryMap<T,V> {
+
   @Override
   protected Map<T, V> createMap() {
-    return new ConcurrentHashMap<T,V>();
+    return ContainerUtil.newConcurrentMap();
   }
 }
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java b/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java
index 59a2240..f86dd2e 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentHashSet.java
@@ -28,13 +28,13 @@
   private final ConcurrentMap<K, Boolean> map;
 
   public ConcurrentHashSet(int initialCapacity) {
-    map = new ConcurrentHashMap<K, Boolean>(initialCapacity);
+    map = ContainerUtil.newConcurrentMap(initialCapacity);
   }
   public ConcurrentHashSet() {
-    map = new ConcurrentHashMap<K, Boolean>();
+    map = ContainerUtil.newConcurrentMap();
   }
   public ConcurrentHashSet(@NotNull TObjectHashingStrategy<K> hashingStrategy) {
-    map = new ConcurrentHashMap<K, Boolean>(hashingStrategy);
+    map = ContainerUtil.newConcurrentMap(hashingStrategy);
   }
 
   @Override
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentMostlySingularMultiMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentMostlySingularMultiMap.java
index b467007..277bef7 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentMostlySingularMultiMap.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentMostlySingularMultiMap.java
@@ -28,7 +28,7 @@
   @NotNull
   @Override
   protected Map<K, Object> createMap() {
-    return new ConcurrentHashMap<K, Object>();
+    return ContainerUtil.newConcurrentMap();
   }
 
   @Override
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentMultiMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentMultiMap.java
index c6e5616..23f3743 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentMultiMap.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentMultiMap.java
@@ -25,7 +25,7 @@
 public class ConcurrentMultiMap<K,V> extends MultiMap<K,V> {
   @Override
   protected Map<K, Collection<V>> createMap() {
-    return new ConcurrentHashMap<K, Collection<V>>();
+    return ContainerUtil.newConcurrentMap();
   }
 
   @Override
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentRefHashMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentRefHashMap.java
index 469342e..d86d696 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentRefHashMap.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentRefHashMap.java
@@ -36,7 +36,7 @@
  */
 abstract class ConcurrentRefHashMap<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V>, TObjectHashingStrategy<K> {
   protected final ReferenceQueue<K> myReferenceQueue = new ReferenceQueue<K>();
-  private final ConcurrentHashMap<Key<K, V>, V> myMap; // hashing strategy must be canonical, we compute corresponding hash codes using our own myHashingStrategy
+  private final ConcurrentMap<Key<K, V>, V> myMap; // hashing strategy must be canonical, we compute corresponding hash codes using our own myHashingStrategy
   @NotNull
   private final TObjectHashingStrategy<K> myHashingStrategy;
 
@@ -149,7 +149,7 @@
                               int concurrencyLevel,
                               @NotNull TObjectHashingStrategy<K> hashingStrategy) {
     myHashingStrategy = hashingStrategy == THIS ? this : hashingStrategy;
-    myMap = new ConcurrentHashMap<Key<K, V>, V>(initialCapacity, loadFactor, concurrencyLevel, CANONICAL);
+    myMap = ContainerUtil.<Key<K, V>, V>newConcurrentMap(initialCapacity, loadFactor, concurrencyLevel, CANONICAL);
   }
 
   @Override
diff --git a/platform/util/src/com/intellij/util/containers/ConcurrentRefValueHashMap.java b/platform/util/src/com/intellij/util/containers/ConcurrentRefValueHashMap.java
index e388827..71ac7bd 100644
--- a/platform/util/src/com/intellij/util/containers/ConcurrentRefValueHashMap.java
+++ b/platform/util/src/com/intellij/util/containers/ConcurrentRefValueHashMap.java
@@ -26,7 +26,7 @@
 import java.util.concurrent.ConcurrentMap;
 
 abstract class ConcurrentRefValueHashMap<K, V> implements ConcurrentMap<K, V> {
-  private final ConcurrentHashMap<K, MyValueReference<K, V>> myMap;
+  private final ConcurrentMap<K, MyValueReference<K, V>> myMap;
   protected final ReferenceQueue<V> myQueue = new ReferenceQueue<V>();
 
   public ConcurrentRefValueHashMap(@NotNull Map<K, V> map) {
@@ -35,18 +35,18 @@
   }
 
   public ConcurrentRefValueHashMap() {
-    myMap = new ConcurrentHashMap<K, MyValueReference<K, V>>();
+    myMap = ContainerUtil.newConcurrentMap();
   }
 
   public ConcurrentRefValueHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
-    myMap = new ConcurrentHashMap<K, MyValueReference<K, V>>(initialCapacity, loadFactor, concurrencyLevel);
+    myMap = ContainerUtil.newConcurrentMap(initialCapacity, loadFactor, concurrencyLevel);
   }
 
   public ConcurrentRefValueHashMap(int initialCapacity,
                                    float loadFactor,
                                    int concurrencyLevel,
                                    @NotNull TObjectHashingStrategy<K> hashingStrategy) {
-    myMap = new ConcurrentHashMap<K, MyValueReference<K, V>>(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy);
+    myMap = ContainerUtil.newConcurrentMap(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy);
   }
 
   protected interface MyValueReference<K, V> {
diff --git a/platform/util/src/com/intellij/util/containers/ContainerUtil.java b/platform/util/src/com/intellij/util/containers/ContainerUtil.java
index fbcdcd7..e8d4001 100644
--- a/platform/util/src/com/intellij/util/containers/ContainerUtil.java
+++ b/platform/util/src/com/intellij/util/containers/ContainerUtil.java
@@ -16,10 +16,8 @@
 package com.intellij.util.containers;
 
 import com.intellij.openapi.Disposable;
-import com.intellij.openapi.util.Condition;
-import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.Factory;
-import com.intellij.openapi.util.Pair;
+import com.intellij.openapi.util.*;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.*;
 import gnu.trove.*;
 import org.jetbrains.annotations.Contract;
@@ -38,6 +36,7 @@
 @SuppressWarnings({"UtilityClassWithoutPrivateConstructor", "MethodOverridesStaticMethodOfSuperclass", "UnusedDeclaration"})
 public class ContainerUtil extends ContainerUtilRt {
   private static final int INSERTION_SORT_THRESHOLD = 10;
+  private static final int DEFAULT_CONCURRENCY_LEVEL = Math.min(16, Runtime.getRuntime().availableProcessors());
 
   @NotNull
   public static <T> T[] ar(@NotNull T... elements) {
@@ -294,7 +293,23 @@
 
   @NotNull
   public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
-    return new ConcurrentHashMap<K, V>();
+    return CHM_FACTORY.createMap();
+  }
+
+  public static <K, V> ConcurrentMap<K,V> newConcurrentMap(TObjectHashingStrategy<K> hashStrategy) {
+    return CHM_FACTORY.createMap(hashStrategy);
+  }
+
+  public static <K, V> ConcurrentMap<K,V> newConcurrentMap(int initialCapacity) {
+    return CHM_FACTORY.createMap(initialCapacity);
+  }
+
+  public static <K, V> ConcurrentMap<K,V> newConcurrentMap(int initialCapacity, float loadFactor, int concurrencyLevel, TObjectHashingStrategy<K> hashStrategy) {
+    return CHM_FACTORY.createMap(initialCapacity, loadFactor, concurrencyLevel, hashStrategy);
+  }
+
+  public static <K, V> ConcurrentMap<K,V> newConcurrentMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
+    return CHM_FACTORY.createMap(initialCapacity, loadFactor, concurrencyLevel);
   }
 
   @NotNull
@@ -1535,6 +1550,11 @@
   }
 
   @NotNull
+  public static <T> Set<T> createMaybeSingletonSet(@Nullable T element) {
+    return element == null ? Collections.<T>emptySet() : Collections.singleton(element);
+  }
+
+  @NotNull
   public static <T, V> V getOrCreate(@NotNull Map<T, V> result, final T key, @NotNull V defaultValue) {
     V value = result.get(key);
     if (value == null) {
@@ -1989,4 +2009,66 @@
   public static <T> boolean isEmpty(List<T> list) {
     return list == null || list.isEmpty();
   }
+
+  private interface ConcurrentMapFactory {
+    <T, V> ConcurrentMap<T, V> createMap();
+    <T, V> ConcurrentMap<T, V> createMap(int initialCapacity);
+    <T, V> ConcurrentMap<T, V> createMap(TObjectHashingStrategy<T> hashStrategy);
+    <T, V> ConcurrentMap<T, V> createMap(int initialCapacity, float loadFactor, int concurrencyLevel);
+    <T, V> ConcurrentMap<T, V> createMap(int initialCapacity, float loadFactor, int concurrencyLevel, TObjectHashingStrategy<T> hashStrategy);
+  }
+
+  private static final ConcurrentMapFactory V8_MAP_FACTORY = new ConcurrentMapFactory() {
+    public <T, V> ConcurrentMap<T, V> createMap() {
+      return new ConcurrentHashMap<T,V>();
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(int initialCapacity) {
+      return new ConcurrentHashMap<T,V>(initialCapacity);
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(TObjectHashingStrategy<T> hashStrategy) {
+      return new ConcurrentHashMap<T,V>(hashStrategy);
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
+      return new ConcurrentHashMap<T,V>(initialCapacity, loadFactor, concurrencyLevel);
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull TObjectHashingStrategy<T> hashingStrategy) {
+      return new ConcurrentHashMap<T,V>(initialCapacity, loadFactor, concurrencyLevel, hashingStrategy);
+    }
+  };
+
+  private static final ConcurrentMapFactory PLATFORM_MAP_FACTORY = new ConcurrentMapFactory() {
+    public <T, V> ConcurrentMap<T, V> createMap() {
+      return createMap(16, 0.75f, DEFAULT_CONCURRENCY_LEVEL);
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(int initialCapacity) {
+      return new java.util.concurrent.ConcurrentHashMap<T,V>(initialCapacity);
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(TObjectHashingStrategy<T> hashStrategy) {
+      // ignoring strategy parameter, because it is not supported by this implementation
+      return createMap();
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(int initialCapacity, float loadFactor, int concurrencyLevel) {
+      return new java.util.concurrent.ConcurrentHashMap<T,V>(initialCapacity, loadFactor, concurrencyLevel);
+    }
+
+    public <T, V> ConcurrentMap<T, V> createMap(int initialCapacity, float loadFactor, int concurrencyLevel, @NotNull TObjectHashingStrategy<T> hashingStrategy) {
+      // ignoring strategy parameter, because it is not supported by this implementation
+      return createMap(initialCapacity, loadFactor, concurrencyLevel);
+    }
+  };
+
+  private static final ConcurrentMapFactory CHM_FACTORY = SystemInfo.isOracleJvm || SystemInfo.isSunJvm || SystemInfo.isAppleJvm || isAtLeastJava7() ? V8_MAP_FACTORY : PLATFORM_MAP_FACTORY;
+
+  private static boolean isAtLeastJava7() {
+    // IBM JDK provides correct version in java.version property, but not in java.runtime.version property
+    return StringUtil.compareVersionNumbers(SystemInfo.JAVA_VERSION, "1.7") >= 0;
+  }
 }
+
diff --git a/platform/util/src/com/intellij/util/containers/ObjectIntHashMap.java b/platform/util/src/com/intellij/util/containers/ObjectIntHashMap.java
new file mode 100644
index 0000000..f9a231d
--- /dev/null
+++ b/platform/util/src/com/intellij/util/containers/ObjectIntHashMap.java
@@ -0,0 +1,22 @@
+package com.intellij.util.containers;
+
+import gnu.trove.TObjectIntHashMap;
+
+/**
+ * return -1 instead of 0 if no such mapping exists
+ */
+public class ObjectIntHashMap<K> extends TObjectIntHashMap<K> {
+  public ObjectIntHashMap(int initialCapacity) {
+    super(initialCapacity);
+  }
+
+  public ObjectIntHashMap() {
+    super();
+  }
+
+  @Override
+  public final int get(K key) {
+    int index = index(key);
+    return index < 0 ? -1 : _values[index];
+  }
+}
diff --git a/platform/util/src/com/intellij/util/io/BaseDataReader.java b/platform/util/src/com/intellij/util/io/BaseDataReader.java
new file mode 100644
index 0000000..5b02266
--- /dev/null
+++ b/platform/util/src/com/intellij/util/io/BaseDataReader.java
@@ -0,0 +1,139 @@
+/*
+ * 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.io;
+
+import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.util.TimeoutUtil;
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+import java.util.concurrent.ExecutionException;
+import java.util.concurrent.Future;
+
+/**
+ * @author Konstantin Kolosovsky.
+ */
+public abstract class BaseDataReader {
+  private static final Logger LOG = Logger.getInstance(BaseDataReader.class);
+
+  protected volatile boolean isStopped = false;
+
+  private Future<?> myFinishedFuture = null;
+  @NotNull protected final SleepingPolicy mySleepingPolicy;
+
+  public BaseDataReader(SleepingPolicy sleepingPolicy) {
+    mySleepingPolicy = sleepingPolicy != null ? sleepingPolicy: SleepingPolicy.SIMPLE;
+  }
+
+  protected void start() {
+    if (myFinishedFuture == null) {
+      myFinishedFuture = executeOnPooledThread(new Runnable() {
+        @Override
+        public void run() {
+          doRun();
+        }
+      });
+    }
+  }
+
+  protected abstract Future<?> executeOnPooledThread(Runnable runnable);
+
+  public interface SleepingPolicy {
+    int sleepTimeWhenWasActive = 1;
+    int sleepTimeWhenIdle = 5;
+
+    SleepingPolicy SIMPLE = new SleepingPolicy() {
+      @Override
+      public int getTimeToSleep(boolean wasActive) {
+        return wasActive ? sleepTimeWhenWasActive : sleepTimeWhenIdle;
+      }
+    };
+
+    int getTimeToSleep(boolean wasActive);
+  }
+
+  public static class AdaptiveSleepingPolicy implements SleepingPolicy {
+    private static final int maxSleepTimeWhenIdle = 200;
+    private static final int maxIterationsWithCurrentSleepTime = 50;
+
+    private volatile int myIterationsWithCurrentTime;
+    private volatile int myCurrentSleepTime = sleepTimeWhenIdle;
+
+    @Override
+    public int getTimeToSleep(boolean wasActive) {
+      int currentSleepTime = myCurrentSleepTime; // volatile read
+      if (wasActive) currentSleepTime = sleepTimeWhenWasActive;
+      else if (currentSleepTime == sleepTimeWhenWasActive) {
+        currentSleepTime = sleepTimeWhenIdle;
+        myIterationsWithCurrentTime = 0;
+      }
+      else {
+        int iterationsWithCurrentTime = ++myIterationsWithCurrentTime;
+        if (iterationsWithCurrentTime >= maxIterationsWithCurrentSleepTime) {
+          myIterationsWithCurrentTime = 0;
+          currentSleepTime = Math.min(2* currentSleepTime, maxSleepTimeWhenIdle);
+        }
+      }
+
+      myCurrentSleepTime = currentSleepTime; // volatile write
+      return currentSleepTime;
+    }
+  }
+
+  protected void doRun() {
+    try {
+      while (true) {
+        boolean read = readAvailable();
+
+        if (isStopped) {
+          break;
+        }
+
+        TimeoutUtil.sleep(mySleepingPolicy.getTimeToSleep(read));
+      }
+    }
+    catch (IOException e) {
+      LOG.info(e);
+    }
+    catch (Exception e) {
+      LOG.error(e);
+    }
+    finally {
+      try {
+        close();
+      }
+      catch (IOException e) {
+        LOG.error("Can't close stream", e);
+      }
+    }
+  }
+
+  protected abstract boolean readAvailable() throws IOException;
+  protected abstract void close() throws IOException;
+
+  public void stop() {
+    isStopped = true;
+  }
+
+  public void waitFor() throws InterruptedException {
+    try {
+      myFinishedFuture.get();
+    }
+    catch (ExecutionException e) {
+      LOG.error(e);
+    }
+  }
+}
diff --git a/platform/util/src/com/intellij/util/io/BaseOutputReader.java b/platform/util/src/com/intellij/util/io/BaseOutputReader.java
index ba1e187..d668441 100644
--- a/platform/util/src/com/intellij/util/io/BaseOutputReader.java
+++ b/platform/util/src/com/intellij/util/io/BaseOutputReader.java
@@ -15,121 +15,29 @@
  */
 package com.intellij.util.io;
 
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.util.TimeoutUtil;
 import org.jetbrains.annotations.NotNull;
 
 import java.io.IOException;
 import java.io.Reader;
-import java.util.concurrent.ExecutionException;
-import java.util.concurrent.Future;
 
 /**
  * @author traff
  */
-public abstract class BaseOutputReader {
-  private static final Logger LOG = Logger.getInstance("#com.intellij.util.io.BaseOutputReader");
+public abstract class BaseOutputReader extends BaseDataReader {
 
   protected final Reader myReader;
-  protected volatile boolean isStopped = false;
 
   private final char[] myBuffer = new char[8192];
   private final StringBuilder myTextBuffer = new StringBuilder();
   private boolean skipLF = false;
 
-  private Future<?> myFinishedFuture = null;
-  @NotNull protected final SleepingPolicy mySleepingPolicy;
-
   public BaseOutputReader(@NotNull Reader reader) {
     this(reader, null);
   }
 
   public BaseOutputReader(@NotNull Reader reader, SleepingPolicy sleepingPolicy) {
+    super(sleepingPolicy);
     myReader = reader;
-    mySleepingPolicy = sleepingPolicy != null ? sleepingPolicy: SleepingPolicy.SIMPLE;
-  }
-
-  protected void start() {
-    if (myFinishedFuture == null) {
-      myFinishedFuture = executeOnPooledThread(new Runnable() {
-        @Override
-        public void run() {
-          doRun();
-        }
-      });
-    }
-  }
-
-  protected abstract Future<?> executeOnPooledThread(Runnable runnable);
-
-  public interface SleepingPolicy {
-    int sleepTimeWhenWasActive = 1;
-    int sleepTimeWhenIdle = 5;
-
-    SleepingPolicy SIMPLE = new SleepingPolicy() {
-      @Override
-      public int getTimeToSleep(boolean wasActive) {
-        return wasActive ? sleepTimeWhenWasActive : sleepTimeWhenIdle;
-      }
-    };
-
-    int getTimeToSleep(boolean wasActive);
-  }
-
-  public static class AdaptiveSleepingPolicy implements SleepingPolicy {
-    private static final int maxSleepTimeWhenIdle = 200;
-    private static final int maxIterationsWithCurrentSleepTime = 50;
-
-    private volatile int myIterationsWithCurrentTime;
-    private volatile int myCurrentSleepTime = sleepTimeWhenIdle;
-
-    @Override
-    public int getTimeToSleep(boolean wasActive) {
-      int currentSleepTime = myCurrentSleepTime; // volatile read
-      if (wasActive) currentSleepTime = sleepTimeWhenWasActive;
-      else if (currentSleepTime == sleepTimeWhenWasActive) {
-        currentSleepTime = sleepTimeWhenIdle;
-        myIterationsWithCurrentTime = 0;
-      }
-      else {
-        int iterationsWithCurrentTime = ++myIterationsWithCurrentTime;
-        if (iterationsWithCurrentTime >= maxIterationsWithCurrentSleepTime) {
-          myIterationsWithCurrentTime = 0;
-          currentSleepTime = Math.min(2* currentSleepTime, maxSleepTimeWhenIdle);
-        }
-      }
-
-      myCurrentSleepTime = currentSleepTime; // volatile write
-      return currentSleepTime;
-    }
-  }
-
-  protected void doRun() {
-    try {
-      while (true) {
-        boolean read = readAvailable();
-
-        if (isStopped) {
-          break;
-        }
-
-        TimeoutUtil.sleep(mySleepingPolicy.getTimeToSleep(read));
-      }
-    }
-    catch (IOException e) {
-      LOG.info(e);
-    }
-    catch (Exception e) {
-      LOG.error(e);
-    }
-    finally {
-      try {
-        myReader.close();
-      }
-      catch (IOException e) {
-        LOG.error("Can't close stream", e);
-      }
-    }
   }
 
   /**
@@ -176,18 +84,10 @@
     return read;
   }
 
+  @Override
+  protected void close() throws IOException {
+    myReader.close();
+  }
+
   protected abstract void onTextAvailable(@NotNull String text);
-
-  public void stop() {
-    isStopped = true;
-  }
-
-  public void waitFor() throws InterruptedException {
-    try {
-      myFinishedFuture.get();
-    }
-    catch (ExecutionException e) {
-      LOG.error(e);
-    }
-  }
 }
diff --git a/platform/util/src/com/intellij/util/io/BinaryOutputReader.java b/platform/util/src/com/intellij/util/io/BinaryOutputReader.java
new file mode 100644
index 0000000..a80fb50
--- /dev/null
+++ b/platform/util/src/com/intellij/util/io/BinaryOutputReader.java
@@ -0,0 +1,58 @@
+/*
+ * 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.io;
+
+import org.jetbrains.annotations.NotNull;
+
+import java.io.IOException;
+import java.io.InputStream;
+
+/**
+* @author Konstantin Kolosovsky.
+*/
+public abstract class BinaryOutputReader extends BaseDataReader {
+
+  @NotNull private final InputStream myStream;
+  @NotNull private final byte[] myBuffer = new byte[8192];
+
+  public BinaryOutputReader(@NotNull InputStream stream, SleepingPolicy sleepingPolicy) {
+    super(sleepingPolicy);
+    myStream = stream;
+  }
+
+  @Override
+  protected boolean readAvailable() throws IOException {
+    byte[] buffer = myBuffer;
+
+    boolean read = false;
+    while (myStream.available() > 0) {
+      int n = myStream.read(buffer);
+      if (n <= 0) break;
+      read = true;
+
+      onBinaryAvailable(buffer, n);
+    }
+
+    return read;
+  }
+
+  protected abstract void onBinaryAvailable(@NotNull byte[] data, int size);
+
+  @Override
+  protected void close() throws IOException {
+    myStream.close();
+  }
+}
diff --git a/platform/util/src/com/intellij/util/io/IOUtil.java b/platform/util/src/com/intellij/util/io/IOUtil.java
index c10f04a..625b1e6 100644
--- a/platform/util/src/com/intellij/util/io/IOUtil.java
+++ b/platform/util/src/com/intellij/util/io/IOUtil.java
@@ -18,6 +18,7 @@
 import com.intellij.openapi.util.ThrowableComputable;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.CharsetToolkit;
+import com.intellij.reference.SoftReference;
 import com.intellij.util.SystemProperties;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
@@ -113,6 +114,8 @@
   }
 
   public static final Charset US_ASCII = Charset.forName("US-ASCII");
+  private static final ThreadLocal<SoftReference<char[]>> spareBufferLocal = new ThreadLocal<SoftReference<char[]>>();
+
   public static String readUTFFast(@NotNull byte[] buffer, @NotNull DataInput storage) throws IOException {
     int len = 0xFF & (int)storage.readByte();
     if (len == 0xFF) {
@@ -126,7 +129,15 @@
 
     if (len == 0) return "";
     storage.readFully(buffer, 0, len);
-    return new String(buffer, 0, len, US_ASCII);
+
+    SoftReference<char[]> reference = spareBufferLocal.get();
+    char[] chars = reference != null ? reference.get() : null;
+    if (chars == null) {
+      chars = new char[STRING_LENGTH_THRESHOLD];
+      spareBufferLocal.set(new SoftReference<char[]>(chars));
+    }
+    for(int i = 0; i < len; ++i) chars[i] = (char)(buffer[i] &0xFF);
+    return new String(chars, 0, len);
   }
 
   public static boolean isAscii(@NotNull String str) {
diff --git a/platform/util/src/com/intellij/util/io/ResizeableMappedFile.java b/platform/util/src/com/intellij/util/io/ResizeableMappedFile.java
index cfa73a8..f7a74f5 100644
--- a/platform/util/src/com/intellij/util/io/ResizeableMappedFile.java
+++ b/platform/util/src/com/intellij/util/io/ResizeableMappedFile.java
@@ -55,7 +55,8 @@
     if (myLogicalSize == 0) {
       try {
         getPagedFileStorage().lock();
-        resize(initialSize);
+        // use direct call to storage.resize() so that IOException is not masked with RuntimeException
+        myStorage.resize(initialSize);
       }
       finally {
         getPagedFileStorage().unlock();
diff --git a/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java b/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java
index 501e5e4..f2d3566 100644
--- a/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java
+++ b/platform/util/src/com/intellij/util/io/storage/RefCountingStorage.java
@@ -24,7 +24,7 @@
 import com.intellij.openapi.util.io.StreamUtil;
 import com.intellij.util.ConcurrencyUtil;
 import com.intellij.util.IncorrectOperationException;
-import com.intellij.util.containers.ConcurrentHashMap;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.io.PagePool;
 import com.intellij.util.io.UnsyncByteArrayInputStream;
 
@@ -39,7 +39,7 @@
 import java.util.zip.InflaterInputStream;
 
 public class RefCountingStorage extends AbstractStorage {
-  private final Map<Integer, Future<?>> myPendingWriteRequests = new ConcurrentHashMap<Integer, Future<?>>();
+  private final Map<Integer, Future<?>> myPendingWriteRequests = ContainerUtil.newConcurrentMap();
   private int myPendingWriteRequestsSize;
   private final ThreadPoolExecutor myPendingWriteRequestsExecutor = new ThreadPoolExecutor(1, 1, Long.MAX_VALUE, TimeUnit.DAYS, new LinkedBlockingQueue<Runnable>(), ConcurrencyUtil.newNamedThreadFactory("RefCountingStorage write content helper"));
 
diff --git a/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java b/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java
index 631b381..1b8f35a 100644
--- a/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java
+++ b/platform/util/src/com/intellij/util/pico/DefaultPicoContainer.java
@@ -16,7 +16,6 @@
 package com.intellij.util.pico;
 
 import com.intellij.util.ReflectionCache;
-import com.intellij.util.containers.ConcurrentHashMap;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.FList;
 import org.jetbrains.annotations.NotNull;
@@ -34,9 +33,9 @@
   private final PicoContainer parent;
   private final Set<PicoContainer> children = new HashSet<PicoContainer>();
 
-  private final Map<Object, ComponentAdapter> componentKeyToAdapterCache = new ConcurrentHashMap<Object, ComponentAdapter>();
+  private final Map<Object, ComponentAdapter> componentKeyToAdapterCache = ContainerUtil.newConcurrentMap();
   private final LinkedHashSetWrapper<ComponentAdapter> componentAdapters = new LinkedHashSetWrapper<ComponentAdapter>();
-  private final Map<String, ComponentAdapter> classNameToAdapter = new ConcurrentHashMap<String, ComponentAdapter>();
+  private final Map<String, ComponentAdapter> classNameToAdapter = ContainerUtil.newConcurrentMap();
   private final AtomicReference<FList<ComponentAdapter>> nonAssignableComponentAdapters = new AtomicReference<FList<ComponentAdapter>>(FList.<ComponentAdapter>emptyList());
 
   public DefaultPicoContainer(@NotNull ComponentAdapterFactory componentAdapterFactory, PicoContainer parent) {
diff --git a/platform/util/src/com/intellij/util/ui/UIUtil.java b/platform/util/src/com/intellij/util/ui/UIUtil.java
index 35075ac..ec92502 100644
--- a/platform/util/src/com/intellij/util/ui/UIUtil.java
+++ b/platform/util/src/com/intellij/util/ui/UIUtil.java
@@ -221,6 +221,11 @@
   }
 
   public static boolean isRetina() {
+    //Temporary workaround for HiDPI on Windows/Linux
+    if ("true".equalsIgnoreCase(System.getProperty("is.hidpi"))) {
+      return true;
+    }
+
     synchronized (ourRetina) {
       if (ourRetina.isNull()) {
         ourRetina.set(false); // in case HiDPIScaledImage.drawIntoImage is not called for some reason
diff --git a/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilLightTest.java b/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilLightTest.java
index 710e0c8..1e1295c 100644
--- a/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilLightTest.java
+++ b/platform/util/testSrc/com/intellij/openapi/util/io/FileUtilLightTest.java
@@ -19,12 +19,16 @@
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.PairProcessor;
 import com.intellij.util.ThreeState;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.Convertor;
 import org.junit.Test;
 
+import java.io.IOException;
+import java.io.StringReader;
 import java.util.Arrays;
 import java.util.Collection;
 import java.util.List;
+import java.util.Map;
 
 import static org.junit.Assert.*;
 
@@ -145,4 +149,11 @@
     assertFalse(FileUtil.startsWith("c:/idea2", "c:/idea"));
     assertFalse(FileUtil.startsWith("c:/idea_branches/i18n", "c:/idea"));
   }
+
+  @Test
+  public void testLoadProperties() throws IOException {
+    String data = "key2=value2\nkey1=value1\nkey3=value3";
+    Map<String, String> map = FileUtil.loadProperties(new StringReader(data));
+    assertEquals(ContainerUtil.newArrayList("key2", "key1", "key3"), ContainerUtil.newArrayList(map.keySet()));
+  }
 }
diff --git a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java
index 2914851..dfce147 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/diff/impl/dir/DirDiffTableModel.java
@@ -27,7 +27,7 @@
 import com.intellij.openapi.diff.impl.dir.actions.popup.WarnOnDeletion;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.MessageBuilder;
+import com.intellij.openapi.ui.MessageDialogBuilder;
 import com.intellij.openapi.ui.MessageType;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.ui.popup.Balloon;
@@ -804,7 +804,7 @@
   }
 
   private boolean confirmDeletion(int count) {
-    return MessageBuilder.yesNo("Confirm Delete", "Delete " + count + " items?").project(myProject).yesText("Delete").noText(CommonBundle.message("button.cancel")).doNotAsk(
+    return MessageDialogBuilder.yesNo("Confirm Delete", "Delete " + count + " items?").project(myProject).yesText("Delete").noText(CommonBundle.message("button.cancel")).doNotAsk(
       new DialogWrapper.DoNotAskOption() {
         @Override
         public boolean isToBeShown() {
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsActionPromoter.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsActionPromoter.java
new file mode 100644
index 0000000..bf7343e
--- /dev/null
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/actions/VcsActionPromoter.java
@@ -0,0 +1,42 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package com.intellij.openapi.vcs.actions;
+
+import com.intellij.openapi.actionSystem.ActionPromoter;
+import com.intellij.openapi.actionSystem.AnAction;
+import com.intellij.openapi.actionSystem.DataContext;
+import com.intellij.openapi.vcs.ui.Refreshable;
+
+import java.util.Arrays;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Konstantin Bulenkov
+ */
+public class VcsActionPromoter implements ActionPromoter {
+  @Override
+  public List<AnAction> promote(List<AnAction> actions, DataContext context) {
+    if (Refreshable.PANEL_KEY.getData(context) != null) {
+      for (AnAction action : actions) {
+        if (action instanceof ShowMessageHistoryAction) {
+          return Arrays.asList(action);
+        }
+      }
+    }
+    return Collections.emptyList();
+  }
+}
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/MatchPatchPaths.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/MatchPatchPaths.java
index 7f8b2e8..5dee17f 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/MatchPatchPaths.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/patch/MatchPatchPaths.java
@@ -84,7 +84,7 @@
           for (VirtualFile file : files) {
             Pair<VirtualFile, Integer> pair = compareNamesImpl(strings, file, i);
             if (pair != null && pair.getSecond() < i) {
-              if (best == null || pair.getSecond() > best.getSecond()) {
+              if (best == null || pair.getSecond() < best.getSecond()) {
                 best = pair;
               }
             }
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitChangeListDialog.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitChangeListDialog.java
index d32de17..71c0c8f 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitChangeListDialog.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ui/CommitChangeListDialog.java
@@ -28,10 +28,7 @@
 import com.intellij.openapi.progress.ProgressManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.*;
-import com.intellij.openapi.util.Comparing;
-import com.intellij.openapi.util.Disposer;
-import com.intellij.openapi.util.Getter;
-import com.intellij.openapi.util.Ref;
+import com.intellij.openapi.util.*;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vcs.*;
 import com.intellij.openapi.vcs.changes.*;
@@ -585,15 +582,17 @@
       @Override
       public void run() {
         try {
-          runBeforeCommitHandlers(new Runnable() {
-              @Override
-              public void run() {
-                CommitChangeListDialog.super.doOKAction();
-                doCommit(myResultHandler);
-              }
-            }, null);
+          CheckinHandler.ReturnResult result = runBeforeCommitHandlers(new Runnable() {
+            @Override
+            public void run() {
+              CommitChangeListDialog.super.doOKAction();
+              doCommit(myResultHandler);
+            }
+          }, null);
 
-          defaultListCleaner.clean();
+          if (result == CheckinHandler.ReturnResult.COMMIT) {
+            defaultListCleaner.clean();
+          }
         }
         catch (InputException ex) {
           ex.show();
@@ -854,10 +853,10 @@
     myUpdateButtonsRunnable.restart(this);
   }
   
-  private void runBeforeCommitHandlers(final Runnable okAction, final CommitExecutor executor) {
-    Runnable proceedRunnable = new Runnable() {
+  private CheckinHandler.ReturnResult runBeforeCommitHandlers(final Runnable okAction, final CommitExecutor executor) {
+    final Computable<CheckinHandler.ReturnResult> proceedRunnable = new Computable<CheckinHandler.ReturnResult>() {
       @Override
-      public void run() {
+      public CheckinHandler.ReturnResult compute() {
         FileDocumentManager.getInstance().saveAllDocuments();
 
         for (CheckinHandler handler : myHandlers) {
@@ -866,7 +865,7 @@
           if (result == CheckinHandler.ReturnResult.COMMIT) continue;
           if (result == CheckinHandler.ReturnResult.CANCEL) {
             restartUpdate();
-            return;
+            return CheckinHandler.ReturnResult.CANCEL;
           }
 
           if (result == CheckinHandler.ReturnResult.CLOSE_WINDOW) {
@@ -877,16 +876,23 @@
                              VcsBundle.message("commit.dialog.rejected.commit.template", changeList.getName()),
                              myProject);
             doCancelAction();
-            return;
+            return CheckinHandler.ReturnResult.CLOSE_WINDOW;
           }
         }
 
         okAction.run();
+        return CheckinHandler.ReturnResult.COMMIT;
       }
     };
 
     stopUpdate();
-    Runnable runnable = proceedRunnable;
+    final Ref<CheckinHandler.ReturnResult> compoundResultRef = Ref.create();
+    Runnable runnable = new Runnable() {
+      @Override
+      public void run() {
+        compoundResultRef.set(proceedRunnable.compute());
+      }
+    };
     for(final CheckinHandler handler: myHandlers) {
       if (handler instanceof CheckinMetaHandler) {
         final Runnable previousRunnable = runnable;
@@ -899,6 +905,7 @@
       }
     }
     runnable.run();
+    return compoundResultRef.get();
   }
 
   private boolean saveDialogState() {
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsDirectoryConfigurationPanel.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsDirectoryConfigurationPanel.java
index 4c5b10c..05ba63f 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsDirectoryConfigurationPanel.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/configurable/VcsDirectoryConfigurationPanel.java
@@ -34,6 +34,7 @@
 import com.intellij.ui.components.labels.LinkLabel;
 import com.intellij.ui.components.labels.LinkListener;
 import com.intellij.ui.table.TableView;
+import com.intellij.util.UriUtil;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.ui.*;
 import com.intellij.xml.util.XmlStringUtil;
@@ -106,7 +107,7 @@
         String directory = mapping.getDirectory();
         VirtualFile baseDir = myProject.getBaseDir();
         if (baseDir != null) {
-          final File directoryFile = new File(StringUtil.trimEnd(StringUtil.trimEnd(directory, "/"), "\\") + "/");
+          final File directoryFile = new File(StringUtil.trimEnd(UriUtil.trimLastSlash(directory), "\\") + "/");
           File ioBase = new File(baseDir.getPath());
           if (directoryFile.isAbsolute() && !FileUtil.isAncestor(ioBase, directoryFile, false)) {
             append(new File(directory).getPath());
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetectInfo.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetectInfo.java
index 64e3277..eae6956 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetectInfo.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetectInfo.java
@@ -12,29 +12,17 @@
 public class VcsRootDetectInfo {
 
   private final @NotNull Collection<VcsRoot> myRoots;
-  private final boolean myFull;
   private final boolean myBelow;
 
   /**
    * @param roots Vcs roots important for the project.
-   * @param full  Pass true to indicate that the project is fully under Vcs.
    * @param below Pass true to indicate that the project dir is below Vcs dir,
-   *              i.e. .git is above the project dir, and there is no DOT dir directly under the project dir.
    */
-  public VcsRootDetectInfo(@NotNull Collection<VcsRoot> roots, boolean full, boolean below) {
+  public VcsRootDetectInfo(@NotNull Collection<VcsRoot> roots, boolean below) {
     myRoots = new ArrayList<VcsRoot>(roots);
-    myFull = full;
     myBelow = below;
   }
 
-  /**
-   * @return True if the project is fully under Vcs.
-   * It is true if f.e. .git is directly inside or above the project dir.
-   */
-  public boolean totallyUnderVcs() {
-    return myFull;
-  }
-
   public boolean empty() {
     return myRoots.isEmpty();
   }
diff --git a/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetector.java b/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetector.java
index 1fb3689..d298baa 100644
--- a/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetector.java
+++ b/platform/vcs-impl/src/com/intellij/openapi/vcs/roots/VcsRootDetector.java
@@ -37,22 +37,22 @@
   @NotNull
   public VcsRootDetectInfo detect(@Nullable VirtualFile startDir) {
     if (startDir == null) {
-      return new VcsRootDetectInfo(Collections.<VcsRoot>emptyList(), false, false);
+      return new VcsRootDetectInfo(Collections.<VcsRoot>emptyList(), false);
     }
 
     final Set<VcsRoot> roots = scanForRootsInsideDir(startDir);
     roots.addAll(scanForRootsInContentRoots());
     for (VcsRoot root : roots) {
       if (startDir.equals(root.getPath())) {
-        return new VcsRootDetectInfo(roots, true, false);
+        return new VcsRootDetectInfo(roots, false);
       }
     }
     List<VcsRoot> rootsAbove = scanForSingleRootAboveDir(startDir);
     if (!rootsAbove.isEmpty()) {
       roots.addAll(rootsAbove);
-      return new VcsRootDetectInfo(roots, true, true);
+      return new VcsRootDetectInfo(roots, true);
     }
-    return new VcsRootDetectInfo(roots, false, false);
+    return new VcsRootDetectInfo(roots, false);
   }
 
   @NotNull
diff --git a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootDetectorTest.java b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootDetectorTest.java
index 75e1b30..8a5e862 100644
--- a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootDetectorTest.java
+++ b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootDetectorTest.java
@@ -16,6 +16,7 @@
 package com.intellij.openapi.vcs.roots;
 
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vcs.VcsRoot;
 import com.intellij.openapi.vcs.VcsTestUtil;
@@ -42,14 +43,14 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Collections.<String>emptyList());
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, null, Collections.<String>emptyList(), false, false);
+    doTest(map, null, Collections.<String>emptyList());
   }
 
   public void testProjectUnderSingleMockRoot() throws IOException {
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList("."));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myProjectRoot, Arrays.asList("."), true, false);
+    doTest(map, myProjectRoot, Arrays.asList("."));
   }
 
   public void testProjectWithMockRootUnderIt() throws IOException {
@@ -59,7 +60,7 @@
     cd(myProjectRoot);
     mkdir("src");
     mkdir(".idea");
-    doTest(map, myProjectRoot, Arrays.asList("community"), false, false);
+    doTest(map, myProjectRoot, Arrays.asList("community"));
   }
 
   public void testProjectWithAllSubdirsUnderMockRootShouldStillBeNotFullyControlled() throws IOException {
@@ -67,7 +68,7 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(dirNames));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myProjectRoot, Arrays.asList(dirNames), false, false);
+    doTest(map, myProjectRoot, Arrays.asList(dirNames));
   }
 
   public void testProjectUnderVcsAboveIt() throws IOException {
@@ -78,8 +79,8 @@
     map.put("mock", Arrays.asList(myRepository.getName()));
     map.put("content_roots", Collections.<String>emptyList());
     VirtualFile vfile = myRepository.findChild(subdir);
-    doTest(map, vfile, Arrays.asList(myRepository.getName()),
-           true, true);
+    doTest(map, vfile, Arrays.asList(myRepository.getName())
+    );
   }
 
   public void testIDEAProject() throws IOException {
@@ -87,7 +88,7 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(names));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myProjectRoot, Arrays.asList(names), true, false);
+    doTest(map, myProjectRoot, Arrays.asList(names));
   }
 
   public void testOneAboveAndOneUnder() throws IOException {
@@ -95,7 +96,7 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(names));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myRepository, Arrays.asList(names), true, true);
+    doTest(map, myRepository, Arrays.asList(names));
   }
 
   public void testOneAboveAndOneForProjectShouldShowOnlyProjectRoot() throws IOException {
@@ -103,7 +104,7 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(names));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myRepository, Arrays.asList(myRepository.getName()), true, false);
+    doTest(map, myRepository, Arrays.asList(myRepository.getName()));
   }
 
   public void testOneAboveAndSeveralUnderProject() throws IOException {
@@ -111,7 +112,7 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(names));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myRepository, Arrays.asList(names), true, true);
+    doTest(map, myRepository, Arrays.asList(names));
   }
 
   public void testMultipleAboveShouldBeDetectedAsOneAbove() throws IOException {
@@ -122,14 +123,14 @@
     cd(myRepository);
     mkdir(subdir);
     VirtualFile vfile = myRepository.findChild(subdir);
-    doTest(map, vfile, Arrays.asList(myRepository.getName()), true, true);
+    doTest(map, vfile, Arrays.asList(myRepository.getName()));
   }
 
   public void testUnrelatedRootShouldNotBeDetected() throws IOException {
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList("another"));
     map.put("content_roots", Collections.<String>emptyList());
-    doTest(map, myRepository, Collections.<String>emptyList(), false, false);
+    doTest(map, myRepository, Collections.<String>emptyList());
   }
 
 
@@ -137,21 +138,21 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList("linked_root"));
     map.put("content_roots", Arrays.asList("linked_root"));
-    doTest(map, myRepository, Arrays.asList("linked_root"), false, false);
+    doTest(map, myRepository, Arrays.asList("linked_root"));
   }
 
   public void testLinkedSourceRootAndProjectRootShouldBeDetected() throws IOException {
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(".", "linked_root"));
     map.put("content_roots", Arrays.asList("linked_root"));
-    doTest(map, myProjectRoot, Arrays.asList(".", "linked_root"), true, false);
+    doTest(map, myProjectRoot, Arrays.asList(".", "linked_root"));
   }
 
   public void testLinkedSourceBelowMockRoot() throws IOException {
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList(".", "linked_root"));
     map.put("content_roots", Arrays.asList("linked_root/src"));
-    doTest(map, myProjectRoot, Arrays.asList(".", "linked_root"), true, false);
+    doTest(map, myProjectRoot, Arrays.asList(".", "linked_root"));
   }
 
   // This is a test of performance optimization via limitation: don't scan deep though the whole VFS, i.e. don't detect deep roots
@@ -159,7 +160,7 @@
     Map<String, Collection<String>> map = new HashMap<String, Collection<String>>();
     map.put("mock", Arrays.asList("community", "content_root/lev1/lev2", "content_root2/lev1/lev2/lev3"));
     map.put("content_roots", Arrays.asList("content_root"));
-    doTest(map, myProjectRoot, Arrays.asList("community", "content_root/lev1/lev2"), false, false);
+    doTest(map, myProjectRoot, Arrays.asList("community", "content_root/lev1/lev2"));
   }
 
   void assertRoots(Collection<String> expectedRelativePaths, Collection<String> actual) {
@@ -202,15 +203,18 @@
 
   public void doTest(@NotNull Map<String, Collection<String>> map,
                      @Nullable VirtualFile startDir,
-                     @NotNull Collection<String> expectedPaths,
-                     boolean expectedFull,
-                     boolean expectedBelow)
+                     @NotNull Collection<String> expectedPaths)
     throws IOException {
     initProject(map.get("mock"), Collections.<String>emptyList(), map.get("content_roots"));
 
     VcsRootDetectInfo info = detect(startDir);
-    assertRoots(expectedPaths, getPaths(info.getRoots()));
-    assertEquals(expectedFull, info.totallyUnderVcs());
-    assertEquals(expectedBelow, info.projectIsBelowVcs());
+    assertRoots(expectedPaths, getPaths(
+      ContainerUtil.filter(info.getRoots(), new Condition<VcsRoot>() {
+        @Override
+        public boolean value(VcsRoot root) {
+          assert root.getVcs() != null;
+          return root.getVcs().getKeyInstanceMethod().equals(myVcs.getKeyInstanceMethod());
+        }
+      })));
   }
 }
diff --git a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootErrorsFinderTest.java b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootErrorsFinderTest.java
index 462186c..80a9ce9 100644
--- a/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootErrorsFinderTest.java
+++ b/platform/vcs-impl/testSrc/com/intellij/openapi/vcs/roots/VcsRootErrorsFinderTest.java
@@ -15,9 +15,11 @@
  */
 package com.intellij.openapi.vcs.roots;
 
+import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.vcs.VcsDirectoryMapping;
 import com.intellij.openapi.vcs.VcsRootError;
 import com.intellij.openapi.vcs.VcsTestUtil;
+import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 
 import java.io.IOException;
@@ -218,7 +220,12 @@
     if (extraPaths != null) {
       expected.addAll(extraAll(extraPaths));
     }
-    Collection<VcsRootError> actual = new VcsRootErrorsFinder(myProject).find();
+    Collection<VcsRootError> actual = ContainerUtil.filter(new VcsRootErrorsFinder(myProject).find(), new Condition<VcsRootError>() {
+      @Override
+      public boolean value(VcsRootError error) {
+        return error.getVcsKey().equals(myVcs.getKeyInstanceMethod());
+      }
+    });
     VcsTestUtil.assertEqualCollections(actual, expected);
   }
 
diff --git a/platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogProvider.java b/platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogProvider.java
index 75460f6..37000a7 100644
--- a/platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogProvider.java
+++ b/platform/vcs-log/api/src/com/intellij/vcs/log/VcsLogProvider.java
@@ -87,4 +87,10 @@
   @Nullable
   VcsUser getCurrentUser(@NotNull VirtualFile root) throws VcsException;
 
+  /**
+   * Returns the list of names of branches/references which contain the given commit.
+   */
+  @NotNull
+  Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException;
+
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.java
index 5db2212..8ac6e84 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/data/ContainingBranchesGetter.java
@@ -18,19 +18,18 @@
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.vcs.VcsException;
+import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.ThrowableConsumer;
-import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.SLRUMap;
-import com.intellij.vcs.log.VcsRef;
-import com.intellij.vcs.log.graph.elements.Edge;
-import com.intellij.vcs.log.graph.elements.Node;
+import com.intellij.vcs.log.Hash;
 import com.intellij.vcs.log.util.SequentialLimitedLifoExecutor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.awt.*;
-import java.util.*;
+import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 
 /**
@@ -41,20 +40,22 @@
   private static final Logger LOG = Logger.getInstance(ContainingBranchesGetter.class);
 
   @NotNull private final SequentialLimitedLifoExecutor<Task> myTaskExecutor;
-  @NotNull private volatile SLRUMap<Node, List<VcsRef>> myCache = createCache();
+  @NotNull private final VcsLogDataHolder myDataHolder;
+  @NotNull private volatile SLRUMap<Hash, List<String>> myCache = createCache();
   @Nullable private Runnable myLoadingFinishedListener; // access only from EDT
 
-  ContainingBranchesGetter(@NotNull Disposable parentDisposable) {
+  ContainingBranchesGetter(@NotNull VcsLogDataHolder dataHolder, @NotNull Disposable parentDisposable) {
+    myDataHolder = dataHolder;
     myTaskExecutor = new SequentialLimitedLifoExecutor<Task>(parentDisposable, 10, new ThrowableConsumer<Task, Throwable>() {
       @Override
       public void consume(final Task task) throws Throwable {
-        final List<VcsRef> branches = getContainingBranches(task.pack, task.node);
+        final List<String> branches = getContainingBranches(task.root, task.hash);
         ApplicationManager.getApplication().invokeLater(new Runnable() {
           @Override
           public void run() {
             // if cache is cleared (because of log refresh) during this task execution,
             // this will put obsolete value into the old instance we don't care anymore
-            task.cache.put(task.node, branches);
+            task.cache.put(task.hash, branches);
             notifyListener();
           }
         });
@@ -94,83 +95,40 @@
    * if it is not available, starts calculating in the background and returns null.
    */
   @Nullable
-  public List<VcsRef> requestContainingBranches(@NotNull DataPack dataPack, @NotNull Node node) {
-    List<VcsRef> refs = myCache.get(node);
+  public List<String> requestContainingBranches(@NotNull VirtualFile root, @NotNull Hash hash) {
+    List<String> refs = myCache.get(hash);
     if (refs == null) {
-      myTaskExecutor.queue(new Task(dataPack, node, myCache));
+      myTaskExecutor.queue(new Task(root, hash, myCache));
     }
     return refs;
   }
 
   @NotNull
-  private static SLRUMap<Node, List<VcsRef>> createCache() {
-    return new SLRUMap<Node, List<VcsRef>>(1000, 1000);
+  private static SLRUMap<Hash, List<String>> createCache() {
+    return new SLRUMap<Hash, List<String>>(1000, 1000);
   }
 
   @NotNull
-  private List<VcsRef> getContainingBranches(@NotNull DataPack dataPack, @NotNull Node node) {
-    RefsModel refsModel = dataPack.getRefsModel();
-    Set<VcsRef> containingBranches = ContainerUtil.newHashSet();
-
-    Set<Node> visitedNodes = ContainerUtil.newHashSet();
-    Set<Node> nodesToCheck = ContainerUtil.newHashSet();
-    nodesToCheck.add(node);
-    while (!nodesToCheck.isEmpty()) {
-      Iterator<Node> nodeIterator = nodesToCheck.iterator();
-      Node nextNode = nodeIterator.next();
-      nodeIterator.remove();
-
-      if (!visitedNodes.add(nextNode)) {
-        continue;
-      }
-
-      for (Edge edge : nextNode.getUpEdges()) {
-        Node upNode = edge.getUpNode();
-        // optimization: the node is contained in all branches which contain its child => no need to walk over this graph branch
-        List<VcsRef> upRefs = myCache.get(upNode);
-        if (upRefs != null) {
-          containingBranches.addAll(upRefs);
-        }
-        else {
-          nodesToCheck.add(upNode);
-        }
-      }
-
-      containingBranches.addAll(getBranchesPointingToThisNode(refsModel, nextNode));
+  private List<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash hash) {
+    try {
+      List<String> branches = new ArrayList<String>(myDataHolder.getLogProvider(root).getContainingBranches(root, hash));
+      Collections.sort(branches);
+      return branches;
     }
-
-    return sortByName(containingBranches);
-  }
-
-  @NotNull
-  private static Collection<VcsRef> getBranchesPointingToThisNode(@NotNull RefsModel refsModel, @NotNull Node node) {
-    return ContainerUtil.filter(refsModel.refsToCommit(node.getCommitIndex()), new Condition<VcsRef>() {
-      @Override
-      public boolean value(VcsRef ref) {
-        return ref.getType().isBranch();
-      }
-    });
-  }
-
-  private static List<VcsRef> sortByName(Collection<VcsRef> branches) {
-    List<VcsRef> branchesList = new ArrayList<VcsRef>(branches);
-    ContainerUtil.sort(branchesList, new Comparator<VcsRef>() {
-      @Override
-      public int compare(VcsRef o1, VcsRef o2) {
-        return o1.getName().compareTo(o2.getName());
-      }
-    });
-    return branchesList;
+    catch (VcsException e) {
+      LOG.warn(e);
+      return Collections.emptyList();
+    }
   }
 
   private static class Task {
-    private final DataPack pack;
-    private final Node node;
-    private final SLRUMap<Node, List<VcsRef>> cache;
+    private final VirtualFile root;
+    private final Hash hash;
+    private final SLRUMap<Hash, List<String>> cache;
 
-    public Task(DataPack pack, Node node, SLRUMap<Node, List<VcsRef>> cache) {
-      this.pack = pack;
-      this.node = node;
+    public Task(VirtualFile root, Hash hash, SLRUMap<Hash, List<String>> cache) {
+      this.root = root;
+      this.hash = hash;
       this.cache = cache;
     }
   }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogDataHolder.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogDataHolder.java
index de7b48f..266cb14 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogDataHolder.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/data/VcsLogDataHolder.java
@@ -148,8 +148,9 @@
   private final NotNullFunction<Hash, Integer> myIndexGetter;
   private final ContainingBranchesGetter myContainingBranchesGetter;
 
-  public VcsLogDataHolder(@NotNull Project project,
+  public VcsLogDataHolder(@NotNull Project project, @NotNull Disposable parentDisposable,
                           @NotNull Map<VirtualFile, VcsLogProvider> logProviders, @NotNull VcsLogSettings settings) {
+    Disposer.register(parentDisposable, this);
     myProject = project;
     myLogProviders = logProviders;
     myDataLoaderQueue = new BackgroundTaskQueue(project, "Loading history...");
@@ -181,7 +182,7 @@
         return putHash(hash);
       }
     };
-    myContainingBranchesGetter = new ContainingBranchesGetter(this);
+    myContainingBranchesGetter = new ContainingBranchesGetter(this, this);
   }
 
   @NotNull
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java
index fc2a77e..d748015 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogContentProvider.java
@@ -30,6 +30,8 @@
  */
 public class VcsLogContentProvider implements ChangesViewContentProvider, NotNullFunction<Project, Boolean> {
 
+  public static final String TAB_NAME = "Log";
+
   @NotNull private final VcsLogManager myLogManager;
 
   public VcsLogContentProvider(@NotNull VcsLogManager logManager) {
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java
index 525a774..e06fc4e 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogManager.java
@@ -31,6 +31,7 @@
 import com.intellij.vcs.log.ui.VcsLogColorManagerImpl;
 import com.intellij.vcs.log.ui.VcsLogUI;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.awt.*;
@@ -51,8 +52,8 @@
   @NotNull private final VcsLogUiProperties myUiProperties;
 
   private PostponeableLogRefresher myLogRefresher;
-  private VcsLogDataHolder myLogDataHolder;
-  private VcsLogUI myUi;
+  private volatile VcsLogDataHolder myLogDataHolder;
+  private volatile VcsLogUI myUi;
 
   public VcsLogManager(@NotNull Project project, @NotNull ProjectLevelVcsManager vcsManager,
                        @NotNull VcsLogSettings settings,
@@ -69,11 +70,10 @@
     final Map<VirtualFile, VcsLogProvider> logProviders = findLogProviders();
     final VcsLogContainer mainPanel = new VcsLogContainer(myProject);
 
-    myLogDataHolder = new VcsLogDataHolder(myProject, logProviders, mySettings);
+    myLogDataHolder = new VcsLogDataHolder(myProject, this, logProviders, mySettings);
     myLogDataHolder.initialize(new Consumer<VcsLogDataHolder>() {
       @Override
       public void consume(VcsLogDataHolder vcsLogDataHolder) {
-        Disposer.register(VcsLogManager.this, vcsLogDataHolder);
         VcsLogUI logUI = new VcsLogUI(vcsLogDataHolder, myProject, mySettings,
                                       new VcsLogColorManagerImpl(logProviders.keySet()), myUiProperties);
         myLogDataHolder = vcsLogDataHolder;
@@ -114,11 +114,18 @@
     return logProviders;
   }
 
+  /**
+   * The instance of the {@link VcsLogDataHolder} or null if the log was not initialized yet.
+   */
+  @Nullable
   public VcsLogDataHolder getDataHolder() {
     return myLogDataHolder;
   }
 
-  @NotNull
+  /**
+   * The instance of the {@link VcsLogUI} or null if the log was not initialized yet.
+   */
+  @Nullable
   public VcsLogUI getLogUi() {
     return myUi;
   }
@@ -155,7 +162,6 @@
   private static class PostponeableLogRefresher implements VcsLogRefresher, Disposable {
 
     private  static final String TOOLWINDOW_ID = ChangesViewContentManager.TOOLWINDOW_ID;
-    private static final String TAB_NAME = "Log";
 
     @NotNull private final VcsLogDataHolder myDataHolder;
     @NotNull private final ToolWindowManagerImpl myToolWindowManager;
@@ -211,7 +217,7 @@
     private boolean isOurContentPaneShowing() {
       if (myToolWindowManager.isToolWindowRegistered(TOOLWINDOW_ID) && myToolWindow.isVisible()) {
         Content content = myToolWindow.getContentManager().getSelectedContent();
-        return content != null && content.getTabName().equals(TAB_NAME);
+        return content != null && content.getTabName().equals(VcsLogContentProvider.TAB_NAME);
       }
       return false;
     }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogObjectsFactoryImpl.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogObjectsFactoryImpl.java
index 132222c..7ad114a 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogObjectsFactoryImpl.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/impl/VcsLogObjectsFactoryImpl.java
@@ -1,5 +1,6 @@
 package com.intellij.vcs.log.impl;
 
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.vcs.changes.Change;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.NotNullFunction;
@@ -14,6 +15,8 @@
  */
 public class VcsLogObjectsFactoryImpl implements VcsLogObjectsFactory {
 
+  private static final Logger LOG = Logger.getInstance(VcsLogObjectsFactoryImpl.class);
+
   @NotNull private final VcsLogManager myLogManager;
 
   public VcsLogObjectsFactoryImpl(@NotNull VcsLogManager logManager) {
@@ -77,7 +80,12 @@
       @NotNull
       @Override
       public Integer fun(Hash hash) {
-        return myLogManager.getDataHolder().putHash(hash);
+        VcsLogDataHolder dataHolder = myLogManager.getDataHolder();
+        if (dataHolder == null) {
+          LOG.error("The log data holder should have been initialized at this point");
+          return -1;
+        }
+        return dataHolder.putHash(hash);
       }
     }, commitHash, name, type, root);
   }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/GoToRefAction.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/GoToRefAction.java
index 4514217..12e67eb 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/GoToRefAction.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/GoToRefAction.java
@@ -61,7 +61,7 @@
   @Override
   public void update(AnActionEvent e) {
     VcsLog log = e.getData(VcsLogDataKeys.VSC_LOG);
-    getTemplatePresentation().setEnabledAndVisible(e.getProject() != null && log != null);
+    e.getPresentation().setEnabledAndVisible(e.getProject() != null && log != null);
   }
 
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogQuickSettingsActions.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogQuickSettingsActions.java
index 36ce6fd..e047633 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogQuickSettingsActions.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogQuickSettingsActions.java
@@ -38,10 +38,10 @@
     }
     VcsLogSettings settings = ServiceManager.getService(project, VcsLogSettings.class);
     VcsLogManager logManager = ServiceManager.getService(project, VcsLogManager.class);
-    if (settings == null || logManager == null) {
+    VcsLogUI logUi = logManager.getLogUi();
+    if (logUi == null) {
       return;
     }
-    VcsLogUI logUi = logManager.getLogUi();
 
     ActionGroup settingsGroup = new MySettingsActionGroup(settings, logUi);
     ActionPopupMenu popupMenu = ActionManager.getInstance().createActionPopupMenu(ToolWindowContentUi.POPUP_PLACE, settingsGroup);
@@ -55,6 +55,18 @@
     popupMenu.getComponent().show(inputEvent.getComponent(), x, y);
   }
 
+  @Override
+  public void update(AnActionEvent e) {
+    Project project = e.getProject();
+    if (project == null) {
+      e.getPresentation().setEnabledAndVisible(false);
+    }
+    else {
+      VcsLogManager logManager = ServiceManager.getService(project, VcsLogManager.class);
+      e.getPresentation().setEnabledAndVisible(logManager.getLogUi() != null);
+    }
+  }
+
   private static class MySettingsActionGroup extends ActionGroup {
 
     private final VcsLogSettings mySettings;
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogUI.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogUI.java
index 7706c2b..c15af9f 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogUI.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/VcsLogUI.java
@@ -90,9 +90,7 @@
     UIUtil.invokeLaterIfNeeded(new Runnable() {
       @Override
       public void run() {
-        myMainFrame.getGraphTable().setPreferredColumnWidths();
         myMainFrame.getGraphTable().repaint();
-        myMainFrame.refresh();
       }
     });
   }
@@ -274,4 +272,9 @@
   public Component getToolbar() {
     return myMainFrame.getToolbar();
   }
+
+  @NotNull
+  public VcsLog getVcsLog() {
+    return myLog;
+  }
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/BranchesPanel.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/BranchesPanel.java
index 70dad07..44f58dd 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/BranchesPanel.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/BranchesPanel.java
@@ -1,6 +1,7 @@
 package com.intellij.vcs.log.ui.frame;
 
 import com.google.common.collect.Ordering;
+import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.JBPopup;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -75,6 +76,14 @@
         }
       }
     });
+
+    Project project = dataHolder.getProject();
+    project.getMessageBus().connect(project).subscribe(VcsLogDataHolder.REFRESH_COMPLETED, new Runnable() {
+      @Override
+      public void run() {
+        rebuild();
+      }
+    });
   }
 
   @Nullable
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java
index b37092e..248bfd9 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/DetailsPanel.java
@@ -8,14 +8,15 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.ui.BrowserHyperlinkListener;
 import com.intellij.ui.ScrollPaneFactory;
+import com.intellij.ui.components.JBLabel;
 import com.intellij.ui.components.JBLoadingPanel;
-import com.intellij.util.Function;
+import com.intellij.ui.components.JBTextField;
 import com.intellij.util.text.DateFormatUtil;
+import com.intellij.util.ui.AsyncProcessIcon;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.vcs.log.Hash;
 import com.intellij.vcs.log.VcsFullCommitDetails;
 import com.intellij.vcs.log.VcsRef;
-import com.intellij.vcs.log.data.DataPack;
 import com.intellij.vcs.log.data.LoadingDetails;
 import com.intellij.vcs.log.data.VcsLogDataHolder;
 import com.intellij.vcs.log.graph.render.PrintParameters;
@@ -48,6 +49,7 @@
 
   @NotNull private final RefsPanel myRefsPanel;
   @NotNull private final DataPanel myDataPanel;
+  @NotNull private final ContainingBranchesPanel myContainingBranchesPanel;
   @NotNull private final MessagePanel myMessagePanel;
   @NotNull private final JBLoadingPanel myLoadingPanel;
 
@@ -58,11 +60,13 @@
 
     myRefsPanel = new RefsPanel(colorManager);
     myDataPanel = new DataPanel(logDataHolder.getProject());
+    myContainingBranchesPanel = new ContainingBranchesPanel();
     myMessagePanel = new MessagePanel();
 
     Box content = Box.createVerticalBox();
     content.add(myRefsPanel);
     content.add(myDataPanel);
+    content.add(myContainingBranchesPanel);
     content.setBorder(BorderFactory.createEmptyBorder(0, 5, 0, 5));
 
     myLoadingPanel = new JBLoadingPanel(new BorderLayout(), logDataHolder, ProgressWindow.DEFAULT_PROGRESS_DIALOG_POSTPONE_TIME_MILLIS);
@@ -94,18 +98,22 @@
       }
 
       VcsFullCommitDetails commitData = myLogDataHolder.getCommitDetailsGetter().getCommitData(hash);
-      DataPack dataPack = myLogDataHolder.getDataPack();
-      List<VcsRef> branches = myLogDataHolder.getContainingBranchesGetter().requestContainingBranches(dataPack, dataPack.getNode(row));
-      if (commitData instanceof LoadingDetails || branches == null) {
+      if (commitData instanceof LoadingDetails) {
         myLoadingPanel.startLoading();
-        myDataPanel.setData(null, null);
+        myDataPanel.setData(null);
         myRefsPanel.setRefs(Collections.<VcsRef>emptyList());
       }
       else {
         myLoadingPanel.stopLoading();
-        myDataPanel.setData(commitData, branches);
+        myDataPanel.setData(commitData);
         myRefsPanel.setRefs(sortRefs(hash, commitData.getRoot()));
       }
+
+      List<String> branches = null;
+      if (!(commitData instanceof LoadingDetails)) {
+        branches = myLogDataHolder.getContainingBranchesGetter().requestContainingBranches(commitData.getRoot(), hash);
+      }
+      myContainingBranchesPanel.setBranches(branches);
     }
   }
 
@@ -130,30 +138,20 @@
       setEditable(false);
       myProject = project;
       addHyperlinkListener(new BrowserHyperlinkListener());
-      setPreferredSize(new Dimension(150, 100));
+      setOpaque(false);
     }
 
-    void setData(@Nullable VcsFullCommitDetails commit, @Nullable List<VcsRef> branches) {
-      if (commit == null || branches == null) {
+    void setData(@Nullable VcsFullCommitDetails commit) {
+      if (commit == null) {
         setText("");
       }
       else {
-        String body = getHashText(commit) + "<br/>" + getAuthorText(commit) + "<p>" + getMessageText(commit) + "</p>" +
-                      "<p>" + getContainedBranchesText(branches) + "</p>";
+        String body = getHashText(commit) + "<br/>" + getAuthorText(commit) + "<p>" + getMessageText(commit) + "</p>";
         setText("<html><head>" + UIUtil.getCssFontDeclaration(UIUtil.getLabelFont()) + "</head><body>" + body + "</body></html>");
         setCaretPosition(0);
       }
     }
 
-    private static String getContainedBranchesText(List<VcsRef> branches) {
-      return "<i>Contained in branches:</i> " + StringUtil.join(branches, new Function<VcsRef, String>() {
-        @Override
-        public String fun(VcsRef ref) {
-          return ref.getName();
-        }
-      }, ", ");
-    }
-
     private String getMessageText(VcsFullCommitDetails commit) {
       String subject = commit.getSubject();
       String description = subject.length() < commit.getFullMessage().length() ? commit.getFullMessage().substring(subject.length()) : "";
@@ -184,6 +182,46 @@
     }
   }
 
+  private static class ContainingBranchesPanel extends JPanel {
+
+    private final JComponent myLoadingIcon;
+    private final JTextField myBranchesList;
+
+    ContainingBranchesPanel() {
+      JLabel label = new JBLabel("Contained in branches: ");
+      label.setFont(label.getFont().deriveFont(Font.ITALIC));
+      myLoadingIcon = new AsyncProcessIcon("Loading...");
+      myBranchesList = new JBTextField("");
+      myBranchesList.setEditable(false);
+      myBranchesList.setBorder(null);
+
+      setOpaque(false);
+      setLayout(new BoxLayout(this, BoxLayout.X_AXIS));
+      add(label);
+      add(myLoadingIcon);
+      add(myBranchesList);
+      add(Box.createHorizontalGlue());
+    }
+
+    void setBranches(@Nullable List<String> branches) {
+      if (branches == null) {
+        myLoadingIcon.setVisible(true);
+        myBranchesList.setVisible(false);
+      }
+      else {
+        myLoadingIcon.setVisible(false);
+        myBranchesList.setVisible(true);
+        myBranchesList.setText(getContainedBranchesText(branches));
+      }
+    }
+
+    @NotNull
+    private static String getContainedBranchesText(@NotNull List<String> branches) {
+      return StringUtil.join(branches, ", ");
+    }
+
+  }
+
   private static class RefsPanel extends JPanel {
 
     @NotNull private final RefPainter myRefPainter;
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/MainFrame.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/MainFrame.java
index 04a3e3e..8c6fd2f 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/MainFrame.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/MainFrame.java
@@ -4,6 +4,7 @@
 import com.intellij.ide.actions.RefreshAction;
 import com.intellij.openapi.Disposable;
 import com.intellij.openapi.actionSystem.*;
+import com.intellij.openapi.project.DumbAware;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.Splitter;
@@ -176,34 +177,8 @@
       }
     };
 
-    AnAction showFullPatchAction = new ToggleAction("Show long edges",
-                                                    "Show long branch edges even if commits are invisible in the current view.",
-                                                    VcsLogIcons.ShowHideLongEdges) {
-      @Override
-      public boolean isSelected(AnActionEvent e) {
-        return !myUI.areLongEdgesHidden();
-      }
-
-      @Override
-      public void setSelected(AnActionEvent e, boolean state) {
-        myUI.setLongEdgeVisibility(state);
-      }
-    };
-
-    ToggleAction showDetailsAction = new ToggleAction("Show Details", "Display details panel", AllIcons.Actions.Preview) {
-      @Override
-      public boolean isSelected(AnActionEvent e) {
-        return !myProject.isDisposed() && myUiProperties.isShowDetails();
-      }
-
-      @Override
-      public void setSelected(AnActionEvent e, boolean state) {
-        setupDetailsSplitter(state);
-        if (!myProject.isDisposed()) {
-          myUiProperties.setShowDetails(state);
-        }
-      }
-    };
+    AnAction showFullPatchAction = new ShowLongEdgesAction();
+    AnAction showDetailsAction = new ShowDetailsAction();
 
     refreshAction.registerShortcutOn(this);
 
@@ -224,10 +199,6 @@
     return this;
   }
 
-  public void refresh() {
-    myBranchesPanel.rebuild();
-  }
-
   public void setBranchesPanelVisible(boolean visible) {
     myBranchesPanel.setVisible(visible);
   }
@@ -284,4 +255,40 @@
       }
     }
   }
+
+  private class ShowDetailsAction extends ToggleAction implements DumbAware {
+
+    public ShowDetailsAction() {
+      super("Show Details", "Display details panel", AllIcons.Actions.Preview);
+    }
+
+    @Override
+    public boolean isSelected(AnActionEvent e) {
+      return !myProject.isDisposed() && myUiProperties.isShowDetails();
+    }
+
+    @Override
+    public void setSelected(AnActionEvent e, boolean state) {
+      setupDetailsSplitter(state);
+      if (!myProject.isDisposed()) {
+        myUiProperties.setShowDetails(state);
+      }
+    }
+  }
+
+  private class ShowLongEdgesAction extends ToggleAction implements DumbAware {
+    public ShowLongEdgesAction() {
+      super("Show long edges", "Show long branch edges even if commits are invisible in the current view.", VcsLogIcons.ShowHideLongEdges);
+    }
+
+    @Override
+    public boolean isSelected(AnActionEvent e) {
+      return !myUI.areLongEdgesHidden();
+    }
+
+    @Override
+    public void setSelected(AnActionEvent e, boolean state) {
+      myUI.setLongEdgeVisibility(state);
+    }
+  }
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogGraphTable.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogGraphTable.java
index fe9a62f..ea3ba7c 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogGraphTable.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/frame/VcsLogGraphTable.java
@@ -12,6 +12,7 @@
 import com.intellij.ui.PopupHandler;
 import com.intellij.ui.table.JBTable;
 import com.intellij.util.containers.ContainerUtil;
+import com.intellij.util.text.DateFormatUtil;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.vcs.log.Hash;
 import com.intellij.vcs.log.data.VcsLogDataHolder;
@@ -30,14 +31,12 @@
 
 import javax.swing.*;
 import javax.swing.event.*;
-import javax.swing.table.DefaultTableCellRenderer;
-import javax.swing.table.TableCellRenderer;
-import javax.swing.table.TableColumn;
-import javax.swing.table.TableModel;
+import javax.swing.table.*;
 import java.awt.*;
 import java.awt.datatransfer.StringSelection;
 import java.awt.event.MouseAdapter;
 import java.awt.event.MouseEvent;
+import java.util.Date;
 import java.util.List;
 
 import static com.intellij.vcs.log.graph.render.PrintParameters.HEIGHT_CELL;
@@ -49,11 +48,13 @@
 
   private static final Logger LOG = Logger.getInstance(VcsLogGraphTable.class);
   private static final int ROOT_INDICATOR_WIDTH = 5;
+  private static final int MAX_DEFAULT_AUTHOR_COLUMN_WIDTH = 200;
 
   @NotNull private final VcsLogUI myUI;
   @NotNull private final GraphCellPainter myGraphPainter;
 
-  private  volatile boolean myRepaintFreezed;
+  private boolean myColumnsSizeInitialized = false;
+  private volatile boolean myRepaintFreezed;
 
   public VcsLogGraphTable(@NotNull VcsLogUI UI, final VcsLogDataHolder logDataHolder) {
     super();
@@ -113,6 +114,53 @@
   }
 
   @Override
+  public void setModel(TableModel model) {
+    super.setModel(model);
+    // initialize sizes once, when the real model is set (not from the constructor).
+    if (!myColumnsSizeInitialized && !(model instanceof DefaultTableModel)) {
+      myColumnsSizeInitialized = true;
+      setColumnPreferredSize();
+      setAutoCreateColumnsFromModel(false); // otherwise sizes are recalculated after each TableColumn re-initialization
+    }
+  }
+
+  private void setColumnPreferredSize() {
+    for (int i = 0; i < getColumnCount(); i++) {
+      TableColumn column = getColumnModel().getColumn(i);
+      if (i == AbstractVcsLogTableModel.ROOT_COLUMN) { // thin stripe or nothing
+        int rootWidth = myUI.getColorManager().isMultipleRoots() ? ROOT_INDICATOR_WIDTH : 0;
+        // NB: all further instructions and their order are important, otherwise the minimum size which is less than 15 won't be applied
+        column.setMinWidth(rootWidth);
+        column.setMaxWidth(rootWidth);
+        column.setPreferredWidth(rootWidth);
+      }
+      else if (i == AbstractVcsLogTableModel.COMMIT_COLUMN) { // let commit message occupy as much as possible
+        column.setPreferredWidth(Short.MAX_VALUE);
+      }
+      else if (i == AbstractVcsLogTableModel.AUTHOR_COLUMN) { // detect author with the longest name
+        int contentWidth = calcMaxContentColumnWidth(i, 1000);
+        column.setMinWidth(Math.min(contentWidth, MAX_DEFAULT_AUTHOR_COLUMN_WIDTH));
+        column.setWidth(column.getMinWidth());
+      }
+      else if (i == AbstractVcsLogTableModel.DATE_COLUMN) { // all dates have nearly equal sizes
+        Font tableFont = UIManager.getFont("Table.font");
+        column.setMinWidth(getFontMetrics(tableFont).stringWidth("mm" + DateFormatUtil.formatDateTime(new Date())));
+        column.setWidth(column.getMinWidth());
+      }
+    }
+  }
+
+  private int calcMaxContentColumnWidth(int columnIndex, int maxRowsToCheck) {
+    int maxWidth = 0;
+    for (int row = 0; row < maxRowsToCheck && row < getRowCount(); row++) {
+      TableCellRenderer renderer = getCellRenderer(row, columnIndex);
+      Component comp = prepareRenderer(renderer, row, columnIndex);
+      maxWidth = Math.max(comp.getPreferredSize().width, maxWidth);
+    }
+    return maxWidth + UIUtil.DEFAULT_HGAP;
+  }
+
+  @Override
   public String getToolTipText(@NotNull MouseEvent event) {
     int row = rowAtPoint(event.getPoint());
     int column = columnAtPoint(event.getPoint());
@@ -128,19 +176,6 @@
     return null;
   }
 
-  public void setPreferredColumnWidths() {
-    TableColumn rootColumn = getColumnModel().getColumn(AbstractVcsLogTableModel.ROOT_COLUMN);
-    int rootWidth = myUI.getColorManager().isMultipleRoots() ? ROOT_INDICATOR_WIDTH : 0;
-    // NB: all further instructions and their order are important, otherwise the minimum size which is less than 15 won't be applied
-    rootColumn.setMinWidth(rootWidth);
-    rootColumn.setMaxWidth(rootWidth);
-    rootColumn.setPreferredWidth(rootWidth);
-
-    getColumnModel().getColumn(AbstractVcsLogTableModel.COMMIT_COLUMN).setPreferredWidth(700);
-    getColumnModel().getColumn(AbstractVcsLogTableModel.AUTHOR_COLUMN).setMinWidth(90);
-    getColumnModel().getColumn(AbstractVcsLogTableModel.DATE_COLUMN).setMinWidth(90);
-  }
-
   public void jumpToRow(int rowIndex) {
     scrollRectToVisible(getCellRect(rowIndex, 0, false));
     setRowSelectionInterval(rowIndex, rowIndex);
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/AbstractPaddingCellRender.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/AbstractPaddingCellRender.java
index 9f1cf5a..d75ca1d 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/AbstractPaddingCellRender.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/AbstractPaddingCellRender.java
@@ -1,24 +1,33 @@
 package com.intellij.vcs.log.ui.render;
 
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Condition;
 import com.intellij.openapi.vcs.changes.issueLinks.IssueLinkRenderer;
 import com.intellij.ui.ColoredTableCellRenderer;
+import com.intellij.util.containers.ContainerUtil;
+import com.intellij.vcs.log.VcsRef;
 import com.intellij.vcs.log.graph.render.GraphCommitCell;
 import com.intellij.vcs.log.printmodel.SpecialPrintElement;
+import com.intellij.vcs.log.ui.VcsLogColorManager;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import java.awt.*;
+import java.util.Collection;
+import java.util.List;
+import java.util.Map;
 
 public abstract class AbstractPaddingCellRender extends ColoredTableCellRenderer {
 
   public static final Color MARKED_BACKGROUND = new Color(200, 255, 250);
 
+  @NotNull protected final RefPainter myRefPainter;
   @NotNull private final IssueLinkRenderer myIssueLinkRenderer;
   @Nullable private Object myValue;
 
-  protected AbstractPaddingCellRender(@NotNull Project project) {
+  protected AbstractPaddingCellRender(@NotNull Project project, VcsLogColorManager colorManager) {
+    myRefPainter = new RefPainter(colorManager, false);
     myIssueLinkRenderer = new IssueLinkRenderer(project, this);
   }
 
@@ -58,4 +67,47 @@
     super.paint(g);
     additionPaint(g, myValue);
   }
+
+  protected void drawRefs(@NotNull Graphics2D g2, @NotNull Collection<VcsRef> refs, int padding) {
+    myRefPainter.drawLabels(g2, collectLabelsForRefs(refs), padding);
+  }
+
+  @NotNull
+  private static Map<String, Color> collectLabelsForRefs(@NotNull Collection<VcsRef> refs) {
+    List<VcsRef> branches = getBranches(refs);
+    Collection<VcsRef> tags = ContainerUtil.subtract(refs, branches);
+    return getLabelsForRefs(branches, tags);
+  }
+
+  protected int calcRefsPadding(@NotNull Collection<VcsRef> refs, @NotNull Graphics2D g2) {
+    return myRefPainter.padding(collectLabelsForRefs(refs).keySet(), g2);
+  }
+
+  @NotNull
+  private static Map<String, Color> getLabelsForRefs(@NotNull List<VcsRef> branches, @NotNull Collection<VcsRef> tags) {
+    Map<String, Color> labels = ContainerUtil.newLinkedHashMap();
+    for (VcsRef branch : branches) {
+      labels.put(branch.getName(), branch.getType().getBackgroundColor());
+    }
+    if (!tags.isEmpty()) {
+      VcsRef firstTag = tags.iterator().next();
+      Color color = firstTag.getType().getBackgroundColor();
+      if (tags.size() > 1) {
+        labels.put(firstTag.getName() + " +", color);
+      }
+      else {
+        labels.put(firstTag.getName(), color);
+      }
+    }
+    return labels;
+  }
+
+  private static List<VcsRef> getBranches(Collection<VcsRef> refs) {
+    return ContainerUtil.filter(refs, new Condition<VcsRef>() {
+      @Override
+      public boolean value(VcsRef ref) {
+        return ref.getType().isBranch();
+      }
+    });
+  }
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/CommitCellRender.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/CommitCellRender.java
index 7547655..702af3f 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/CommitCellRender.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/CommitCellRender.java
@@ -7,26 +7,20 @@
 
 import javax.swing.*;
 import java.awt.*;
-import java.awt.font.FontRenderContext;
 
 /**
  * @author erokhins
  */
 public class CommitCellRender extends AbstractPaddingCellRender {
 
-  @NotNull private final RefPainter refPainter;
-
   public CommitCellRender(@NotNull VcsLogColorManager colorManager, Project project) {
-    super(project);
-    refPainter = new RefPainter(colorManager, false);
+    super(project, colorManager);
   }
 
   @Override
   protected int getLeftPadding(JTable table, Object value) {
     CommitCell cell = getAssertCommitCell(value);
-
-    FontRenderContext fontContext = ((Graphics2D)table.getGraphics()).getFontRenderContext();
-    return refPainter.padding(cell.getRefsToThisCommit(), fontContext);
+    return calcRefsPadding(cell.getRefsToThisCommit(), (Graphics2D)table.getGraphics());
   }
 
   private static CommitCell getAssertCommitCell(Object value) {
@@ -48,6 +42,7 @@
   protected void additionPaint(Graphics g, Object value) {
     CommitCell cell = getAssertCommitCell(value);
     Graphics2D g2 = (Graphics2D)g;
-    refPainter.draw(g2, cell.getRefsToThisCommit(), 0, -1);
+    drawRefs(g2, cell.getRefsToThisCommit(), 0);
   }
+
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRender.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRender.java
index 130c3c4..0752ce3 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRender.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/GraphCommitCellRender.java
@@ -27,7 +27,6 @@
 
 import javax.swing.*;
 import java.awt.*;
-import java.awt.font.FontRenderContext;
 import java.awt.image.BufferedImage;
 import java.util.Collection;
 
@@ -41,14 +40,12 @@
 
   @NotNull private final GraphCellPainter graphPainter;
   @NotNull private final VcsLogDataHolder myDataHolder;
-  @NotNull private final RefPainter refPainter;
 
   public GraphCommitCellRender(@NotNull GraphCellPainter graphPainter, @NotNull VcsLogDataHolder logDataHolder,
                                @NotNull VcsLogColorManager colorManager) {
-    super(logDataHolder.getProject());
+    super(logDataHolder.getProject(), colorManager);
     this.graphPainter = graphPainter;
     myDataHolder = logDataHolder;
-    refPainter = new RefPainter(colorManager, false);
   }
 
   @Override
@@ -59,8 +56,7 @@
       return 0;
     }
 
-    FontRenderContext fontContext = ((Graphics2D)table.getGraphics()).getFontRenderContext();
-    int refPadding = refPainter.padding(cell.getRefsToThisCommit(), fontContext);
+    int refPadding = calcRefsPadding(cell.getRefsToThisCommit(), (Graphics2D)table.getGraphics());
 
     int countCells = cell.getPrintCell().countCell();
     int graphPadding = countCells * WIDTH_NODE;
@@ -99,7 +95,7 @@
       VirtualFile root = refs.iterator().next().getRoot(); // all refs are from the same commit => they have the same root
       refs = myDataHolder.getLogProvider(root).getReferenceManager().sort(refs);
     }
-    refPainter.draw(g2, refs, padding, -1); // TODO think how to behave if there are too many refs here (even if tags are collapsed)
+    drawRefs(g2, refs, padding);
 
     UIUtil.drawImage(g, image, 0, 0, null);
   }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/RefPainter.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/RefPainter.java
index ae52d3f..004a9ed 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/RefPainter.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/render/RefPainter.java
@@ -4,6 +4,7 @@
 import com.intellij.vcs.log.VcsRef;
 import com.intellij.vcs.log.ui.VcsLogColorManager;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.awt.*;
 import java.awt.font.FontRenderContext;
@@ -21,6 +22,7 @@
   private static final int RECTANGLE_X_PADDING = 4;
   private static final int RECTANGLE_Y_PADDING = 3;
   private static final int REF_PADDING = 13;
+  private static final int LABEL_PADDING = 3;
 
   private static final int FLAG_WIDTH = 8;
   private static final int FLAG_PADDING = 8;
@@ -40,7 +42,11 @@
   }
 
   private double paddingStr(@NotNull String str, @NotNull FontRenderContext renderContext) {
-    return DEFAULT_FONT.getStringBounds(str, renderContext).getWidth() + REF_PADDING + flagWidth();
+    return getStringWidth(str, renderContext) + REF_PADDING + flagWidth();
+  }
+
+  private static double getStringWidth(@NotNull String str, @NotNull FontRenderContext renderContext) {
+    return DEFAULT_FONT.getStringBounds(str, renderContext).getWidth();
   }
 
   private int flagWidth() {
@@ -79,12 +85,16 @@
     g2.drawPolygon(polygon);
   }
 
-  public int padding(@NotNull Collection<VcsRef> refs, @NotNull FontRenderContext renderContext) {
-    float p = 0;
-    for (VcsRef ref : refs) {
-      p += paddingStr(ref.getName(), renderContext);
+  public int padding(@NotNull Collection<String> refs, @NotNull Graphics2D g2) {
+    int p = 0;
+    for (String ref : refs) {
+      XAndWidth xAndWidth = getXAndWidth(ref, 0, g2.getFontMetrics(DEFAULT_FONT));
+      p += xAndWidth.x + xAndWidth.width + LABEL_PADDING;
     }
-    return Math.round(p);
+    if (p > 0) { // additional padding after all references looks better
+      p += LABEL_PADDING;
+    }
+    return p;
   }
 
   public Map<Integer, VcsRef> draw(@NotNull Graphics2D g2, @NotNull Collection<VcsRef> refs, int startPadding, int maxWidth) {
@@ -109,12 +119,28 @@
     g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
   }
 
-  public Rectangle drawLabel(@NotNull Graphics2D g2, @NotNull String label, int paddingX, @NotNull Color bgColor, Color rootIndicatorColor) {
+  public void drawLabels(@NotNull Graphics2D g2, @NotNull Map<String, Color> labels, int startPadding) {
+    int padding = startPadding;
+    for (Map.Entry<String, Color> entry : labels.entrySet()) {
+      Rectangle rectangle = drawLabel(g2, entry.getKey(), padding, entry.getValue(), null);
+      padding += rectangle.width + LABEL_PADDING;
+    }
+  }
+
+  private XAndWidth getXAndWidth(String label, int paddingX, FontMetrics metrics) {
+    int x = paddingX + REF_PADDING / 2 - RECTANGLE_X_PADDING;
+    int width = metrics.stringWidth(label) + 2 * RECTANGLE_X_PADDING + flagWidth();
+    return new XAndWidth(x, width);
+  }
+
+  public Rectangle drawLabel(@NotNull Graphics2D g2, @NotNull String label, int paddingX, @NotNull Color bgColor,
+                             @Nullable Color rootIndicatorColor) {
     setupGraphics(g2);
     FontMetrics metrics = g2.getFontMetrics();
-    int x = paddingX + REF_PADDING / 2 - RECTANGLE_X_PADDING;
+    XAndWidth xAndWidth = getXAndWidth(label, paddingX, metrics);
+    int x = xAndWidth.x;
+    int width = xAndWidth.width;
     int y = RECTANGLE_Y_PADDING;
-    int width = metrics.stringWidth(label) + 2 * RECTANGLE_X_PADDING + flagWidth();
     int height = HEIGHT_CELL - 2 * RECTANGLE_Y_PADDING;
     RoundRectangle2D rectangle2D = new RoundRectangle2D.Double(x, y, width, height, ROUND_RADIUS, ROUND_RADIUS);
 
@@ -127,11 +153,21 @@
     g2.setColor(JBColor.BLACK);
     drawText(g2, label, paddingX + flagWidth());
 
-    if (myColorManager.isMultipleRoots() && myDrawMultiRepoIndicator) {
+    if (rootIndicatorColor != null && myColorManager.isMultipleRoots() && myDrawMultiRepoIndicator) {
       drawRootIndicator(g2, paddingX, y, height, rootIndicatorColor);
     }
 
     return new Rectangle(x, y, width, height);
   }
 
+  private static class XAndWidth {
+    private final int x;
+    private final int width;
+
+    private XAndWidth(int x, int width) {
+      this.x = x;
+      this.width = width;
+    }
+  }
+
 }
diff --git a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/tables/AbstractVcsLogTableModel.java b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/tables/AbstractVcsLogTableModel.java
index 6ab7844..1e26910 100644
--- a/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/tables/AbstractVcsLogTableModel.java
+++ b/platform/vcs-log/impl/src/com/intellij/vcs/log/ui/tables/AbstractVcsLogTableModel.java
@@ -26,7 +26,7 @@
   public static final int DATE_COLUMN = 3;
   private static final int COLUMN_COUNT = DATE_COLUMN + 1;
 
-  private static final String[] COLUMN_NAMES = {"Root", "Subject", "Author", "Date"};
+  private static final String[] COLUMN_NAMES = {"", "Subject", "Author", "Date"};
 
   @Override
   public final int getColumnCount() {
diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebugSessionImpl.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebugSessionImpl.java
index 70f9cac..eedd2e3e 100644
--- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebugSessionImpl.java
+++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/XDebugSessionImpl.java
@@ -66,6 +66,7 @@
 import com.intellij.xdebugger.impl.ui.XDebuggerUIConstants;
 import com.intellij.xdebugger.stepping.XSmartStepIntoHandler;
 import com.intellij.xdebugger.stepping.XSmartStepIntoVariant;
+import gnu.trove.THashSet;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -295,7 +296,11 @@
 
   private void disableSlaveBreakpoints(final XDependentBreakpointManager dependentBreakpointManager) {
     Set<XBreakpoint<?>> slaveBreakpoints = dependentBreakpointManager.getAllSlaveBreakpoints();
-    Set<XBreakpointType<?, ?>> breakpointTypes = new HashSet<XBreakpointType<?, ?>>();
+    if (slaveBreakpoints.isEmpty()) {
+      return;
+    }
+
+    Set<XBreakpointType<?, ?>> breakpointTypes = new THashSet<XBreakpointType<?, ?>>();
     for (XBreakpointHandler<?> handler : myDebugProcess.getBreakpointHandlers()) {
       breakpointTypes.add(getBreakpointTypeClass(handler));
     }
diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java
index 0502704..80c9504 100644
--- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java
+++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/DebuggerUIUtil.java
@@ -17,12 +17,8 @@
 
 import com.intellij.codeInsight.hint.HintUtil;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.Editor;
-import com.intellij.openapi.editor.EditorFactory;
 import com.intellij.openapi.editor.LogicalPosition;
-import com.intellij.openapi.editor.impl.DocumentImpl;
-import com.intellij.openapi.fileTypes.FileTypes;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.popup.Balloon;
 import com.intellij.openapi.ui.popup.JBPopupFactory;
@@ -35,7 +31,6 @@
 import com.intellij.openapi.wm.WindowManager;
 import com.intellij.ui.AppUIUtil;
 import com.intellij.ui.EditorTextField;
-import com.intellij.ui.ScrollPaneFactory;
 import com.intellij.ui.awt.RelativePoint;
 import com.intellij.xdebugger.XDebuggerManager;
 import com.intellij.xdebugger.breakpoints.XBreakpoint;
@@ -105,28 +100,21 @@
   }
 
   public static void showValuePopup(@NotNull XFullValueEvaluator text, @NotNull MouseEvent event, @NotNull Project project) {
-    Document document = EditorFactory.getInstance().createDocument("Evaluating...");
-    if (document instanceof DocumentImpl) {
-      ((DocumentImpl)document).setAcceptSlashR(true);
-    }
-
-    EditorTextField textArea = new EditorTextField(document, project, FileTypes.PLAIN_TEXT, true);
+    EditorTextField textArea = new TextViewer("Evaluating...", project);
     textArea.setBackground(HintUtil.INFORMATION_COLOR);
 
     final FullValueEvaluationCallbackImpl callback = new FullValueEvaluationCallbackImpl(textArea);
     text.startEvaluation(callback);
 
-    final JScrollPane component = ScrollPaneFactory.createScrollPane(textArea);
-    final Dimension frameSize = WindowManager.getInstance().getFrame(project).getSize();
     Dimension size = DimensionService.getInstance().getSize(FULL_VALUE_POPUP_DIMENSION_KEY, project);
     if (size == null) {
+      Dimension frameSize = WindowManager.getInstance().getFrame(project).getSize();
       size = new Dimension(frameSize.width / 2, frameSize.height / 2);
     }
 
-    component.setPreferredSize(size);
-    component.setBorder(null);
+    textArea.setPreferredSize(size);
 
-    JBPopupFactory.getInstance().createComponentPopupBuilder(component, null)
+    JBPopupFactory.getInstance().createComponentPopupBuilder(textArea, null)
       .setResizable(true)
       .setMovable(true)
       .setDimensionServiceKey(project, FULL_VALUE_POPUP_DIMENSION_KEY, false)
diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/ExecutionPointHighlighter.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/ExecutionPointHighlighter.java
index 57f9240..d34ebcd 100644
--- a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/ExecutionPointHighlighter.java
+++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/ExecutionPointHighlighter.java
@@ -22,7 +22,6 @@
 import com.intellij.openapi.editor.colors.EditorColorsScheme;
 import com.intellij.openapi.editor.markup.GutterIconRenderer;
 import com.intellij.openapi.editor.markup.RangeHighlighter;
-import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.fileEditor.FileEditorManager;
 import com.intellij.openapi.fileEditor.OpenFileDescriptor;
 import com.intellij.openapi.project.Project;
@@ -30,6 +29,7 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.ui.AppUIUtil;
 import com.intellij.xdebugger.XSourcePosition;
+import com.intellij.xdebugger.impl.XSourcePositionImpl;
 import com.intellij.xdebugger.ui.DebuggerColors;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -54,6 +54,7 @@
   public void show(final @NotNull XSourcePosition position, final boolean useSelection,
                    @Nullable final GutterIconRenderer gutterIconRenderer) {
     AppUIUtil.invokeLaterIfProjectAlive(myProject, new Runnable() {
+      @Override
       public void run() {
         doShow(position, useSelection, gutterIconRenderer);
       }
@@ -62,6 +63,7 @@
 
   public void hide() {
     AppUIUtil.invokeOnEdt(new Runnable() {
+      @Override
       public void run() {
         doHide();
       }
@@ -99,7 +101,8 @@
     removeHighlighter();
 
     mySourcePosition = position;
-    myEditor = openEditor();
+    myOpenFileDescriptor = XSourcePositionImpl.createOpenFileDescriptor(myProject, mySourcePosition);
+    myEditor = FileEditorManager.getInstance(myProject).openTextEditor(myOpenFileDescriptor, false);
     myUseSelection = useSelection;
     myGutterIconRenderer = renderer;
     if (myEditor != null) {
@@ -107,20 +110,6 @@
     }
   }
 
-  @Nullable
-  private Editor openEditor() {
-    VirtualFile file = mySourcePosition.getFile();
-    Document document = FileDocumentManager.getInstance().getDocument(file);
-    int offset = mySourcePosition.getOffset();
-    if (offset < 0 || offset >= document.getTextLength()) {
-      myOpenFileDescriptor = new OpenFileDescriptor(myProject, file, mySourcePosition.getLine(), 0);
-    }
-    else {
-      myOpenFileDescriptor = new OpenFileDescriptor(myProject, file, offset);
-    }
-    return FileEditorManager.getInstance(myProject).openTextEditor(myOpenFileDescriptor, false);
-  }
-
   private void doHide() {
     ApplicationManager.getApplication().assertIsDispatchThread();
     removeHighlighter();
diff --git a/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/TextViewer.java b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/TextViewer.java
new file mode 100644
index 0000000..bd43d87
--- /dev/null
+++ b/platform/xdebugger-impl/src/com/intellij/xdebugger/impl/ui/TextViewer.java
@@ -0,0 +1,49 @@
+package com.intellij.xdebugger.impl.ui;
+
+import com.intellij.openapi.editor.Document;
+import com.intellij.openapi.editor.EditorFactory;
+import com.intellij.openapi.editor.ex.EditorEx;
+import com.intellij.openapi.editor.impl.DocumentImpl;
+import com.intellij.openapi.fileTypes.FileTypes;
+import com.intellij.openapi.project.Project;
+import com.intellij.ui.EditorTextField;
+import org.jetbrains.annotations.NotNull;
+
+public final class TextViewer extends EditorTextField {
+  private final boolean myEmbeddedIntoDialogWrapper;
+  private final boolean myUseSoftWraps;
+
+  public TextViewer(@NotNull Project project, boolean embeddedIntoDialogWrapper, boolean useSoftWraps) {
+    this(createDocument(""), project, embeddedIntoDialogWrapper, useSoftWraps);
+  }
+
+  public TextViewer(@NotNull String initialText, @NotNull Project project) {
+    this(createDocument(initialText), project, false, false);
+  }
+
+  public TextViewer(@NotNull Document document, @NotNull Project project, boolean embeddedIntoDialogWrapper, boolean useSoftWraps) {
+    super(document, project, FileTypes.PLAIN_TEXT, true, false);
+
+    myEmbeddedIntoDialogWrapper = embeddedIntoDialogWrapper;
+    myUseSoftWraps = useSoftWraps;
+  }
+
+  private static Document createDocument(@NotNull String initialText) {
+    final Document document = EditorFactory.getInstance().createDocument(initialText);
+    if (document instanceof DocumentImpl) {
+      ((DocumentImpl)document).setAcceptSlashR(true);
+    }
+    return document;
+  }
+
+  @Override
+  protected EditorEx createEditor() {
+    final EditorEx editor = super.createEditor();
+    editor.setHorizontalScrollbarVisible(true);
+    editor.setVerticalScrollbarVisible(true);
+    editor.setEmbeddedIntoDialogWrapper(myEmbeddedIntoDialogWrapper);
+    editor.getComponent().setPreferredSize(null);
+    editor.getSettings().setUseSoftWraps(myUseSoftWraps);
+    return editor;
+  }
+}
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/DeclareCollectionAsInterfaceInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/DeclareCollectionAsInterfaceInspection.java
index 2180e66d..a9f6d14 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/DeclareCollectionAsInterfaceInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/abstraction/DeclareCollectionAsInterfaceInspection.java
@@ -23,6 +23,7 @@
 import com.intellij.psi.codeStyle.JavaCodeStyleManager;
 import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.psi.search.PsiSearchHelper;
+import com.intellij.psi.search.SearchScope;
 import com.intellij.util.IncorrectOperationException;
 import com.siyeh.InspectionGadgetsBundle;
 import com.siyeh.ig.BaseInspection;
@@ -304,11 +305,11 @@
       final ProgressManager progressManager =
         ProgressManager.getInstance();
       final PsiSearchHelper searchHelper = PsiSearchHelper.SERVICE.getInstance(element.getProject());
-      final GlobalSearchScope scope =
-        GlobalSearchScope.projectScope(element.getProject());
-      return searchHelper.isCheapEnoughToSearch(name, scope, null,
-                                                progressManager.getProgressIndicator()) !=
-             PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES;
+      SearchScope useScope = element.getUseScope();
+      if (useScope instanceof GlobalSearchScope) {
+        return searchHelper.isCheapEnoughToSearch(name, (GlobalSearchScope)useScope, null, progressManager.getProgressIndicator()) != PsiSearchHelper.SearchCostResult.TOO_MANY_OCCURRENCES;
+      }
+      return true;
     }
   }
 }
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/ChangeModifierFix.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/ChangeModifierFix.java
index 2be78a4..8e3bf79 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/ChangeModifierFix.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/fixes/ChangeModifierFix.java
@@ -31,9 +31,16 @@
 public class ChangeModifierFix extends InspectionGadgetsFix {
 
   @PsiModifier.ModifierConstant private final String modifierText;
+  private final String[] incompatibleModifiers;
 
   public ChangeModifierFix(@NonNls @PsiModifier.ModifierConstant String modifierText) {
     this.modifierText = modifierText;
+    this.incompatibleModifiers = null;
+  }
+
+  public ChangeModifierFix(String modifierText, String... incompatibleModifiers) {
+    this.modifierText = modifierText;
+    this.incompatibleModifiers = incompatibleModifiers;
   }
 
   @Override
@@ -63,5 +70,10 @@
       return;
     }
     modifiers.setModifierProperty(modifierText, true);
+    if (incompatibleModifiers != null) {
+      for (String modifier : incompatibleModifiers) {
+        modifiers.setModifierProperty(modifier, false);
+      }
+    }
   }
 }
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/UnnecessaryExplicitNumericCastInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/UnnecessaryExplicitNumericCastInspection.java
index f7eeccf..86a1eb2 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/UnnecessaryExplicitNumericCastInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/numeric/UnnecessaryExplicitNumericCastInspection.java
@@ -232,10 +232,12 @@
       final Project project = expression.getProject();
       final JavaPsiFacade javaPsiFacade = JavaPsiFacade.getInstance(project);
       final PsiElementFactory factory = javaPsiFacade.getElementFactory();
-      final PsiCallExpression newMethodCall = (PsiCallExpression)
-        factory.createExpressionFromText(newMethodCallText.toString(), expression);
-      if (targetMethod != newMethodCall.resolveMethod()) {
-        return true;
+      final PsiExpression expressionFromText = factory.createExpressionFromText(newMethodCallText.toString(), expression);
+      if (expressionFromText instanceof PsiCallExpression) {
+        final PsiCallExpression newMethodCall = (PsiCallExpression)expressionFromText;
+        if (targetMethod != newMethodCall.resolveMethod()) {
+          return true;
+        }
       }
     }
     final PsiType expectedType = ExpectedTypeUtils.findExpectedType(expression, false);
diff --git a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/MethodMayBeStaticInspection.java b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/MethodMayBeStaticInspection.java
index 51c7c51..ab8934e 100644
--- a/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/MethodMayBeStaticInspection.java
+++ b/plugins/InspectionGadgets/InspectionGadgetsAnalysis/src/com/siyeh/ig/performance/MethodMayBeStaticInspection.java
@@ -18,6 +18,7 @@
 import com.intellij.codeInspection.InspectionManager;
 import com.intellij.codeInspection.ui.MultipleCheckboxOptionsPanel;
 import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.util.WriteExternalException;
 import com.intellij.psi.*;
 import com.intellij.psi.search.searches.ClassInheritorsSearch;
 import com.intellij.util.Processor;
@@ -30,6 +31,7 @@
 import com.siyeh.ig.psiutils.ClassUtils;
 import com.siyeh.ig.psiutils.MethodUtils;
 import com.siyeh.ig.psiutils.SerializationUtils;
+import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
@@ -37,6 +39,9 @@
 
 public class MethodMayBeStaticInspection extends BaseInspection {
 
+  private static final String IGNORE_DEFAULT_METHODS_ATTR_NAME = "m_ignoreDefaultMethods";
+  private static final String ONLY_PRIVATE_OR_FINAL_ATTR_NAME = "m_onlyPrivateOrFinal";
+  private static final String IGNORE_EMPTY_METHODS_ATTR_NAME = "m_ignoreEmptyMethods";
   /**
    * @noinspection PublicField
    */
@@ -45,6 +50,7 @@
    * @noinspection PublicField
    */
   public boolean m_ignoreEmptyMethods = true;
+  public boolean m_ignoreDefaultMethods = true;
 
   @Override
   @NotNull
@@ -60,14 +66,15 @@
 
   @Override
   protected InspectionGadgetsFix buildFix(Object... infos) {
-    return new ChangeModifierFix(PsiModifier.STATIC);
+    return new ChangeModifierFix(PsiModifier.STATIC, PsiModifier.DEFAULT);
   }
 
   @Override
   public JComponent createOptionsPanel() {
     final MultipleCheckboxOptionsPanel optionsPanel = new MultipleCheckboxOptionsPanel(this);
-    optionsPanel.addCheckbox(InspectionGadgetsBundle.message("method.may.be.static.only.option"), "m_onlyPrivateOrFinal");
-    optionsPanel.addCheckbox(InspectionGadgetsBundle.message("method.may.be.static.empty.option"), "m_ignoreEmptyMethods");
+    optionsPanel.addCheckbox(InspectionGadgetsBundle.message("method.may.be.static.only.option"), ONLY_PRIVATE_OR_FINAL_ATTR_NAME);
+    optionsPanel.addCheckbox(InspectionGadgetsBundle.message("method.may.be.static.empty.option"), IGNORE_EMPTY_METHODS_ATTR_NAME);
+    optionsPanel.addCheckbox("Ignore default methods", IGNORE_DEFAULT_METHODS_ATTR_NAME);
     return optionsPanel;
   }
 
@@ -76,6 +83,16 @@
     return new MethodCanBeStaticVisitor();
   }
 
+  @Override
+  public void writeSettings(@NotNull Element node) throws WriteExternalException {
+    node.addContent(new Element("option").setAttribute("name", ONLY_PRIVATE_OR_FINAL_ATTR_NAME).setAttribute("value", String.valueOf(m_onlyPrivateOrFinal)));
+    node.addContent(new Element("option").setAttribute("name", IGNORE_EMPTY_METHODS_ATTR_NAME).setAttribute("value", String.valueOf(
+      m_ignoreEmptyMethods)));
+    if (!m_ignoreDefaultMethods) {
+      node.addContent(new Element("option").setAttribute("name", IGNORE_DEFAULT_METHODS_ATTR_NAME).setAttribute("value", "false"));
+    }
+  }
+
   private class MethodCanBeStaticVisitor extends BaseInspectionVisitor {
 
     @Override
@@ -90,6 +107,9 @@
       if (method.isConstructor() || method.getNameIdentifier() == null) {
         return;
       }
+      if (m_ignoreDefaultMethods && method.hasModifierProperty(PsiModifier.DEFAULT)) {
+        return;
+      }
       if (m_ignoreEmptyMethods && MethodUtils.isEmpty(method)) {
         return;
       }
@@ -104,7 +124,7 @@
         }
       }
       final PsiElement scope = containingClass.getScope();
-      if (!(scope instanceof PsiJavaFile) && !containingClass.hasModifierProperty(PsiModifier.STATIC)) {
+      if (!(scope instanceof PsiJavaFile) && !containingClass.hasModifierProperty(PsiModifier.STATIC) && !containingClass.isInterface()) {
         return;
       }
       if (m_onlyPrivateOrFinal && !method.hasModifierProperty(PsiModifier.FINAL) && !method.hasModifierProperty(PsiModifier.PRIVATE)) {
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/A.java b/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/A.java
index 94bb4a3..d0417da 100644
--- a/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/A.java
+++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/A.java
@@ -36,4 +36,10 @@
 }
 interface Surprise {
   int getInt();
+}
+
+interface FromJava8 {
+  default void foo() {
+    System.out.println();
+  }
 }
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/expected.xml b/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/expected.xml
index bb2af8f..63fe5d9 100644
--- a/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/expected.xml
+++ b/plugins/InspectionGadgets/test/com/siyeh/igtest/performance/method_may_be_static/expected.xml
@@ -6,5 +6,11 @@
     <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Method may be 'static'</problem_class>
     <description>Method &lt;code&gt;g()&lt;/code&gt; may be 'static' #loc</description>
   </problem>
+  <problem>
+    <file>A.java</file>
+    <line>42</line>
+    <problem_class severity="WARNING" attribute_key="WARNING_ATTRIBUTES">Method may be 'static'</problem_class>
+    <description>Method &lt;code&gt;foo()&lt;/code&gt; may be 'static' #loc</description>
+  </problem>
 
 </problems>
\ No newline at end of file
diff --git a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/performance/MethodMayBeStaticInspectionTest.java b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/performance/MethodMayBeStaticInspectionTest.java
index 7cc0738..84cfdd7 100644
--- a/plugins/InspectionGadgets/testsrc/com/siyeh/ig/performance/MethodMayBeStaticInspectionTest.java
+++ b/plugins/InspectionGadgets/testsrc/com/siyeh/ig/performance/MethodMayBeStaticInspectionTest.java
@@ -7,6 +7,7 @@
   public void test() throws Exception {
     final MethodMayBeStaticInspection tool = new MethodMayBeStaticInspection();
     tool.m_ignoreEmptyMethods = false;
+    tool.m_ignoreDefaultMethods = false;
     doTest("com/siyeh/igtest/performance/method_may_be_static", tool);
   }
 }
\ No newline at end of file
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 bf13c7f..76baab1 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
@@ -52,6 +52,7 @@
 import com.intellij.ui.content.*;
 import com.intellij.util.Alarm;
 import com.intellij.util.text.DateFormatUtil;
+import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -102,8 +103,6 @@
   private final java.util.List<LogCommand> myLog = Collections.synchronizedList(new ArrayList<LogCommand>(1024));
   private volatile int myCommandsProcessedCount = 0;
 
-  private JPanel myProgressPanel;
-
   private final AntMessageCustomizer[] myMessageCustomizers = AntMessageCustomizer.EP_NAME.getExtensions();
 
   private final Alarm myAlarm = new Alarm(Alarm.ThreadToUse.SWING_THREAD);
@@ -119,7 +118,7 @@
     }
   };
 
-  private boolean myIsAborted;
+  private volatile boolean myIsAborted;
   private ActionToolbar myLeftToolbar;
   private ActionToolbar myRightToolbar;
   private final TreeExpander myTreeExpander = new TreeExpander() {
@@ -166,19 +165,6 @@
     showAntView(AntBuildFileImpl.TREE_VIEW.value(buildFile.getAllOptions()));
   }
 
-  public boolean hasMessagesOfType(MessageType type) {
-    synchronized (myLog) {
-      for (LogCommand cmd : myLog) {
-        if (cmd instanceof MessageCommand) {
-          if (((MessageCommand)cmd).getMessage().getType() == type) {
-            return true;
-          }
-        }
-      }
-    }
-    return false;
-  }
-
   public void changeView() {
     showAntView(!isTreeView());
     if (myBuildFile != null) {
@@ -316,19 +302,6 @@
     return messageView;
   }
 
-  public void removeProgressPanel() {
-    if (myProgressPanel != null) {
-      myMessagePanel.remove(myProgressPanel);
-      // fix of 9377
-      SwingUtilities.invokeLater(new Runnable() {
-        public void run() {
-          myMessagePanel.validate();
-        }
-      });
-      myProgressPanel = null;
-    }
-  }
-
   public void setParsingThread(OutputParser parsingThread) {
     myParsingThread = parsingThread;
     myIsAborted = false;
@@ -446,7 +419,7 @@
   }
 
   public void outputError(String error, int priority) {
-    //updateErrorAndWarningCounters(priority);
+    updateErrorAndWarningCounters(priority);
     final AntMessage message = createErrorMessage(priority, error);
     addCommand(new AddMessageCommand(message));
     WolfTheProblemSolver wolf = WolfTheProblemSolver.getInstance(myProject);
@@ -455,7 +428,7 @@
 
   public void outputException(String exception) {
     updateErrorAndWarningCounters(PRIORITY_ERR);
-    AntMessage message = createErrorMessage(0, exception);
+    AntMessage message = createErrorMessage(PRIORITY_ERR, exception);
     addCommand(new AddExceptionCommand(message));
     WolfTheProblemSolver wolf = WolfTheProblemSolver.getInstance(myProject);
     wolf.queue(message.getFile());
@@ -797,19 +770,63 @@
     return myWarningCount;
   }
 
-  void buildFinished(boolean isProgressAborted, long buildTimeInMilliseconds, @NotNull final AntBuildListener antBuildListener, OutputPacketProcessor dispatcher) {
+  void buildFinished(boolean isProgressAborted, final long buildTimeInMilliseconds, @NotNull final AntBuildListener antBuildListener, OutputPacketProcessor dispatcher) {
     final boolean aborted = isProgressAborted || myIsAborted;
-    final String message = getFinishStatusText(aborted, buildTimeInMilliseconds);
 
     dispatcher.processOutput(new Printable() {
       @Override
       public void printOn(Printer printer) {
         if (!myProject.isDisposed()) { // if not disposed
+          final String message = getFinishStatusText(aborted, buildTimeInMilliseconds);
           addCommand(new FinishBuildCommand(message));
           final StatusBar statusBar = WindowManager.getInstance().getStatusBar(myProject);
           if (statusBar != null) {
             statusBar.setInfo(message);
           }
+          final AntBuildFileBase buildFile = myBuildFile;
+          final boolean isBackground = buildFile != null && buildFile.isRunInBackground();
+          final boolean shouldActivate = !isBackground || getErrorCount() > 0;
+          UIUtil.invokeLaterIfNeeded(new Runnable() {
+            public void run() {
+              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();
+                    }
+                    else {
+                      myTreeView.scrollToStatus();
+                    }
+                  }
+                  else {
+                    myTreeView.scrollToLastMessage();
+                  }
+                  VirtualFileManager.getInstance().asyncRefresh(new Runnable() {
+                    public void run() {
+                      antBuildListener.buildFinished(aborted ? AntBuildListener.ABORTED : AntBuildListener.FINISHED_SUCCESSFULLY, errorCount);
+                    }
+                  });
+                }
+              };
+              if (shouldActivate) {
+                final ToolWindow toolWindow = !myProject.isDisposed() ? ToolWindowManager.getInstance(myProject).getToolWindow(ToolWindowId.MESSAGES_WINDOW) : null;
+                if (toolWindow != null) { // can be null if project is closed
+                  toolWindow.activate(finishRunnable, false);
+                }
+                else {
+                  finishRunnable.run();
+                }
+              }
+              else {
+                finishRunnable.run();
+              }
+            }
+          });
         }
       }
     });
@@ -819,50 +836,25 @@
         if (!myIsOutputPaused) {
           new OutputFlusher().doFlush();
         }
-        final AntBuildFileBase buildFile = myBuildFile;
-        if (buildFile != null) {
-          if (getErrorCount() == 0 && buildFile.isViewClosedWhenNoErrors()) {
-            close();
-          }
-          else if (getErrorCount() > 0) {
-            myTreeView.scrollToFirstError();
-          }
-          else {
-            myTreeView.scrollToStatus();
-          }
-        }
-        else {
-          myTreeView.scrollToLastMessage();
-        }
-        VirtualFileManager.getInstance().asyncRefresh(new Runnable() {
-          public void run() {
-            antBuildListener.buildFinished(aborted ? AntBuildListener.ABORTED : AntBuildListener.FINISHED_SUCCESSFULLY, getErrorCount());
-          }
-        });
       }
     });
   }
 
-  public String getFinishStatusText(boolean isAborted, long buildTimeInMilliseconds) {
-    int errors = getErrorCount();
-    int warnings = getWarningCount();
+  private String getFinishStatusText(boolean isAborted, long buildTimeInMilliseconds) {
     final String theDateAsString = DateFormatUtil.formatDateTime(Clock.getTime());
-
-    String formattedBuildTime = formatBuildTime(buildTimeInMilliseconds / 1000);
-
+    final String formattedBuildTime = formatBuildTime(buildTimeInMilliseconds / 1000);
     if (isAborted) {
       return AntBundle.message("build.finished.status.ant.build.aborted", formattedBuildTime, theDateAsString);
     }
-    else if (errors == 0 && warnings == 0) {
+    final int errors = getErrorCount();
+    final int warnings = getWarningCount();
+    if (errors == 0 && warnings == 0) {
       return AntBundle.message("build.finished.status.ant.build.completed.successfully", formattedBuildTime, theDateAsString);
     }
-    else if (errors == 0) {
+    if (errors == 0) {
       return AntBundle.message("build.finished.status.ant.build.completed.with.warnings", warnings, formattedBuildTime, theDateAsString);
     }
-    else {
-      return AntBundle
-        .message("build.finished.status.ant.build.completed.with.errors.warnings", errors, warnings, formattedBuildTime, theDateAsString);
-    }
+    return AntBundle.message("build.finished.status.ant.build.completed.with.errors.warnings", errors, warnings, formattedBuildTime, theDateAsString);
   }
 
   private static String formatBuildTime(long seconds) {
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 87972fd..f0e8950 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
@@ -25,6 +25,9 @@
 import com.intellij.execution.process.OSProcessHandler;
 import com.intellij.execution.process.ProcessAdapter;
 import com.intellij.execution.process.ProcessEvent;
+import com.intellij.execution.process.ProcessOutputTypes;
+import com.intellij.execution.testframework.Printable;
+import com.intellij.execution.testframework.Printer;
 import com.intellij.execution.util.ExecutionErrorDialog;
 import com.intellij.history.LocalHistory;
 import com.intellij.ide.macro.Macro;
@@ -34,16 +37,17 @@
 import com.intellij.lang.ant.config.impl.BuildFileProperty;
 import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.application.ApplicationManager;
-import com.intellij.openapi.application.ModalityState;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.progress.ProcessCanceledException;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Key;
 import com.intellij.openapi.vfs.VfsUtil;
 import com.intellij.openapi.vfs.encoding.EncodingProjectManager;
-import com.intellij.openapi.wm.*;
+import com.intellij.openapi.wm.StatusBar;
+import com.intellij.openapi.wm.WindowManager;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -106,12 +110,10 @@
       }
     }
 
-    final boolean startInBackground = buildFile.isRunInBackground();
-    
     new Task.Backgroundable(buildFile.getProject(), AntBundle.message("ant.build.progress.dialog.title"), true) {
 
       public boolean shouldStartInBackground() {
-        return startInBackground;
+        return true;
       }
 
       public void run(@NotNull final ProgressIndicator indicator) {
@@ -170,30 +172,47 @@
 
     final OutputParser parser = OutputParser2.attachParser(project, handler, errorView, progress, buildFile);
 
-    final boolean isBackground = buildFile.isRunInBackground();
-
     handler.addProcessListener(new ProcessAdapter() {
+      private final StringBuilder myUnprocessedStdErr = new StringBuilder();
+
+      public void onTextAvailable(ProcessEvent event, Key outputType) {
+        if (outputType == ProcessOutputTypes.STDERR) {
+          final String text = event.getText();
+          synchronized (myUnprocessedStdErr) {
+            myUnprocessedStdErr.append(text);
+          }
+        }
+      }
+
       public void processTerminated(ProcessEvent event) {
         final long buildTime = System.currentTimeMillis() - startTime;
         checkCancelTask.cancel();
         parser.setStopped(true);
+
         final OutputPacketProcessor dispatcher = handler.getErr().getEventsDispatcher();
-        errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener, dispatcher);
-        ApplicationManager.getApplication().invokeLater(new Runnable() {
-          public void run() {
-            if (project.isDisposed()) {
-              return;
-            }
-            errorView.removeProgressPanel();
-            final boolean shouldActivate = !isBackground || errorView.hasMessagesOfType(AntBuildMessageView.MessageType.ERROR);
-            if (shouldActivate) {
-              ToolWindow toolWindow = ToolWindowManager.getInstance(project).getToolWindow(ToolWindowId.MESSAGES_WINDOW);
-              if (toolWindow != null) { // can be null if project is closed
-                toolWindow.activate(null, false);
-              }
-            }
+
+        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);
           }
-        }, ModalityState.NON_MODAL);
+          if (!unprocessed.isEmpty()) {
+            dispatcher.processOutput(new Printable() {
+              public void printOn(Printer printer) {
+                errorView.outputError(unprocessed, AntBuildMessageView.PRIORITY_ERR);
+              }
+            });
+          }
+        }
+        else {
+          synchronized (myUnprocessedStdErr) {
+            myUnprocessedStdErr.setLength(0);
+          }
+        }
+
+        errorView.buildFinished(progress != null && progress.isCanceled(), buildTime, antBuildListener, dispatcher);
       }
     });
     handler.startNotify();
diff --git a/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java b/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java
index e5ee280..09d19f9 100644
--- a/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java
+++ b/plugins/copyright/src/com/maddyhome/idea/copyright/CopyrightManager.java
@@ -92,10 +92,10 @@
               final Document document = e.getDocument();
               final VirtualFile virtualFile = fileDocumentManager.getFile(document);
               if (virtualFile == null) return;
-              if (!newFileTracker.poll(virtualFile)) return;
-              if (!fileTypeUtil.isSupportedFile(virtualFile)) return;
               final Module module = projectRootManager.getFileIndex().getModuleForFile(virtualFile);
               if (module == null) return;
+              if (!newFileTracker.poll(virtualFile)) return;
+              if (!fileTypeUtil.isSupportedFile(virtualFile)) return;
               final PsiFile file = psiManager.findFile(virtualFile);
               if (file == null) return;
               application.invokeLater(new Runnable() {
diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/CvsUtil.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/CvsUtil.java
index cf8dccc..712f53a 100644
--- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/CvsUtil.java
+++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/CvsUtil.java
@@ -29,6 +29,7 @@
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vcs.FilePath;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -101,6 +102,22 @@
     }
   }
 
+  public static boolean fileIsUnderCvsMaybeWithVfs(VirtualFile vFile) {
+    try {
+      if (Registry.is("cvs.roots.refresh.uses.vfs")) {
+        if (vFile.isDirectory()) {
+          return directoryIsUnderCVS(vFile);
+        }
+        return fileIsUnderCvs(getEntryFor(vFile));
+      } else {
+        return fileIsUnderCvs(vFile);
+      }
+    }
+    catch (Exception e1) {
+      return false;
+    }
+  }
+
   public static boolean fileIsUnderCvs(VirtualFile vFile) {
     return fileIsUnderCvs(CvsVfsUtil.getFileFor(vFile));
   }
@@ -125,6 +142,22 @@
     return true;
   }
 
+  private static boolean directoryIsUnderCVS(VirtualFile vDir) {
+    VirtualFile dir = getAdminDir(vDir);
+    if (dir == null) return false;
+
+    if (!hasPlainFileInTheAdminDir(dir, ENTRIES)) return false;
+    if (!hasPlainFileInTheAdminDir(dir, CVS_ROOT_FILE)) return false;
+    if (!hasPlainFileInTheAdminDir(dir, REPOSITORY)) return false;
+
+    return true;
+  }
+
+  private static boolean hasPlainFileInTheAdminDir(VirtualFile dir, String filename) {
+    VirtualFile child = dir.findChild(filename);
+    return child != null && !child.isDirectory();
+  }
+
   public static Entry getEntryFor(@NotNull VirtualFile file) {
     return CvsEntriesManager.getInstance().getEntryFor(file.getParent(), file.getName());
   }
@@ -301,6 +334,11 @@
     return new File(file, CVS);
   }
 
+  private static VirtualFile getAdminDir(VirtualFile file) {
+    VirtualFile child = file.findChild(CVS);
+    return child != null && child.isDirectory() ? child:null;
+  }
+
   @Nullable
   public static String getStickyDateForDirectory(VirtualFile parentFile) {
     File file = CvsVfsUtil.getFileFor(parentFile);
diff --git a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/common/FindAllRootsHelper.java b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/common/FindAllRootsHelper.java
index 47527c4..2f73e9f 100644
--- a/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/common/FindAllRootsHelper.java
+++ b/plugins/cvs/cvs-plugin/src/com/intellij/cvsSupport2/cvsoperations/common/FindAllRootsHelper.java
@@ -66,7 +66,7 @@
     }
 
     public boolean process(VirtualFile file) {
-      if (CvsUtil.fileIsUnderCvs(file)) {
+      if (CvsUtil.fileIsUnderCvsMaybeWithVfs(file)) {
         myFound.add(file);
       }
       return true;
diff --git a/plugins/devkit/devkit.iml b/plugins/devkit/devkit.iml
index 8c3fc85..494abc9 100644
--- a/plugins/devkit/devkit.iml
+++ b/plugins/devkit/devkit.iml
@@ -39,6 +39,7 @@
       </library>
     </orderEntry>
     <orderEntry type="module" module-name="spellchecker" />
+    <orderEntry type="module" module-name="dom-tests" scope="TEST" />
   </component>
 </module>
 
diff --git a/plugins/devkit/resources/fileTemplates/j2ee/plugin.xml.ft b/plugins/devkit/resources/fileTemplates/j2ee/plugin.xml.ft
index 71f115b..01841ba 100644
--- a/plugins/devkit/resources/fileTemplates/j2ee/plugin.xml.ft
+++ b/plugins/devkit/resources/fileTemplates/j2ee/plugin.xml.ft
@@ -6,24 +6,28 @@
 
   <description><![CDATA[
       Enter short description for your plugin here.<br>
-      <small>most HTML tags may be used</small>
-      ]]></description>
+      <em>most HTML tags may be used</em>
+    ]]></description>
 
   <change-notes><![CDATA[
       Add change notes here.<br>
-      <small>most HTML tags may be used</small>
-      ]]>
+      <em>most HTML tags may be used</em>
+    ]]>
   </change-notes>
 
-  <!-- please see http://confluence.jetbrains.net/display/IDEADEV/Build+Number+Ranges for description -->
-  <idea-version since-build="107.105"/>
+  <!-- please see http://confluence.jetbrains.com/display/IDEADEV/Build+Number+Ranges for description -->
+  <idea-version since-build="131"/>
 
-  <!-- please see http://confluence.jetbrains.net/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
+  <!-- please see http://confluence.jetbrains.com/display/IDEADEV/Plugin+Compatibility+with+IntelliJ+Platform+Products
        on how to target different products -->
   <!-- uncomment to enable plugin in all products
   <depends>com.intellij.modules.lang</depends>
   -->
 
+  <extensions defaultExtensionNs="com.intellij">
+    <!-- Add your extensions here -->
+  </extensions>
+
   <application-components>
     <!-- Add your application components here -->
   </application-components>
@@ -36,7 +40,4 @@
     <!-- Add your actions here -->
   </actions>
 
-  <extensions defaultExtensionNs="com.intellij">
-    <!-- Add your extensions here -->
-  </extensions>
 </idea-plugin>
\ No newline at end of file
diff --git a/plugins/devkit/src/build/PrepareAllToDeployAction.java b/plugins/devkit/src/build/PrepareAllToDeployAction.java
index 051a891..9d26f3b 100644
--- a/plugins/devkit/src/build/PrepareAllToDeployAction.java
+++ b/plugins/devkit/src/build/PrepareAllToDeployAction.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,14 +18,13 @@
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
 import com.intellij.openapi.actionSystem.LangDataKeys;
-import com.intellij.openapi.actionSystem.PlatformDataKeys;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.module.ModuleType;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.roots.ui.configuration.ChooseModulesDialog;
 import org.jetbrains.idea.devkit.DevKitBundle;
 import org.jetbrains.idea.devkit.module.PluginModuleType;
-import org.jetbrains.idea.devkit.util.ChooseModulesDialog;
 
 import java.util.ArrayList;
 import java.util.List;
@@ -43,12 +42,13 @@
       }
     }
 
-    //TODO replace with com.intellij.openapi.roots.ui.configuration.libraryEditor.ChooseModulesDialog
-    ChooseModulesDialog dialog = new ChooseModulesDialog(project, pluginModules, DevKitBundle.message("select.plugin.modules.title"),
+    ChooseModulesDialog dialog = new ChooseModulesDialog(project,
+                                                         pluginModules,
+                                                         DevKitBundle.message("select.plugin.modules.title"),
                                                          DevKitBundle.message("select.plugin.modules.description"));
     dialog.show();
     if (dialog.isOK()) {
-      doPrepare(dialog.getSelectedModules(), project);
+      doPrepare(dialog.getChosenElements(), project);
     }
   }
 
diff --git a/plugins/devkit/src/dom/Extensions.java b/plugins/devkit/src/dom/Extensions.java
index 6428d35..ebf9ef5 100644
--- a/plugins/devkit/src/dom/Extensions.java
+++ b/plugins/devkit/src/dom/Extensions.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,10 +19,7 @@
 
 package org.jetbrains.idea.devkit.dom;
 
-import com.intellij.util.xml.Attribute;
-import com.intellij.util.xml.Convert;
-import com.intellij.util.xml.DomElement;
-import com.intellij.util.xml.GenericAttributeValue;
+import com.intellij.util.xml.*;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.idea.devkit.dom.impl.ExtensionNsConverter;
 
@@ -32,10 +29,12 @@
   @NotNull
   @Attribute("defaultExtensionNs")
   @Convert(value=ExtensionNsConverter.class, soft=true)
+  @Stubbed
   GenericAttributeValue<IdeaPlugin> getDefaultExtensionNs();
 
   @NotNull
   @Convert(value=ExtensionNsConverter.class, soft=true)
+  @Stubbed
   GenericAttributeValue<IdeaPlugin> getXmlns();
 
   List<Extension> getExtensions();
diff --git a/plugins/devkit/src/dom/IdeaPlugin.java b/plugins/devkit/src/dom/IdeaPlugin.java
index 6b5bb48..d624be7 100644
--- a/plugins/devkit/src/dom/IdeaPlugin.java
+++ b/plugins/devkit/src/dom/IdeaPlugin.java
@@ -105,6 +105,7 @@
 
   @NotNull
   @SubTagList("extensions")
+  @Stubbed
   List<Extensions> getExtensions();
   Extensions addExtensions();
 
diff --git a/plugins/devkit/src/dom/impl/PluginXmlDomFileDescription.java b/plugins/devkit/src/dom/impl/PluginXmlDomFileDescription.java
index d960091..f0dd66b 100644
--- a/plugins/devkit/src/dom/impl/PluginXmlDomFileDescription.java
+++ b/plugins/devkit/src/dom/impl/PluginXmlDomFileDescription.java
@@ -28,9 +28,7 @@
 import com.intellij.util.xml.highlighting.DomElementAnnotationHolder;
 import com.intellij.util.xml.highlighting.DomElementsAnnotator;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.idea.devkit.dom.Extension;
-import org.jetbrains.idea.devkit.dom.ExtensionPoint;
-import org.jetbrains.idea.devkit.dom.IdeaPlugin;
+import org.jetbrains.idea.devkit.dom.*;
 
 import javax.swing.*;
 
@@ -45,6 +43,17 @@
       if (element instanceof Extension) {
         annotateExtension((Extension)element, holder);
       }
+      else if (element instanceof Vendor) {
+        annotateVendor((Vendor)element, holder);
+      }
+      else if (element instanceof IdeaVersion) {
+        annotateIdeaVersion((IdeaVersion)element, holder);
+      }
+    }
+
+    private void annotateIdeaVersion(IdeaVersion ideaVersion, DomElementAnnotationHolder holder) {
+      highlightNotUsedAnymore(ideaVersion.getMin(), holder);
+      highlightNotUsedAnymore(ideaVersion.getMax(), holder);
     }
 
     private void annotateExtension(Extension extension, DomElementAnnotationHolder holder) {
@@ -59,6 +68,20 @@
         annotation.setHighlightType(ProblemHighlightType.LIKE_DEPRECATED);
       }
     }
+
+    private void annotateVendor(Vendor vendor, DomElementAnnotationHolder holder) {
+      highlightNotUsedAnymore(vendor.getLogo(), holder);
+    }
+
+    private void highlightNotUsedAnymore(GenericAttributeValue attributeValue,
+                                         DomElementAnnotationHolder holder) {
+      if (!DomUtil.hasXml(attributeValue)) return;
+
+      final Annotation annotation = holder.createAnnotation(attributeValue,
+                                                            HighlightSeverity.WARNING,
+                                                            "Not used anymore");
+      annotation.setHighlightType(ProblemHighlightType.LIKE_DEPRECATED);
+    }
   };
 
   public PluginXmlDomFileDescription() {
@@ -80,4 +103,9 @@
   public boolean hasStubs() {
     return true;
   }
+
+  @Override
+  public int getStubVersion() {
+    return 2;
+  }
 }
diff --git a/plugins/devkit/testData/codeInsight/deprecatedAttributes.xml b/plugins/devkit/testData/codeInsight/deprecatedAttributes.xml
new file mode 100644
index 0000000..9b14b40
--- /dev/null
+++ b/plugins/devkit/testData/codeInsight/deprecatedAttributes.xml
@@ -0,0 +1,11 @@
+<idea-plugin>
+  <id>com.intellij.myPlugin</id>
+
+  <vendor <warning descr="Not used anymore">logo="deprecated"</warning>/>
+
+  <idea-version since-build="133"
+                <warning descr="Not used anymore">min="deprecated"</warning>
+                <warning descr="Not used anymore">max="deprecated"</warning>
+                />
+
+</idea-plugin>
\ No newline at end of file
diff --git a/plugins/devkit/testData/codeInsight/pluginXmlStubs.xml b/plugins/devkit/testData/codeInsight/pluginXmlStubs.xml
new file mode 100644
index 0000000..3000339
--- /dev/null
+++ b/plugins/devkit/testData/codeInsight/pluginXmlStubs.xml
@@ -0,0 +1,20 @@
+<idea-plugin>
+  <id>com.intellij.myPlugin</id>
+  <name>pluginName</name>
+
+  <depends>anotherPlugin</depends>
+  <module value="myModule"/>
+
+  <extensions xmlns="someNS" defaultExtensionNs="com.intellij">
+    <actionPromoter implementation="someImpl"/>
+  </extensions>
+
+  <extensionPoints>
+    <extensionPoint name="myEP" interface="SomeInterface">
+    <with attribute="attributeName" implements="SomeImplements"/>
+    </extensionPoint>
+
+    <extensionPoint qualifiedName="qualifiedName" beanClass="BeanClass"/>
+  </extensionPoints>
+
+</idea-plugin>
\ No newline at end of file
diff --git a/plugins/devkit/testSources/codeInsight/PluginXmlDomStubsTest.java b/plugins/devkit/testSources/codeInsight/PluginXmlDomStubsTest.java
new file mode 100644
index 0000000..4326a14
--- /dev/null
+++ b/plugins/devkit/testSources/codeInsight/PluginXmlDomStubsTest.java
@@ -0,0 +1,52 @@
+/*
+ * 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.idea.devkit.codeInsight;
+
+import com.intellij.openapi.application.PluginPathManager;
+import com.intellij.util.xml.stubs.DomStubTest;
+
+public class PluginXmlDomStubsTest extends DomStubTest {
+
+  public void testStubs() {
+    doBuilderTest("pluginXmlStubs.xml",
+                  "File:idea-plugin\n" +
+                  "  Element:idea-plugin\n" +
+                  "    Element:id\n" +
+                  "    Element:name\n" +
+                  "    Element:depends\n" +
+                  "    Element:module\n" +
+                  "      Attribute:value:myModule\n" +
+                  "    Element:extensions\n" +
+                  "      Attribute:xmlns:someNS\n" +
+                  "      Attribute:defaultExtensionNs:com.intellij\n" +
+                  "    Element:extensionPoints\n" +
+                  "      Element:extensionPoint\n" +
+                  "        Attribute:name:myEP\n" +
+                  "        Attribute:interface:SomeInterface\n" +
+                  "        Element:with\n" +
+                  "          Attribute:attribute:attributeName\n" +
+                  "          Attribute:implements:SomeImplements\n" +
+                  "      Element:extensionPoint\n" +
+                  "        Attribute:qualifiedName:qualifiedName\n" +
+                  "        Attribute:beanClass:BeanClass\n"
+    );
+  }
+
+  @Override
+  protected String getBasePath() {
+    return PluginPathManager.getPluginHomePathRelative("devkit") + "/testData/codeInsight";
+  }
+}
diff --git a/plugins/devkit/testSources/codeInsight/PluginXmlFunctionalTest.groovy b/plugins/devkit/testSources/codeInsight/PluginXmlFunctionalTest.groovy
index 76cc9b1..e6e588f 100644
--- a/plugins/devkit/testSources/codeInsight/PluginXmlFunctionalTest.groovy
+++ b/plugins/devkit/testSources/codeInsight/PluginXmlFunctionalTest.groovy
@@ -196,6 +196,10 @@
     myFixture.testHighlighting("deprecatedExtensionAttribute.xml", "MyExtBean.java");
   }
 
+  public void testDeprecatedAttributes() {
+    myFixture.testHighlighting("deprecatedAttributes.xml")
+  }
+
   public void testExtensionAttributeDeclaredUsingAccessors() {
     myFixture.testHighlighting("extensionAttributeWithAccessors.xml", "ExtBeanWithAccessors.java");
   }
diff --git a/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java b/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java
index 113cf49..42363ba 100644
--- a/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java
+++ b/plugins/eclipse/jps-plugin/src/org/jetbrains/jps/eclipse/model/JpsEclipseClasspathReader.java
@@ -31,6 +31,7 @@
 import org.jetbrains.jps.model.module.*;
 import org.jetbrains.jps.model.serialization.JpsMacroExpander;
 import org.jetbrains.jps.model.serialization.library.JpsLibraryTableSerializer;
+import org.jetbrains.jps.model.serialization.library.JpsSdkTableSerializer;
 
 import java.io.File;
 import java.io.FilenameFilter;
@@ -96,6 +97,10 @@
                                 Collection<String> unknownJdks,
                                 EclipseModuleManager eclipseModuleManager,
                                 String jdkName) {
+    if (LOG.isDebugEnabled()) {
+      LOG.debug("loading " + rootModel.getName() + ": set module jdk " + jdkName);
+    }
+    rootModel.getDependenciesList().addSdkDependency(JpsJavaSdkType.INSTANCE);
   }
 
   @Override
diff --git a/plugins/eclipse/resources/META-INF/plugin.xml b/plugins/eclipse/resources/META-INF/plugin.xml
index 5145ea5..b3cd54d 100644
--- a/plugins/eclipse/resources/META-INF/plugin.xml
+++ b/plugins/eclipse/resources/META-INF/plugin.xml
@@ -14,7 +14,7 @@
     <fileTypeFactory implementation="org.jetbrains.idea.eclipse.config.EclipseFileTypeFactory"/>
     <syntaxHighlighter key="Eclipse" implementationClass="com.intellij.ide.highlighter.XmlFileHighlighter"/>
     <schemeImporter 
-        name="Eclpse XML Profile"
+        name="Eclipse XML Profile"
         implementationClass="org.jetbrains.idea.eclipse.importer.EclipseCodeStyleSchemeImporter"
         schemeClass="com.intellij.psi.codeStyle.CodeStyleScheme"/>
   </extensions>
diff --git a/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java b/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java
index 6b4def5..c1832f6 100644
--- a/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java
+++ b/plugins/git4idea/src/git4idea/branch/GitBranchUtil.java
@@ -30,6 +30,7 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.roots.*;
 import com.intellij.openapi.ui.Messages;
+import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vcs.AbstractVcs;
 import com.intellij.openapi.vcs.ProjectLevelVcsManager;
 import com.intellij.openapi.vcs.VcsException;
@@ -38,6 +39,7 @@
 import com.intellij.openapi.wm.StatusBar;
 import com.intellij.openapi.wm.WindowManager;
 import com.intellij.openapi.wm.impl.status.StatusBarUtil;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.vcs.log.Hash;
 import com.intellij.vcsUtil.VcsUtil;
 import git4idea.*;
@@ -52,6 +54,8 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.io.File;
+import java.io.IOException;
 import java.util.*;
 
 /**
@@ -68,6 +72,8 @@
       return input.getName();
     }
   };
+  // The name that specifies that git is on specific commit rather then on some branch ({@value})
+ private static final String NO_BRANCH_NAME = "(no branch)";
 
   private GitBranchUtil() {}
 
@@ -542,4 +548,107 @@
     return rootCandidate;
   }
 
+  @NotNull
+  public static Collection<String> getCommonBranches(Collection<GitRepository> repositories,
+                                                     boolean local) {
+    Collection<String> commonBranches = null;
+    for (GitRepository repository : repositories) {
+      GitBranchesCollection branchesCollection = repository.getBranches();
+
+      Collection<String> names = local
+                                 ? convertBranchesToNames(branchesCollection.getLocalBranches())
+                                 : getBranchNamesWithoutRemoteHead(branchesCollection.getRemoteBranches());
+      if (commonBranches == null) {
+        commonBranches = names;
+      }
+      else {
+        commonBranches = ContainerUtil.intersection(commonBranches, names);
+      }
+    }
+
+    if (commonBranches != null) {
+      ArrayList<String> common = new ArrayList<String>(commonBranches);
+      Collections.sort(common);
+      return common;
+    }
+    else {
+      return Collections.emptyList();
+    }
+  }
+
+  /**
+   * List branches containing a commit. Specify null if no commit filtering is needed.
+   */
+  @NotNull
+  public static Collection<String> getBranches(@NotNull Project project, @NotNull VirtualFile root, boolean localWanted,
+                                               boolean remoteWanted, @Nullable String containingCommit) throws VcsException {
+    // preparing native command executor
+    final GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.BRANCH);
+    handler.setSilent(true);
+    handler.addParameters("--no-color");
+    boolean remoteOnly = false;
+    if (remoteWanted && localWanted) {
+      handler.addParameters("-a");
+      remoteOnly = false;
+    } else if (remoteWanted) {
+      handler.addParameters("-r");
+      remoteOnly = true;
+    }
+    if (containingCommit != null) {
+      handler.addParameters("--contains", containingCommit);
+    }
+    final String output = handler.run();
+
+    if (output.trim().length() == 0) {
+      // the case after git init and before first commit - there is no branch and no output, and we'll take refs/heads/master
+      String head;
+      try {
+        head = FileUtil.loadFile(new File(root.getPath(), GitRepositoryFiles.GIT_HEAD), GitUtil.UTF8_ENCODING).trim();
+        final String prefix = "ref: refs/heads/";
+        return head.startsWith(prefix) ?
+               Collections.singletonList(head.substring(prefix.length())) :
+               Collections.<String>emptyList();
+      } catch (IOException e) {
+        LOG.info(e);
+        return Collections.emptyList();
+      }
+    }
+
+    Collection<String> branches = ContainerUtil.newArrayList();
+    // standard situation. output example:
+    //  master
+    //* my_feature
+    //  remotes/origin/HEAD -> origin/master
+    //  remotes/origin/eap
+    //  remotes/origin/feature
+    //  remotes/origin/master
+    // also possible:
+    //* (no branch)
+    // and if we call with -r instead of -a, remotes/ prefix is omitted:
+    // origin/HEAD -> origin/master
+    final String[] split = output.split("\n");
+    for (String b : split) {
+      b = b.substring(2).trim();
+      if (b.equals(NO_BRANCH_NAME)) { continue; }
+
+      String remotePrefix = null;
+      if (b.startsWith("remotes/")) {
+        remotePrefix = "remotes/";
+      } else if (b.startsWith(GitBranch.REFS_REMOTES_PREFIX)) {
+        remotePrefix = GitBranch.REFS_REMOTES_PREFIX;
+      }
+      boolean isRemote = remotePrefix != null || remoteOnly;
+      if (isRemote) {
+        if (! remoteOnly) {
+          b = b.substring(remotePrefix.length());
+        }
+        final int idx = b.indexOf("HEAD ->");
+        if (idx > 0) {
+          continue;
+        }
+      }
+      branches.add(b);
+    }
+    return branches;
+  }
 }
diff --git a/plugins/git4idea/src/git4idea/branch/GitBranchesCollection.java b/plugins/git4idea/src/git4idea/branch/GitBranchesCollection.java
index 13da918..e3081f9 100644
--- a/plugins/git4idea/src/git4idea/branch/GitBranchesCollection.java
+++ b/plugins/git4idea/src/git4idea/branch/GitBranchesCollection.java
@@ -23,7 +23,6 @@
 
 import java.util.Collection;
 import java.util.Collections;
-import java.util.HashSet;
 
 /**
  * <p>
@@ -49,27 +48,14 @@
     myLocalBranches = localBranches;
   }
 
-  /**
-   * Copy constructor. Sets inside are also copied.
-   */
-  public GitBranchesCollection(@NotNull GitBranchesCollection branches) {
-    this(branches.getLocalBranches(), branches.getRemoteBranches());
-  }
-
-  /**
-   * @return the copy of local branches set.
-   */
   @NotNull
   public Collection<GitLocalBranch> getLocalBranches() {
-    return new HashSet<GitLocalBranch>(myLocalBranches);
+    return Collections.unmodifiableCollection(myLocalBranches);
   }
 
-  /**
-   * @return the copy of remote branches set.
-   */
   @NotNull
   public Collection<GitRemoteBranch> getRemoteBranches() {
-    return new HashSet<GitRemoteBranch>(myRemoteBranches);
+    return Collections.unmodifiableCollection(myRemoteBranches);
   }
 
   public GitLocalBranch findLocalBranch(@NotNull final String name) {
diff --git a/plugins/git4idea/src/git4idea/branch/GitDeleteBranchOperation.java b/plugins/git4idea/src/git4idea/branch/GitDeleteBranchOperation.java
index dfa570d..68e17a9 100644
--- a/plugins/git4idea/src/git4idea/branch/GitDeleteBranchOperation.java
+++ b/plugins/git4idea/src/git4idea/branch/GitDeleteBranchOperation.java
@@ -20,6 +20,7 @@
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Key;
 import com.intellij.util.ArrayUtil;
+import com.intellij.util.containers.ContainerUtil;
 import git4idea.GitCommit;
 import git4idea.GitPlatformFacade;
 import git4idea.GitVcs;
@@ -199,7 +200,7 @@
         mergedToBranches = branches;
       } 
       else {
-        mergedToBranches.retainAll(branches);
+        mergedToBranches = new ArrayList<String>(ContainerUtil.intersection(mergedToBranches, branches));
       }
     }
     return mergedToBranches != null ? mergedToBranches : new ArrayList<String>();
diff --git a/plugins/git4idea/src/git4idea/branch/GitDeleteRemoteBranchOperation.java b/plugins/git4idea/src/git4idea/branch/GitDeleteRemoteBranchOperation.java
index bdc24da..1d63456 100644
--- a/plugins/git4idea/src/git4idea/branch/GitDeleteRemoteBranchOperation.java
+++ b/plugins/git4idea/src/git4idea/branch/GitDeleteRemoteBranchOperation.java
@@ -10,7 +10,7 @@
 import com.intellij.notification.NotificationType;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.MessageBuilder;
+import com.intellij.openapi.ui.MessageDialogBuilder;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.text.StringUtil;
@@ -231,7 +231,7 @@
       }
 
       final AtomicBoolean deleteChoice = new AtomicBoolean();
-      delete = MessageBuilder.yesNo(title, message).project(myProject).yesText("Delete").noText("Cancel").doNotAsk(new DialogWrapper.DoNotAskOption() {
+      delete = MessageDialogBuilder.yesNo(title, message).project(myProject).yesText("Delete").noText("Cancel").doNotAsk(new DialogWrapper.DoNotAskOption() {
         @Override
         public boolean isToBeShown() {
           return true;
diff --git a/plugins/git4idea/src/git4idea/history/browser/LowLevelAccessImpl.java b/plugins/git4idea/src/git4idea/history/browser/LowLevelAccessImpl.java
index eaea1cf..e4f8164 100644
--- a/plugins/git4idea/src/git4idea/history/browser/LowLevelAccessImpl.java
+++ b/plugins/git4idea/src/git4idea/history/browser/LowLevelAccessImpl.java
@@ -19,36 +19,31 @@
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Getter;
-import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vcs.FilePathImpl;
 import com.intellij.openapi.vcs.VcsException;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.AsynchConsumer;
-import git4idea.*;
+import git4idea.GitBranch;
+import git4idea.GitPlatformFacade;
+import git4idea.GitTag;
+import git4idea.GitUtil;
 import git4idea.branch.GitBranchUtil;
 import git4idea.branch.GitBranchesCollection;
-import git4idea.commands.GitCommand;
-import git4idea.commands.GitSimpleHandler;
 import git4idea.config.GitConfigUtil;
 import git4idea.history.GitHistoryUtils;
 import git4idea.history.wholeTree.AbstractHash;
 import git4idea.history.wholeTree.CommitHashPlusParents;
 import git4idea.repo.GitBranchTrackInfo;
 import git4idea.repo.GitRepository;
-import git4idea.repo.GitRepositoryFiles;
 import git4idea.repo.GitRepositoryImpl;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import java.io.File;
-import java.io.IOException;
 import java.util.*;
 
 public class LowLevelAccessImpl implements LowLevelAccess {
   private final static Logger LOG = Logger.getInstance("#git4idea.history.browser.LowLevelAccessImpl");
-   // The name that specifies that git is on specific commit rather then on some branch ({@value})
-  private static final String NO_BRANCH_NAME = "(no branch)";
 
   private final Project myProject;
   private final VirtualFile myRoot;
@@ -185,7 +180,7 @@
   }
 
   public List<String> getBranchesWithCommit(final String hash) throws VcsException {
-    return new ArrayList<String>(listAsStrings(myProject, myRoot, true, true, hash));
+    return new ArrayList<String>(GitBranchUtil.getBranches(myProject, myRoot, true, true, hash));
   }
 
   public Collection<String> getTagsWithCommit(final SHAHash hash) throws VcsException {
@@ -193,100 +188,4 @@
     GitTag.listAsStrings(myProject, myRoot, result, hash.getValue());
     return result;
   }
-
-  @NotNull
-  private static Collection<String> listAsStrings(@NotNull Project project, @NotNull VirtualFile root, boolean localWanted,
-                                                 boolean remoteWanted, @Nullable String containingCommit) throws VcsException {
-    return GitBranchUtil.convertBranchesToNames(list(project, root, localWanted, remoteWanted, containingCommit));
-  }
-  /**
-   * List branches containing a commit. Specify null if no commit filtering is needed.
-   */
-  @NotNull
-  private static Collection<? extends GitBranch> list(@NotNull Project project, @NotNull VirtualFile root, boolean localWanted, boolean remoteWanted,
-                                           @Nullable String containingCommit) throws VcsException {
-    // preparing native command executor
-    final GitSimpleHandler handler = new GitSimpleHandler(project, root, GitCommand.BRANCH);
-    handler.setSilent(true);
-    handler.addParameters("--no-color");
-    boolean remoteOnly = false;
-    if (remoteWanted && localWanted) {
-      handler.addParameters("-a");
-      remoteOnly = false;
-    } else if (remoteWanted) {
-      handler.addParameters("-r");
-      remoteOnly = true;
-    }
-    if (containingCommit != null) {
-      handler.addParameters("--contains", containingCommit);
-    }
-    final String output = handler.run();
-
-    if (output.trim().length() == 0) {
-      // the case after git init and before first commit - there is no branch and no output, and we'll take refs/heads/master
-      String head;
-      try {
-        head = FileUtil.loadFile(new File(root.getPath(), GitRepositoryFiles.GIT_HEAD), GitUtil.UTF8_ENCODING).trim();
-        final String prefix = "ref: refs/heads/";
-        return head.startsWith(prefix) ?
-               Collections.singletonList(new GitLocalBranch(head.substring(prefix.length()), GitBranch.DUMMY_HASH)) :
-               null;
-      } catch (IOException e) {
-        LOG.info(e);
-        return null;
-      }
-    }
-
-    Collection<GitBranch> branches = new ArrayList<GitBranch>();
-    // standard situation. output example:
-    //  master
-    //* my_feature
-    //  remotes/origin/HEAD -> origin/master
-    //  remotes/origin/eap
-    //  remotes/origin/feature
-    //  remotes/origin/master
-    // also possible:
-    //* (no branch)
-    // and if we call with -r instead of -a, remotes/ prefix is omitted:
-    // origin/HEAD -> origin/master
-    final String[] split = output.split("\n");
-    for (String b : split) {
-      b = b.substring(2).trim();
-      if (b.equals(NO_BRANCH_NAME)) { continue; }
-
-      String remotePrefix = null;
-      if (b.startsWith("remotes/")) {
-        remotePrefix = "remotes/";
-      } else if (b.startsWith(GitBranch.REFS_REMOTES_PREFIX)) {
-        remotePrefix = GitBranch.REFS_REMOTES_PREFIX;
-      }
-      boolean isRemote = remotePrefix != null || remoteOnly;
-      if (isRemote) {
-        if (! remoteOnly) {
-          b = b.substring(remotePrefix.length());
-        }
-        final int idx = b.indexOf("HEAD ->");
-        if (idx > 0) {
-          continue;
-        }
-      }
-      GitBranch branch = null;
-      if (isRemote) {
-        GitRepository repository = getRepositoryWise(project, root);
-        if (repository != null) {
-          branch = GitBranchUtil.parseRemoteBranch(b, GitBranch.DUMMY_HASH, repository.getRemotes());
-        }
-      }
-      else {
-        branch = new GitLocalBranch(b, GitBranch.DUMMY_HASH);
-      }
-
-      if (branch != null && ((isRemote && remoteWanted) || (!isRemote && localWanted))) {
-        branches.add(branch);
-      }
-    }
-    return branches;
-  }
-
-
 }
diff --git a/plugins/git4idea/src/git4idea/history/wholeTree/SelectRevisionInGitLogAction.java b/plugins/git4idea/src/git4idea/history/wholeTree/SelectRevisionInGitLogAction.java
index 3b015ce..7c88a1c 100644
--- a/plugins/git4idea/src/git4idea/history/wholeTree/SelectRevisionInGitLogAction.java
+++ b/plugins/git4idea/src/git4idea/history/wholeTree/SelectRevisionInGitLogAction.java
@@ -2,6 +2,7 @@
 
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
+import com.intellij.openapi.components.ServiceManager;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.vcs.VcsDataKeys;
@@ -13,7 +14,9 @@
 import com.intellij.openapi.wm.ToolWindowManager;
 import com.intellij.ui.content.Content;
 import com.intellij.ui.content.ContentManager;
-import git4idea.history.browser.GitProjectLogManager;
+import com.intellij.vcs.log.impl.VcsLogContentProvider;
+import com.intellij.vcs.log.impl.VcsLogManager;
+import com.intellij.vcs.log.ui.VcsLogUI;
 import git4idea.i18n.GitBundle;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -36,7 +39,7 @@
       return;
     }
 
-    final GitLog log = GitProjectLogManager.getInstance(project).getLog();
+    final VcsLogManager log = ServiceManager.getService(project, VcsLogManager.class);
     if (log == null) {
       return;
     }
@@ -45,7 +48,7 @@
     ContentManager cm = window.getContentManager();
     Content[] contents = cm.getContents();
     for (Content content : contents) {
-      if (GitProjectLogManager.CONTENT_KEY.equals(content.getDisplayName())) {
+      if (VcsLogContentProvider.TAB_NAME.equals(content.getDisplayName())) {
         cm.setSelectedContent(content);
       }
     }
@@ -53,7 +56,11 @@
     Runnable selectCommit = new Runnable() {
       @Override
       public void run() {
-        log.selectCommit(revision.asString());
+        VcsLogUI logUi = log.getLogUi();
+        if (logUi == null) {
+          return;
+        }
+        logUi.getVcsLog().jumpToReference(revision.asString());
       }
     };
 
diff --git a/plugins/git4idea/src/git4idea/log/GitLogProvider.java b/plugins/git4idea/src/git4idea/log/GitLogProvider.java
index c259035..1228928 100644
--- a/plugins/git4idea/src/git4idea/log/GitLogProvider.java
+++ b/plugins/git4idea/src/git4idea/log/GitLogProvider.java
@@ -16,6 +16,7 @@
 package git4idea.log;
 
 import com.intellij.openapi.components.ServiceManager;
+import com.intellij.openapi.diagnostic.Attachment;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.text.StringUtil;
@@ -24,6 +25,7 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Consumer;
+import com.intellij.util.ExceptionUtil;
 import com.intellij.util.Function;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.vcs.log.*;
@@ -36,6 +38,7 @@
 import git4idea.GitLocalBranch;
 import git4idea.GitRemoteBranch;
 import git4idea.GitVcs;
+import git4idea.branch.GitBranchUtil;
 import git4idea.commands.GitCommand;
 import git4idea.commands.GitSimpleHandler;
 import git4idea.config.GitConfigUtil;
@@ -138,11 +141,17 @@
     tagHandler.addParameters("--tags", "--no-walk", "--format=%H%d" + GitLogParser.RECORD_START_GIT, "--decorate=full");
     String out = tagHandler.run();
     Collection<VcsRef> refs = new ArrayList<VcsRef>();
-    for (String record : out.split(GitLogParser.RECORD_START)) {
-      if (!StringUtil.isEmptyOrSpaces(record)) {
-        refs.addAll(new RefParser(myVcsObjectsFactory).parseCommitRefs(record.trim(), root));
+    try {
+      for (String record : out.split(GitLogParser.RECORD_START)) {
+        if (!StringUtil.isEmptyOrSpaces(record)) {
+          refs.addAll(new RefParser(myVcsObjectsFactory).parseCommitRefs(record.trim(), root));
+        }
       }
     }
+    catch (Exception e) {
+      LOG.error("Error during tags parsing", new Attachment("stack_trace.txt", ExceptionUtil.getThrowableText(e)),
+                new Attachment("git_output.txt", out));
+    }
     return refs;
   }
 
@@ -179,13 +188,13 @@
 
     List<VcsLogBranchFilter> branchFilters = ContainerUtil.findAll(filters, VcsLogBranchFilter.class);
     if (!branchFilters.isEmpty()) {
-      String branchFilter = joinFilters(branchFilters, new Function<VcsLogBranchFilter, String>() {
-        @Override
-        public String fun(VcsLogBranchFilter filter) {
-          return filter.getBranchName();
-        }
-      });
-      filterParameters.add(prepareParameter("branches", branchFilter));
+      // git doesn't support filtering by several branches very well (--branches parameter give a weak pattern capabilities)
+      // => by now assuming there is only one branch filter.
+      if (branchFilters.size() > 1) {
+        LOG.warn("More than one branch filter was passed. Using only the first one.");
+      }
+      VcsLogBranchFilter branchFilter = branchFilters.get(0);
+      filterParameters.add(branchFilter.getBranchName());
     }
     else {
       filterParameters.add("--all");
@@ -247,6 +256,12 @@
     return userName == null ? null : myVcsObjectsFactory.createUser(userName, userEmail);
   }
 
+  @NotNull
+  @Override
+  public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException {
+    return GitBranchUtil.getBranches(myProject, root, true, true, commitHash.asString());
+  }
+
   private static String prepareParameter(String paramName, String value) {
     return "--" + paramName + "=" + value; // no value escaping needed, because the parameter itself will be quoted by GeneralCommandLine
   }
diff --git a/plugins/git4idea/src/git4idea/log/GitRefManager.java b/plugins/git4idea/src/git4idea/log/GitRefManager.java
index 867b825..5b60076 100644
--- a/plugins/git4idea/src/git4idea/log/GitRefManager.java
+++ b/plugins/git4idea/src/git4idea/log/GitRefManager.java
@@ -3,7 +3,9 @@
 import com.intellij.dvcs.repo.RepositoryManager;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.Condition;
+import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.ui.JBColor;
+import com.intellij.util.Function;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.MultiMap;
 import com.intellij.vcs.log.RefGroup;
@@ -12,14 +14,11 @@
 import com.intellij.vcs.log.VcsRefType;
 import com.intellij.vcs.log.impl.SingletonRefGroup;
 import git4idea.GitBranch;
-import git4idea.GitLocalBranch;
 import git4idea.GitRemoteBranch;
-import git4idea.branch.GitBranchesCollection;
 import git4idea.repo.GitBranchTrackInfo;
 import git4idea.repo.GitRemote;
 import git4idea.repo.GitRepository;
 import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
 
 import java.awt.*;
 import java.util.*;
@@ -136,36 +135,39 @@
     List<VcsRef> trackedBranches = ContainerUtil.newArrayList();
     MultiMap<GitRemote, VcsRef> remoteRefGroups = MultiMap.create();
 
-    for (VcsRef ref : refs) {
-      if (ref.getType() == HEAD) {
-        simpleGroups.add(new SingletonRefGroup(ref));
+    MultiMap<VirtualFile, VcsRef> refsByRoot = groupRefsByRoot(refs);
+    for (Map.Entry<VirtualFile, Collection<VcsRef>> entry : refsByRoot.entrySet()) {
+      VirtualFile root = entry.getKey();
+      Collection<VcsRef> refsInRoot = entry.getValue();
+
+      GitRepository repository = myRepositoryManager.getRepositoryForRoot(root);
+      if (repository == null) {
+        LOG.warn("No repository for root: " + root);
+        continue;
       }
-      else {
-        GitRepository repository = myRepositoryManager.getRepositoryForRoot(ref.getRoot());
-        if (repository == null) {
-          LOG.warn("No repository for root: " + ref.getRoot());
+
+      Set<String> locals = getLocalBranches(repository);
+      Set<String> tracked = getTrackedRemoteBranches(repository);
+      Map<String, GitRemote> nonTracked = getNonTrackedRemoteBranches(repository);
+
+      for (VcsRef ref : refsInRoot) {
+        if (ref.getType() == HEAD) {
+          simpleGroups.add(new SingletonRefGroup(ref));
           continue;
         }
-        Collection<GitBranchTrackInfo> trackInfos = repository.getBranchTrackInfos();
-        GitBranchesCollection branches = repository.getBranches();
 
-        GitLocalBranch localBranch = findBranchByName(ref, branches.getLocalBranches());
-        if (localBranch != null) {
+        String refName = ref.getName();
+        if (locals.contains(refName)) {
           localBranches.add(ref);
         }
+        else if (tracked.contains(refName)) {
+          trackedBranches.add(ref);
+        }
+        else if (nonTracked.containsKey(refName)) {
+          remoteRefGroups.putValue(nonTracked.get(refName), ref);
+        }
         else {
-          GitRemoteBranch remoteBranch = findBranchByName(ref, branches.getRemoteBranches());
-          if (remoteBranch != null) {
-            if (isTracked(trackInfos, remoteBranch)) {
-              trackedBranches.add(ref);
-            }
-            else {
-              remoteRefGroups.putValue(remoteBranch.getRemote(), ref);
-            }
-          }
-          else {
-            LOG.warn("Didn't find ref neither in local nor in remote branches: " + ref);
-          }
+          LOG.warn("Didn't find ref neither in local nor in remote branches: " + ref);
         }
       }
     }
@@ -182,23 +184,57 @@
     return result;
   }
 
-  @Nullable
-  private static <T extends GitBranch> T findBranchByName(final VcsRef ref, Collection<T> branches) {
-    return ContainerUtil.find(branches, new Condition<T>() {
+  private static Set<String> getLocalBranches(GitRepository repository) {
+    return ContainerUtil.map2Set(repository.getBranches().getLocalBranches(), new Function<GitBranch, String>() {
       @Override
-      public boolean value(T branch) {
-        return branch.getName().equals(ref.getName());
+      public String fun(GitBranch branch) {
+        return branch.getName();
       }
     });
   }
 
-  private static boolean isTracked(Collection<GitBranchTrackInfo> trackInfos, final GitRemoteBranch remoteBranch) {
-    return ContainerUtil.find(trackInfos, new Condition<GitBranchTrackInfo>() {
-      @Override
-      public boolean value(GitBranchTrackInfo info) {
-        return info.getRemoteBranch().equals(remoteBranch);
+  @NotNull
+  private static Set<String> getTrackedRemoteBranches(@NotNull GitRepository repository) {
+    Set<GitRemoteBranch> all = new HashSet<GitRemoteBranch>(repository.getBranches().getRemoteBranches());
+    Set<String> tracked = new HashSet<String>();
+    for (GitBranchTrackInfo info : repository.getBranchTrackInfos()) {
+      GitRemoteBranch trackedRemoteBranch = info.getRemoteBranch();
+      if (all.contains(trackedRemoteBranch)) { // check that this branch really exists, not just written in .git/config
+        tracked.add(trackedRemoteBranch.getName());
       }
-    }) != null;
+    }
+    return tracked;
+  }
+
+  @NotNull
+  private static Map<String, GitRemote> getNonTrackedRemoteBranches(@NotNull GitRepository repository) {
+    Set<GitRemoteBranch> all = new HashSet<GitRemoteBranch>(repository.getBranches().getRemoteBranches());
+    Set<String> tracked = getTrackedRemoteBranchesFromConfig(repository);
+    Map<String, GitRemote> nonTracked = ContainerUtil.newHashMap();
+    for (GitRemoteBranch remoteBranch : all) {
+      if (!tracked.contains(remoteBranch.getName())) {
+        nonTracked.put(remoteBranch.getName(), remoteBranch.getRemote());
+      }
+    }
+    return nonTracked;
+  }
+
+  private static Set<String> getTrackedRemoteBranchesFromConfig(GitRepository repository) {
+    return ContainerUtil.map2Set(repository.getBranchTrackInfos(), new Function<GitBranchTrackInfo, String>() {
+      @Override
+      public String fun(GitBranchTrackInfo trackInfo) {
+        return trackInfo.getRemoteBranch().getName();
+      }
+    });
+  }
+
+  @NotNull
+  private static MultiMap<VirtualFile, VcsRef> groupRefsByRoot(@NotNull Iterable<VcsRef> refs) {
+    MultiMap<VirtualFile, VcsRef> grouped = MultiMap.create();
+    for (VcsRef ref : refs) {
+      grouped.putValue(ref.getRoot(), ref);
+    }
+    return grouped;
   }
 
   private static class SimpleRefType implements VcsRefType {
diff --git a/plugins/git4idea/src/git4idea/log/RefParser.java b/plugins/git4idea/src/git4idea/log/RefParser.java
index dfef6f3..619cfcd 100644
--- a/plugins/git4idea/src/git4idea/log/RefParser.java
+++ b/plugins/git4idea/src/git4idea/log/RefParser.java
@@ -9,6 +9,7 @@
 import org.jetbrains.annotations.Nullable;
 
 import java.util.ArrayList;
+import java.util.Collections;
 import java.util.List;
 
 
@@ -28,6 +29,9 @@
   // e25b7d8f (HEAD, refs/remotes/origin/master, refs/remotes/origin/HEAD, refs/heads/master)
   public List<VcsRef> parseCommitRefs(@NotNull String input, @NotNull VirtualFile root) {
     int firstSpaceIndex = input.indexOf(' ');
+    if (firstSpaceIndex < 0) {
+      return Collections.emptyList();
+    }
     String strHash = input.substring(0, firstSpaceIndex);
     Hash hash = HashImpl.build(strHash);
     String refPaths = input.substring(firstSpaceIndex + 2, input.length() - 1);
diff --git a/plugins/git4idea/src/git4idea/repo/GitRepositoryReader.java b/plugins/git4idea/src/git4idea/repo/GitRepositoryReader.java
index 1cf1356..fad294e 100644
--- a/plugins/git4idea/src/git4idea/repo/GitRepositoryReader.java
+++ b/plugins/git4idea/src/git4idea/repo/GitRepositoryReader.java
@@ -76,9 +76,15 @@
     myPackedRefsFile = new File(myGitDir, "packed-refs");
   }
 
-  @NotNull
+  @Nullable
   private static Hash createHash(@Nullable String hash) {
-    return hash == null ? GitBranch.DUMMY_HASH : HashImpl.build(hash);
+    try {
+      return hash == null ? GitBranch.DUMMY_HASH : HashImpl.build(hash);
+    }
+    catch (Throwable t) {
+      LOG.info(t);
+      return null;
+    }
   }
 
   @NotNull
@@ -133,7 +139,11 @@
     if (head.isBranch) {
       String branchName = head.ref;
       String hash = readCurrentRevision();  // TODO we know the branch name, so no need to read head twice
-      return new GitLocalBranch(branchName, createHash(hash));
+      Hash h = createHash(hash);
+      if (h == null) {
+        return null;
+      }
+      return new GitLocalBranch(branchName, h);
     }
     if (isRebaseInProgress()) {
       GitLocalBranch branch = readRebaseBranch("rebase-apply");
@@ -164,7 +174,10 @@
     if (!branchFile.exists()) { // can happen when rebasing from detached HEAD: IDEA-93806
       return null;
     }
-    Hash hash = HashImpl.build(readBranchFile(branchFile));
+    Hash hash = createHash(readBranchFile(branchFile));
+    if (hash == null) {
+      return null;
+    }
     if (branchName.startsWith(REFS_HEADS_PREFIX)) {
       branchName = branchName.substring(REFS_HEADS_PREFIX.length());
     }
@@ -293,7 +306,10 @@
       String branchName = entry.getKey();
       File branchFile = entry.getValue();
       String hash = loadHashFromBranchFile(branchFile);
-      branches.add(new GitLocalBranch(branchName, createHash(hash)));
+      Hash h = createHash(hash);
+      if (h != null) {
+        branches.add(new GitLocalBranch(branchName, h));
+      }
     }
     return branches;
   }
@@ -327,9 +343,12 @@
           if (relativePath != null) {
             String branchName = FileUtil.toSystemIndependentName(relativePath);
             String hash = loadHashFromBranchFile(file);
-            GitRemoteBranch remoteBranch = GitBranchUtil.parseRemoteBranch(branchName, createHash(hash), remotes);
-            if (remoteBranch != null) {
-              branches.add(remoteBranch);
+            Hash h = createHash(hash);
+            if (h != null) {
+              GitRemoteBranch remoteBranch = GitBranchUtil.parseRemoteBranch(branchName, h, remotes);
+              if (remoteBranch != null) {
+                branches.add(remoteBranch);
+              }
             }
           }
         }
@@ -352,16 +371,20 @@
     }
 
     readPackedRefsFile(new PackedRefsLineResultHandler() {
-      @Override public void handleResult(@Nullable String hash, @Nullable String branchName) {
-        if (hash == null || branchName == null) {
+      @Override public void handleResult(@Nullable String hashString, @Nullable String branchName) {
+        if (hashString == null || branchName == null) {
           return;
         }
-        hash = shortBuffer(hash);
+        hashString = shortBuffer(hashString);
+        Hash hash = createHash(hashString);
+        if (hash == null) {
+          return;
+        }
         if (branchName.startsWith(REFS_HEADS_PREFIX)) {
-          localBranches.add(new GitLocalBranch(branchName, HashImpl.build(hash)));
+          localBranches.add(new GitLocalBranch(branchName, hash));
         }
         else if (branchName.startsWith(REFS_REMOTES_PREFIX)) {
-          GitRemoteBranch remoteBranch = GitBranchUtil.parseRemoteBranch(branchName, HashImpl.build(hash), remotes);
+          GitRemoteBranch remoteBranch = GitBranchUtil.parseRemoteBranch(branchName, hash, remotes);
           if (remoteBranch != null) {
             remoteBranches.add(remoteBranch);
           }
diff --git a/plugins/git4idea/src/git4idea/ui/branch/GitMultiRootBranchConfig.java b/plugins/git4idea/src/git4idea/ui/branch/GitMultiRootBranchConfig.java
index a9974be..ba4dd2a 100644
--- a/plugins/git4idea/src/git4idea/ui/branch/GitMultiRootBranchConfig.java
+++ b/plugins/git4idea/src/git4idea/ui/branch/GitMultiRootBranchConfig.java
@@ -15,11 +15,11 @@
  */
 package git4idea.ui.branch;
 
+import com.intellij.util.containers.ContainerUtil;
 import git4idea.GitBranch;
 import git4idea.GitLocalBranch;
 import git4idea.GitRemoteBranch;
 import git4idea.branch.GitBranchUtil;
-import git4idea.branch.GitBranchesCollection;
 import git4idea.repo.GitBranchTrackInfo;
 import git4idea.repo.GitRepository;
 import org.jetbrains.annotations.NotNull;
@@ -78,12 +78,12 @@
   
   @NotNull
   Collection<String> getLocalBranches() {
-    return getCommonBranches(true);
+    return GitBranchUtil.getCommonBranches(myRepositories, true);
   }  
 
   @NotNull
   Collection<String> getRemoteBranches() {
-    return getCommonBranches(false);
+    return GitBranchUtil.getCommonBranches(myRepositories, false);
   }
 
   /**
@@ -121,7 +121,7 @@
         trackingBranches = tb;
       }
       else {
-        trackingBranches.retainAll(tb);
+        trackingBranches = ContainerUtil.intersection(trackingBranches, tb);
       }
     }
     return trackingBranches == null ? Collections.<String>emptyList() : trackingBranches;
@@ -144,33 +144,6 @@
     return branch == null ? null : branch.findTrackedBranch(repository);
   }
 
-  @NotNull
-  private Collection<String> getCommonBranches(boolean local) {
-    Collection<String> commonBranches = null;
-    for (GitRepository repository : myRepositories) {
-      GitBranchesCollection branchesCollection = repository.getBranches();
-
-      Collection<String> names = local
-                                 ? GitBranchUtil.convertBranchesToNames(branchesCollection.getLocalBranches())
-                                 : GitBranchUtil.getBranchNamesWithoutRemoteHead(branchesCollection.getRemoteBranches());
-      if (commonBranches == null) {
-        commonBranches = names;
-      }
-      else {
-        commonBranches.retainAll(names);
-      }
-    }
-
-    if (commonBranches != null) {
-      ArrayList<String> common = new ArrayList<String>(commonBranches);
-      Collections.sort(common);
-      return common;
-    }
-    else {
-      return Collections.emptyList();
-    }
-  }
-
   @Override
   public String toString() {
     StringBuilder sb = new StringBuilder();
diff --git a/plugins/git4idea/tests/git4idea/log/RefParserTest.java b/plugins/git4idea/tests/git4idea/log/RefParserTest.java
index 34f0375..f00fd07 100644
--- a/plugins/git4idea/tests/git4idea/log/RefParserTest.java
+++ b/plugins/git4idea/tests/git4idea/log/RefParserTest.java
@@ -65,7 +65,11 @@
     );
   }
 
-
+  @Test
+  public void noTagName() {
+    runTest("787ec72f340d740433ba068d4d58a6e58f6226bf", "");
+  }
+  
   private class TestLogObjectsFactory implements VcsLogObjectsFactory {
     @NotNull
     @Override
diff --git a/plugins/git4idea/tests/git4idea/roots/GitIntegrationEnablerTest.java b/plugins/git4idea/tests/git4idea/roots/GitIntegrationEnablerTest.java
index 8b36327..8643348 100644
--- a/plugins/git4idea/tests/git4idea/roots/GitIntegrationEnablerTest.java
+++ b/plugins/git4idea/tests/git4idea/roots/GitIntegrationEnablerTest.java
@@ -63,7 +63,7 @@
   public void oneRootForTheWholeProjectThenJustAddVcsrRoot() {
     Map<String, List<String>> map = new HashMap<String, List<String>>();
     map.put("git_init", Collections.<String>emptyList());
-    doTest(given(Arrays.asList("."), true, false),
+    doTest(given(Arrays.asList("."), false),
            map, null);
   }
 
@@ -74,7 +74,7 @@
     map.put("vcs_roots", VcsTestUtil.toAbsolute(Arrays.asList("."), myProject));
 
 
-    doTest(given(Collections.<String>emptyList(), false, false),
+    doTest(given(Collections.<String>emptyList(), false),
            map, notification("Created Git repository in " + myProjectRoot));
   }
 
@@ -83,7 +83,7 @@
     Map<String, List<String>> map = new HashMap<String, List<String>>();
     map.put("git_init", Collections.<String>emptyList());
 
-    doTest(given(Arrays.asList(".."), true, true),
+    doTest(given(Arrays.asList(".."), true),
            map, notification("Added Git root: " + myTestRoot));
   }
 
@@ -92,7 +92,7 @@
     Map<String, List<String>> map = new HashMap<String, List<String>>();
     map.put("git_init", Collections.<String>emptyList());
 
-    doTest(given(Arrays.asList(".", "community"), true, false),
+    doTest(given(Arrays.asList(".", "community"), false),
            map, notification("Added Git roots: " + myProjectRoot + ", " + getPresentationForRoot("community")));
   }
 
@@ -101,7 +101,7 @@
     Map<String, List<String>> map = new HashMap<String, List<String>>();
     map.put("git_init", Collections.<String>emptyList());
 
-    doTest(given(Arrays.asList("..", "community"), true, true),
+    doTest(given(Arrays.asList("..", "community"), true),
            map, notification("Added Git roots: " + myTestRoot + ", " + getPresentationForRoot("community")));
   }
 
@@ -110,7 +110,7 @@
     Map<String, List<String>> map = new HashMap<String, List<String>>();
     map.put("git_init", Collections.<String>emptyList());
 
-    doTest(given(Arrays.asList("community", "contrib"), false, false),
+    doTest(given(Arrays.asList("community", "contrib"), false),
            map, notification(
       "Added Git roots: " + getPresentationForRoot("community") + ", " + getPresentationForRoot("contrib")));
   }
@@ -148,14 +148,14 @@
     VcsTestUtil.assertEqualCollections(expectedVcsRoots, getPaths(actualRoots));
   }
 
-  VcsRootDetectInfo given(@NotNull Collection<String> roots, boolean full, boolean below) {
+  VcsRootDetectInfo given(@NotNull Collection<String> roots, boolean below) {
     return new VcsRootDetectInfo(ContainerUtil.map(roots, new Function<String, VcsRoot>() {
 
       @Override
       public VcsRoot fun(String s) {
         return new VcsRoot(myVcs, new MockVirtualFile(VcsTestUtil.toAbsolute(s, myProject)));
       }
-    }), full, below);
+    }), below);
   }
 
   Notification notification(String content) {
diff --git a/plugins/gradle/resources/i18n/GradleBundle.properties b/plugins/gradle/resources/i18n/GradleBundle.properties
index 1447b37..254b5a9 100644
--- a/plugins/gradle/resources/i18n/GradleBundle.properties
+++ b/plugins/gradle/resources/i18n/GradleBundle.properties
@@ -23,6 +23,9 @@
   It will provide IDE with Gradle API/DSL documentation.
 gradle.notifications.hide.tip=Hide the tip
 gradle.notifications.apply.suggestion=Ok, apply suggestion!
+gradle.notifications.unlinked.project.found.title=Unlinked Gradle project?
+gradle.notifications.unlinked.project.found.msg=<a href="{0}">Import Gradle project</a>, this will also enable Gradle Tool Window.
+gradle.notifications.do.not.show=Don't want to see the message for the project again: <a href="{0}">press here</a>.
 
 gradle.codeInsight.action.apply_plugin.text=Add gradle plugin
 gradle.codeInsight.action.apply_plugin.description=Add selected gradle plugin to the project
diff --git a/plugins/gradle/resources/i18n/GradleDocumentationBundle.properties b/plugins/gradle/resources/i18n/GradleDocumentationBundle.properties
index 1c18540..c04882a 100644
--- a/plugins/gradle/resources/i18n/GradleDocumentationBundle.properties
+++ b/plugins/gradle/resources/i18n/GradleDocumentationBundle.properties
@@ -1,88 +1,137 @@
 ## Language plugins
+gradle.documentation.org.gradle.api.Project.apply.plugin.java.non-html=\
+  Adds Java compilation, testing and bundling capabilities to a project.\
+   It serves as the basis for many of the other Gradle plugins.
 gradle.documentation.org.gradle.api.Project.apply.plugin.java=\
   <p>Adds Java compilation, testing and bundling capabilities to a project.\
    It serves as the basis for many of the other Gradle plugins. \
   See also <a class="xref" href="http://www.gradle.org/docs/current/userguide/tutorial_java_projects.html">Chapter 7, <i>Java Quickstart</i></a>.\
   </p>\
   <p>Automatically applies: java-base</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.groovy.non-html=\
+  Adds support for building Groovy projects.
 gradle.documentation.org.gradle.api.Project.apply.plugin.groovy=\
   <p>Adds support for building Groovy projects. \
   See also <a class="xref" href="http://www.gradle.org/docs/current/userguide/tutorial_groovy_projects.html">Chapter 9, <i>Groovy Quickstart</i></a>.</p>\
   <p>Automatically applies: java, groovy-base</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.scala.non-html=\
+  Adds support for building Scala projects.
 gradle.documentation.org.gradle.api.Project.apply.plugin.scala=\
   <p>Adds support for building Scala projects.</p>\
   <p>Automatically applies: java, scala-base</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.antlr.non-html=\
+  Adds support for generating parsers using Antlr
 gradle.documentation.org.gradle.api.Project.apply.plugin.antlr=\
   <p>Adds support for generating parsers using <a class="ulink" href="http://www.antlr.org/" target="_top">Antlr</a>.</p>\
   <p>Automatically applies: java</p>
 
 ## Integration plugins
+gradle.documentation.org.gradle.api.Project.apply.plugin.application.non-html=\
+  Adds tasks for running and bundling a Java project as a command-line application.
 gradle.documentation.org.gradle.api.Project.apply.plugin.application=\
   <p>Adds tasks for running and bundling a Java project as a command-line application.</p>\
   <p>Automatically applies: java</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.ear.non-html=\
+  Adds support for building J2EE applications.
 gradle.documentation.org.gradle.api.Project.apply.plugin.ear=\
   <p>Adds support for building J2EE applications.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.jetty.non-html=\
+  Deploys your web application to a Jetty web container embedded in the build.
 gradle.documentation.org.gradle.api.Project.apply.plugin.jetty=\
   <p>Deploys your web application to a Jetty web container embedded in the build. \
   See also <a class="xref" href="http://www.gradle.org/docs/current/userguide/web_project_tutorial.html">Chapter 10, <i>Web Application Quickstart</i></a>.</p>\
   <p>Automatically applies: war</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.maven.non-html=\
+  Adds support for publishing artifacts to Maven repositories.
 gradle.documentation.org.gradle.api.Project.apply.plugin.maven=\
   <p>Adds support for publishing artifacts to Maven repositories.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.osgi.non-html=\
+  Adds support for building OSGi bundles.
 gradle.documentation.org.gradle.api.Project.apply.plugin.osgi=\
   <p>Adds support for building OSGi bundles.</p>\
   <p>Automatically applies: java-base</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.war.non-html=\
+  Adds support for assembling web application WAR files.
 gradle.documentation.org.gradle.api.Project.apply.plugin.war=\
   <p>Adds support for assembling web application WAR files. \
   See also <a class="xref" href="http://www.gradle.org/docs/current/userguide/web_project_tutorial.html">Chapter 10, <i>Web Application Quickstart</i></a>.</p>\
   <p>Automatically applies: java</p>
 
 ## Software development plugins
+gradle.documentation.org.gradle.api.Project.apply.plugin.announce.non-html=\
+  Publish messages to your favourite platforms, such as Twitter or Growl.
 gradle.documentation.org.gradle.api.Project.apply.plugin.announce=\
   <p>Publish messages to your favourite platforms, such as Twitter or Growl.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.build-announcements.non-html=\
+  Sends local announcements to your desktop about interesting events in the build lifecycle.
 gradle.documentation.org.gradle.api.Project.apply.plugin.build-announcements=\
   <p>Sends local announcements to your desktop about interesting events in the build lifecycle.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.checkstyle.non-html=\
+  Performs quality checks on your project's Java source files using Checkstyle and generates reports from these checks.
 gradle.documentation.org.gradle.api.Project.apply.plugin.checkstyle=\
   <p>Performs quality checks on your project's Java source files using \
       <a class="ulink" href="http://checkstyle.sourceforge.net/index.html" target="_top">Checkstyle</a> \
       and generates reports from these checks.\
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.codenarc.non-html=\
+  Performs quality checks on your project's Groovy source files using CodeNarc and generates reports from these checks.
 gradle.documentation.org.gradle.api.Project.apply.plugin.codenarc=\
   <p>Performs quality checks on your project's Groovy source files using \
       <a class="ulink" href="http://codenarc.sourceforge.net/index.html" target="_top">CodeNarc</a> \
       and generates reports from these checks.\
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.eclipse.non-html=\
+  Generates files that are used by Eclipse IDE, thus making \
+      it possible to import the project into Eclipse.
 gradle.documentation.org.gradle.api.Project.apply.plugin.eclipse=\
   <p>Generates files that are used by <a class="ulink" href="http://eclipse.org" target="_top">Eclipse IDE</a>, thus making \
       it possible to import the project into Eclipse. \
   See also <a class="xref" href="http://www.gradle.org/docs/current/userguide/tutorial_java_projects.html">Chapter 7, <i>Java Quickstart</i></a>.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.eclipse-wtp.non-html=\
+  Does the same as the eclipse plugin plus generates eclipse WTP (Web Tools Platform) configuration files. \
+  After importing to eclipse your war/ear projects should be configured to work with WTP.
 gradle.documentation.org.gradle.api.Project.apply.plugin.eclipse-wtp=\
   <p>Does the same as the eclipse plugin plus generates eclipse WTP (Web Tools Platform) configuration files. \
       After importing to eclipse your war/ear projects should be configured to work with WTP.\
       See also <a class="xref" href="http://www.gradle.org/docs/current/userguide/tutorial_java_projects.html">Chapter 7, <i>Java Quickstart</i></a>. \
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.findbugs.non-html=\
+  Performs quality checks on your project's Java source files using FindBugs and generates reports from these checks.
 gradle.documentation.org.gradle.api.Project.apply.plugin.findbugs=\
   <p>Performs quality checks on your project's Java source files using \
       <a class="ulink" href="http://findbugs.sourceforge.net" target="_top">FindBugs</a> \
       and generates reports from these checks.\
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.idea.non-html=\
+  Generates files and applies IDEA specific customizations that are used by Intellij IDEA IDE thus making it possible to import the project into IDEA.
 gradle.documentation.org.gradle.api.Project.apply.plugin.idea=\
-  <p>Generates files that are used by <a class="ulink" href="http://www.jetbrains.com/idea/index.html" target="_top">Intellij IDEA IDE</a>, \
+  <p>Generates files and applies IDEA specific customizations that are used by <a class="ulink" href="http://www.jetbrains.com/idea/index.html" target="_top">Intellij IDEA IDE</a>, \
       thus making it possible to import the project into IDEA.\
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.jdepend.non-html=\
+  Performs quality checks on your project's source files using JDepend and generates reports from these checks.
 gradle.documentation.org.gradle.api.Project.apply.plugin.jdepend=\
   <p>Performs quality checks on your project's source files using \
       <a class="ulink" href="http://clarkware.com/software/JDepend.html" target="_top">JDepend</a> \
       and generates reports from these checks.\
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.pmd.non-html=\
+  Performs quality checks on your project's Java source files using PMD and generates reports from these checks.
 gradle.documentation.org.gradle.api.Project.apply.plugin.pmd=\
   <p>Performs quality checks on your project's Java source files using \
       <a class="ulink" href="http://pmd.sourceforge.net" target="_top">PMD</a> \
       and generates reports from these checks.\
   </p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.project-report.non-html=\
+  Generates reports containing useful information about your Gradle build.
 gradle.documentation.org.gradle.api.Project.apply.plugin.project-report=\
   <p>Generates reports containing useful information about your Gradle build.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.signing.non-html=\
+  Adds the ability to digitally sign built files and artifacts.
 gradle.documentation.org.gradle.api.Project.apply.plugin.signing=\
   <p>Adds the ability to digitally sign built files and artifacts.</p>
+gradle.documentation.org.gradle.api.Project.apply.plugin.sonar.non-html=\
+  Provides integration with the Sonar  code quality platform. Superceeded by the sonar-runner plugin.
 gradle.documentation.org.gradle.api.Project.apply.plugin.sonar=\
   <p>Provides integration with the \
     <a class="ulink" href="http://www.sonarsource.org" target="_top">Sonar</a> \
diff --git a/plugins/gradle/resources/inspectionDescriptions/MultipleRepositoryUrls.html b/plugins/gradle/resources/inspectionDescriptions/MultipleRepositoryUrls.html
new file mode 100644
index 0000000..f8c19bf
--- /dev/null
+++ b/plugins/gradle/resources/inspectionDescriptions/MultipleRepositoryUrls.html
@@ -0,0 +1,6 @@
+<html>
+<body>
+This inspection reports usage of multiple urls per repository(maven or ivy) block.
+The problem is that no more than one url will be picked up for the repo and others will be ignored.
+</body>
+</html>
\ No newline at end of file
diff --git a/plugins/gradle/src/META-INF/plugin.xml b/plugins/gradle/src/META-INF/plugin.xml
index 653c626..fc7d254 100644
--- a/plugins/gradle/src/META-INF/plugin.xml
+++ b/plugins/gradle/src/META-INF/plugin.xml
@@ -46,8 +46,11 @@
     <resolve.contributor implementation="org.jetbrains.plugins.gradle.service.resolve.GradleImplicitContributor"/>
     <projectResolve implementation="org.jetbrains.plugins.gradle.service.project.BaseGradleProjectResolverExtension"/>
   </extensions>
-  
+
   <extensions defaultExtensionNs="com.intellij">
+
+    <postStartupActivity implementation="org.jetbrains.plugins.gradle.service.project.GradleStartupActivity"/>
+
     <errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
     <projectImportProvider implementation="org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportProvider"/>
     <projectImportBuilder implementation="org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportBuilder"/>
@@ -69,6 +72,7 @@
 
     <projectService serviceImplementation="org.jetbrains.plugins.gradle.settings.GradleSettings"/>
     <projectService serviceImplementation="org.jetbrains.plugins.gradle.settings.GradleLocalSettings"/>
+    <projectService serviceImplementation="org.jetbrains.plugins.gradle.service.project.GradleNotification"/>
 
     <configurationProducer implementation="org.jetbrains.plugins.gradle.service.execution.GradleRuntimeConfigurationProducer"/>
 
@@ -80,6 +84,11 @@
     <editorNotificationProvider implementation="org.jetbrains.plugins.gradle.codeInsight.UseDistributionWithSourcesNotificationProvider"/>
     <annotator language="Groovy" implementationClass="org.jetbrains.plugins.gradle.service.resolve.dsl.GradleDslAnnotator"/>
 
+    <localInspection language="Groovy" groupPath="Gradle" shortName="MultipleRepositoryUrls"
+                     bundle="org.jetbrains.plugins.gradle.codeInspection.GradleInspectionBundle"
+                     key="multiple.repository.urls" groupName="Probable bugs" enabledByDefault="true" level="WARNING"
+                     implementationClass="org.jetbrains.plugins.gradle.codeInspection.MultipleRepositoryUrlsInspection"/>
+
   </extensions>
 
   <extensions defaultExtensionNs="org.intellij.groovy">
diff --git a/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService b/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService
index a07e354..3989c7c 100644
--- a/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService
+++ b/plugins/gradle/src/META-INF/services/org.jetbrains.plugins.gradle.model.ModelBuilderService
@@ -13,6 +13,6 @@
 # See the License for the specific language governing permissions and
 # limitations under the License.
 #
-org.jetbrains.plugins.gradle.model.impl.WarModelBuilderImpl
-org.jetbrains.plugins.gradle.model.impl.ModelDependenciesBuilderImpl
-org.jetbrains.plugins.gradle.model.impl.ModuleExtendedModelBuilderImpl
+org.jetbrains.plugins.gradle.model.builder.WarModelBuilderImpl
+org.jetbrains.plugins.gradle.model.builder.ModelDependenciesBuilderImpl
+org.jetbrains.plugins.gradle.model.builder.ModuleExtendedModelBuilderImpl
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
index d109ded..c888569 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/GradleManager.java
@@ -263,9 +263,20 @@
     // We want to automatically refresh linked projects on gradle service directory change.
     MessageBusConnection connection = project.getMessageBus().connect(project);
     connection.subscribe(GradleSettings.getInstance(project).getChangesTopic(), new GradleSettingsListenerAdapter() {
+
       @Override
       public void onServiceDirectoryPathChange(@Nullable String oldPath, @Nullable String newPath) {
-        ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, true);
+        ensureProjectsRefresh();
+      }
+
+      @Override
+      public void onGradleHomeChange(@Nullable String oldPath, @Nullable String newPath, @NotNull String linkedProjectPath) {
+        ensureProjectsRefresh();
+      }
+
+      @Override
+      public void onGradleDistributionTypeChange(DistributionType currentValue, @NotNull String linkedProjectPath) {
+        ensureProjectsRefresh();
       }
 
       @Override
@@ -299,6 +310,10 @@
             }, false, ProgressExecutionMode.MODAL_SYNC);
         }
       }
+
+      private void ensureProjectsRefresh() {
+        ExternalSystemUtil.refreshProjects(project, GradleConstants.SYSTEM_ID, true);
+      }
     });
 
     // We used to assume that gradle scripts are always named 'build.gradle' and kept path to that build.gradle file at ide settings.
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java
index 6c56652..dc1ce17 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInsight/actions/AddGradleDslPluginAction.java
@@ -83,8 +83,8 @@
 
   @NotNull
   private static KeyValue<String, String> createPluginKey(@NotNull String pluginName) {
-    String description =
-      GradleDocumentationBundle.messageOrDefault("gradle.documentation.org.gradle.api.Project.apply.plugin." + pluginName, "");
+    String description = GradleDocumentationBundle.messageOrDefault(
+      String.format("gradle.documentation.org.gradle.api.Project.apply.plugin.%s.non-html", pluginName), "");
     return KeyValue.create(pluginName, description);
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java
similarity index 63%
copy from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
copy to plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java
index fec7c97..91e6756 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleBaseInspection.java
@@ -13,22 +13,19 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model.impl;
+package org.jetbrains.plugins.gradle.codeInspection;
 
-import org.gradle.tooling.model.Dependency;
-
-import java.io.Serializable;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.codeInspection.BaseInspection;
 
 /**
  * @author Vladislav.Soroka
- * @since 11/8/13
+ * @since 11/21/13
  */
-public interface GradleDependency extends Dependency, Serializable {
-  String getConfigurationName();
-
-  String getDependencyName();
-
-  String getDependencyGroup();
-
-  String getDependencyVersion();
+public abstract class GradleBaseInspection extends BaseInspection {
+  @NotNull
+  @Override
+  public String[] getGroupPath() {
+    return new String[]{"Gradle", getGroupDisplayName()};
+  }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.properties b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.properties
index e2ef587..0f2bed4 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.properties
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/GradleInspectionBundle.properties
@@ -17,4 +17,5 @@
 #
 ########################################################################################################################
 group.other=Other
-
+multiple.repository.urls=Multiple repository urls
+multiple.repository.urls.fix.name=Replace multiple repository urls with separate repository blocks
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java
new file mode 100644
index 0000000..99ec0b4
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsFix.java
@@ -0,0 +1,75 @@
+/*
+ * 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.codeInspection;
+
+import com.intellij.codeInspection.ProblemDescriptor;
+import com.intellij.openapi.project.Project;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.util.IncorrectOperationException;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.codeInspection.GroovyFix;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression;
+import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/21/13
+ */
+public class MultipleRepositoryUrlsFix extends GroovyFix {
+  private final GrClosableBlock myClosure;
+  private final String myRepoType;
+
+  public MultipleRepositoryUrlsFix(@NotNull GrClosableBlock closure, @NotNull String repoType) {
+    myClosure = closure;
+    myRepoType = repoType;
+  }
+
+  @Override
+  protected void doFix(Project project, ProblemDescriptor descriptor) throws IncorrectOperationException {
+    List<GrCallExpression> statements = MultipleRepositoryUrlsInspection.findUrlCallExpressions(myClosure);
+    if (statements.size() <= 1) return;
+    statements.remove(0);
+
+    List<PsiElement> elements = new ArrayList<PsiElement>(statements);
+    for (GrCallExpression statement : statements) {
+      PsiElement newLineCandidate = statement.getNextSibling();
+      if (PsiUtil.isNewLine(newLineCandidate)) {
+        elements.add(newLineCandidate);
+      }
+    }
+
+    myClosure.removeElements(elements.toArray(new PsiElement[elements.size()]));
+    GrClosableBlock closableBlock = PsiTreeUtil.getParentOfType(myClosure, GrClosableBlock.class);
+    if (closableBlock == null) return;
+
+    GroovyPsiElementFactory elementFactory = GroovyPsiElementFactory.getInstance(project);
+    for (GrCallExpression statement : statements) {
+      closableBlock.addStatementBefore(elementFactory.createStatementFromText(myRepoType + '{' + statement.getText() + '}'), null);
+    }
+  }
+
+  @NotNull
+  @Override
+  public String getName() {
+    return GradleInspectionBundle.message("multiple.repository.urls.fix.name");
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java
new file mode 100644
index 0000000..359d043
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/codeInspection/MultipleRepositoryUrlsInspection.java
@@ -0,0 +1,119 @@
+/*
+ * 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.codeInspection;
+
+import com.intellij.codeInspection.LocalQuickFix;
+import com.intellij.codeInspection.ProblemHighlightType;
+import com.intellij.openapi.util.io.FileUtilRt;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.util.ArrayUtil;
+import com.intellij.util.containers.ContainerUtil;
+import org.jetbrains.annotations.Nls;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+import org.jetbrains.plugins.groovy.codeInspection.BaseInspectionVisitor;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrCallExpression;
+
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/21/13
+ */
+public class MultipleRepositoryUrlsInspection extends GradleBaseInspection {
+
+  @NotNull
+  @Override
+  protected BaseInspectionVisitor buildVisitor() {
+    return new MyVisitor();
+  }
+
+  @Nls
+  @NotNull
+  @Override
+  public String getGroupDisplayName() {
+    return PROBABLE_BUGS;
+  }
+
+
+  @Override
+  protected String buildErrorString(Object... args) {
+    return GradleInspectionBundle.message("multiple.repository.urls", args);
+  }
+
+  @Nls
+  @NotNull
+  @Override
+  public String getDisplayName() {
+    return GradleInspectionBundle.message("multiple.repository.urls");
+  }
+
+  private static class MyVisitor extends BaseInspectionVisitor {
+    @Override
+    public void visitClosure(GrClosableBlock closure) {
+      PsiFile file = closure.getContainingFile();
+      if (file == null || !FileUtilRt.extensionEquals(file.getName(), GradleConstants.EXTENSION)) return;
+
+      super.visitClosure(closure);
+      GrMethodCall mavenMethodCall = PsiTreeUtil.getParentOfType(closure, GrMethodCall.class);
+      if (mavenMethodCall == null) return;
+      GrExpression mavenMethodExpression = mavenMethodCall.getInvokedExpression();
+      if (mavenMethodExpression == null ||
+          !ArrayUtil.contains(mavenMethodExpression.getText(), "maven", "ivy")) {
+        return;
+      }
+
+      GrMethodCall repositoryMethodCall = PsiTreeUtil.getParentOfType(mavenMethodCall, GrMethodCall.class);
+      if (repositoryMethodCall == null) return;
+      GrExpression repositoryMethodExpression = repositoryMethodCall.getInvokedExpression();
+      if (repositoryMethodExpression == null || !repositoryMethodExpression.getText().equals("repositories")) return;
+
+      List<GrCallExpression> statements = findUrlCallExpressions(closure);
+      if (statements.size() > 1) {
+        registerError(closure);
+
+        registerError(closure, GradleInspectionBundle.message("multiple.repository.urls"),
+                      new LocalQuickFix[]{new MultipleRepositoryUrlsFix(closure, mavenMethodExpression.getText())},
+                      ProblemHighlightType.GENERIC_ERROR);
+      }
+    }
+  }
+
+  @NotNull
+  static List<GrCallExpression> findUrlCallExpressions(@NotNull GrClosableBlock closure) {
+    GrCallExpression[] applicationStatements = PsiTreeUtil.getChildrenOfType(closure, GrCallExpression.class);
+    if (applicationStatements == null) return Collections.emptyList();
+
+    List<GrCallExpression> statements = ContainerUtil.newArrayList();
+    for (GrCallExpression statement : applicationStatements) {
+      GrReferenceExpression[] referenceExpressions = PsiTreeUtil.getChildrenOfType(statement, GrReferenceExpression.class);
+      if (referenceExpressions == null) continue;
+      for (GrReferenceExpression expression : referenceExpressions) {
+        String expressionText = expression.getText();
+        if ("url".equals(expressionText) || "setUrl".equals(expressionText)) {
+          statements.add(statement);
+        }
+      }
+    }
+    return statements;
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java
index 0319145..f34748e 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/integrations/maven/ImportMavenRepositoriesTask.java
@@ -72,6 +72,8 @@
 
   @Override
   public void run() {
+    if(myProject.isDisposed()) return;
+
     final LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
     final List<PsiFile> psiFileList = ContainerUtil.newArrayList();
 
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java
new file mode 100644
index 0000000..7186312
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/GradleDependencyScope.java
@@ -0,0 +1,140 @@
+/*
+ * 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 {
+  // Implicit scopes
+  PROVIDED("provided", "provided", true, true, true, true),
+  OPTIONAL("optional", "compile", true, true, true, true),
+
+
+  // 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),
+
+  // Groovy Plugin Scopes
+  /**
+   * Compiles production Groovy source files.
+   */
+  COMPILE_GROOVY("compileGroovy", "compile", true, true, true, true),
+  /**
+   * Compiles test Groovy source files.
+   */
+  COMPILE_TEST_GROOVY("compileTestGroovy", "test", false, false, true, true),
+
+  // Scala Plugin Scopes
+  /**
+   * Compiles production Scala source files.
+   */
+  COMPILE_SCALA("compileScala", "compile", true, true, true, true),
+  /**
+   * Compiles test Scala source files.
+   */
+  COMPILE_TEST_SCALA("compileTestScala", "test", false, false, true, 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.toLowerCase())) return scope;
+    }
+    return null;
+  }
+
+  public String getIdeaMappingName() {
+    return myIdeaMappingName;
+  }
+
+  @Override
+  public String toString() {
+    return myGradleName;
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java
index 584d9cf..45828b4 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/ProjectDependenciesModel.java
@@ -15,8 +15,7 @@
  */
 package org.jetbrains.plugins.gradle.model;
 
-import org.jetbrains.plugins.gradle.model.impl.GradleDependency;
-import org.jetbrains.plugins.gradle.model.impl.GradleDependencyImpl;
+import org.gradle.tooling.model.idea.IdeaDependency;
 
 import java.io.Serializable;
 import java.util.List;
@@ -29,5 +28,5 @@
 
   String getProjectName();
 
-  List<GradleDependency> getDependencies();
+  List<IdeaDependency> getDependencies();
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImpl.java
new file mode 100644
index 0000000..0586482
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImpl.java
@@ -0,0 +1,308 @@
+/*
+ * 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.builder;
+
+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.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.ModelBuilderService;
+import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
+import org.jetbrains.plugins.gradle.model.internal.*;
+
+import java.io.File;
+import java.io.Serializable;
+import java.util.*;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/5/13
+ */
+public class ModelDependenciesBuilderImpl implements ModelBuilderService {
+
+  private static final String MODULE_PROPERTY = "ideaModule";
+  private static final String VERSION_PROPERTY = "version";
+  private static final String GROUP_PROPERTY = "group";
+
+  @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<DependencyVersionId, Scopes> scopesMap = new HashMap<DependencyVersionId, 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) {
+        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) {
+          merge(scopesMap, repoFileDependency, userScopes);
+        }
+      }
+
+      final List<IdeDependenciesExtractor.IdeLocalFileDependency> ideLocalFileDependencies =
+        dependenciesExtractor.extractLocalFileDependencies(plusConfigurations, new ArrayList<Configuration>());
+      for (IdeDependenciesExtractor.IdeLocalFileDependency fileDependency : ideLocalFileDependencies) {
+        merge(scopesMap, fileDependency, userScopes);
+      }
+    }
+
+    for (Map.Entry<DependencyVersionId, Scopes> entry : scopesMap.entrySet()) {
+      DependencyVersionId 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 = 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());
+          dependencies.add(libraryDependency);
+        }
+      }
+    }
+
+    return new ProjectDependenciesModelImpl(project.getPath(), dependencies);
+  }
+
+  @Nullable
+  private 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;
+  }
+
+  private static void merge(Map<DependencyVersionId, 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)) : "";
+
+    DependencyVersionId versionId =
+      new DependencyVersionId(dependency, project.getName(), group, version, null);
+    Scopes scopes = map.get(versionId);
+    if (scopes == null) {
+      map.put(versionId, new Scopes(scope));
+    }
+    else {
+      scopes.add(scope);
+    }
+  }
+
+  private static String str(Object o) {
+    return String.valueOf(o == null ? "" : o);
+  }
+
+  private static void merge(Map<DependencyVersionId, 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());
+    DependencyVersionId versionId =
+      new DependencyVersionId(dependency, dependencyId.getName(), dependencyId.getGroup(), dependencyId.getVersion(), classifier);
+    Scopes scopes = map.get(versionId);
+    if (scopes == null) {
+      map.put(versionId, new Scopes(scope));
+    }
+    else {
+      scopes.add(scope);
+    }
+  }
+
+  private 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;
+  }
+
+  private static void merge(Map<DependencyVersionId, 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();
+    DependencyVersionId versionId =
+      new DependencyVersionId(dependency, path, "", "", 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
+   */
+  private static GradleDependencyScope deduceScope(String configurationName,
+                                                   Map<String, Map<String, Collection<Configuration>>> userScopes) {
+    GradleDependencyScope scope = GradleDependencyScope.fromName(configurationName);
+    if (scope == null) {
+      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());
+          }
+        }
+      }
+    }
+
+    return scope;
+  }
+
+  private 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/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModuleExtendedModelBuilderImpl.java
similarity index 97%
rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelBuilderImpl.java
rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModuleExtendedModelBuilderImpl.java
index 59ed769..3dc8540 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelBuilderImpl.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/ModuleExtendedModelBuilderImpl.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.impl;
+package org.jetbrains.plugins.gradle.model.builder;
 
 import org.gradle.api.Project;
 import org.gradle.api.Task;
@@ -29,6 +29,7 @@
 import org.jetbrains.plugins.gradle.model.ModuleExtendedModel;
 import org.jetbrains.plugins.gradle.model.internal.IdeaContentRootImpl;
 import org.jetbrains.plugins.gradle.model.internal.IdeaSourceDirectoryImpl;
+import org.jetbrains.plugins.gradle.model.internal.ModuleExtendedModelImpl;
 
 import java.io.File;
 import java.io.IOException;
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImpl.java
similarity index 97%
rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelBuilderImpl.java
rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImpl.java
index 9964d0b..8a1d2a1 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelBuilderImpl.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImpl.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.impl;
+package org.jetbrains.plugins.gradle.model.builder;
 
 import org.gradle.api.Action;
 import org.gradle.api.Project;
@@ -27,6 +27,7 @@
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.gradle.model.ModelBuilderService;
 import org.jetbrains.plugins.gradle.model.WarModel;
+import org.jetbrains.plugins.gradle.model.internal.WarModelImpl;
 
 import java.io.File;
 import java.io.StringWriter;
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependencyImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependencyImpl.java
deleted file mode 100644
index 9a113ea..0000000
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependencyImpl.java
+++ /dev/null
@@ -1,86 +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.impl;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/8/13
- */
-public class GradleDependencyImpl implements GradleDependency {
-  private final String configurationName;
-  private final String dependencyName;
-  private final String dependencyGroup;
-  private final String dependencyVersion;
-
-  public GradleDependencyImpl(String configurationName, String dependencyName, String dependencyGroup, String dependencyVersion) {
-    this.configurationName = configurationName;
-    this.dependencyName = dependencyName;
-    this.dependencyGroup = dependencyGroup;
-    this.dependencyVersion = dependencyVersion;
-  }
-
-  @Override
-  public String getConfigurationName() {
-    return configurationName;
-  }
-
-  @Override
-  public String getDependencyName() {
-    return dependencyName;
-  }
-
-  @Override
-  public String getDependencyGroup() {
-    return dependencyGroup;
-  }
-
-  @Override
-  public String getDependencyVersion() {
-    return dependencyVersion;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) return true;
-    if (o == null || getClass() != o.getClass()) return false;
-
-    GradleDependencyImpl that = (GradleDependencyImpl)o;
-
-    if (dependencyGroup != null ? !dependencyGroup.equals(that.dependencyGroup) : that.dependencyGroup != null) return false;
-    if (dependencyName != null ? !dependencyName.equals(that.dependencyName) : that.dependencyName != null) return false;
-    if (dependencyVersion != null ? !dependencyVersion.equals(that.dependencyVersion) : that.dependencyVersion != null) return false;
-
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    int result = dependencyName != null ? dependencyName.hashCode() : 0;
-    result = 31 * result + (dependencyGroup != null ? dependencyGroup.hashCode() : 0);
-    result = 31 * result + (dependencyVersion != null ? dependencyVersion.hashCode() : 0);
-    return result;
-  }
-
-  @Override
-  public String toString() {
-    return "GradleDependencyImpl{" +
-           "configurationName='" + configurationName + '\'' +
-           ", dependencyName='" + dependencyName + '\'' +
-           ", dependencyGroup='" + dependencyGroup + '\'' +
-           ", dependencyVersion='" + dependencyVersion + '\'' +
-           '}';
-  }
-}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModelDependenciesBuilderImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModelDependenciesBuilderImpl.java
deleted file mode 100644
index 6f151bd..0000000
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModelDependenciesBuilderImpl.java
+++ /dev/null
@@ -1,108 +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.impl;
-
-import org.gradle.api.Project;
-import org.gradle.api.artifacts.*;
-import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.gradle.model.ModelBuilderService;
-import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
-
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Set;
-
-/**
- * @author Vladislav.Soroka
- * @since 11/5/13
- */
-public class ModelDependenciesBuilderImpl implements ModelBuilderService {
-
-  @Override
-  public boolean canBuild(String modelName) {
-    return ProjectDependenciesModel.class.getName().equals(modelName);
-  }
-
-  @Nullable
-  @Override
-  public Object buildAll(String modelName, Project project) {
-    List<GradleDependency> dependencies = new ArrayList<GradleDependency>();
-
-    for (Configuration configuration : project.getConfigurations()) {
-      for (Dependency dependency : configuration.getDependencies()) {
-        if (dependency instanceof ClientModule) {
-          ClientModule clientModule = (ClientModule)dependency;
-          for (ModuleDependency moduleDependency : clientModule.getDependencies()) {
-            dependencies.add(
-              new GradleDependencyImpl(
-                configuration.getName(),
-                moduleDependency.getName(),
-                moduleDependency.getGroup(),
-                moduleDependency.getVersion()
-              ));
-            ResolvedDependency resolvedDependency =
-              findResolvedDependency(moduleDependency, configuration.getResolvedConfiguration().getFirstLevelModuleDependencies());
-            if (resolvedDependency != null) {
-              addTransitiveDependencies(dependencies, configuration.getName(), resolvedDependency.getChildren());
-            }
-          }
-        }
-        dependencies.add(
-          new GradleDependencyImpl(
-            configuration.getName(),
-            dependency.getName(),
-            dependency.getGroup(),
-            dependency.getVersion()
-          ));
-      }
-    }
-    return new ProjectDependenciesModelImpl(project.getPath(), dependencies);
-  }
-
-  private static void addTransitiveDependencies(List<GradleDependency> dependencies,
-                                                String configurationName,
-                                                Set<ResolvedDependency> resolvedDependencies) {
-    if (resolvedDependencies == null) return;
-    for (ResolvedDependency resolvedDependency : resolvedDependencies) {
-      dependencies.add(
-        new GradleDependencyImpl(
-          configurationName,
-          resolvedDependency.getModuleName(),
-          resolvedDependency.getModuleGroup(),
-          resolvedDependency.getModuleVersion()
-        ));
-      addTransitiveDependencies(dependencies, configurationName, resolvedDependency.getChildren());
-    }
-  }
-
-  private static ResolvedDependency findResolvedDependency(ModuleDependency moduleDependency,
-                                                           Set<ResolvedDependency> resolvedDependencies) {
-    for (ResolvedDependency resolvedDependency : resolvedDependencies) {
-      ResolvedDependency dependency = findResolvedDependency(moduleDependency, resolvedDependency.getChildren());
-      if (dependency != null) return dependency;
-      if (isEqual(resolvedDependency.getModuleName(), moduleDependency.getName()) &&
-          isEqual(resolvedDependency.getModuleGroup(), moduleDependency.getGroup()) &&
-          isEqual(resolvedDependency.getModuleVersion(), moduleDependency.getVersion())) {
-        return resolvedDependency;
-      }
-    }
-    return null;
-  }
-
-  private static boolean isEqual(String str1, String str2) {
-    return str1 != null ? str1.equals(str2) : str2 == null;
-  }
-}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/AbstractGradleDependency.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/AbstractGradleDependency.java
new file mode 100644
index 0000000..948081a
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/AbstractGradleDependency.java
@@ -0,0 +1,105 @@
+/*
+ * 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.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/src/org/jetbrains/plugins/gradle/model/internal/DependencyVersionId.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/DependencyVersionId.java
new file mode 100644
index 0000000..e8658cf
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/DependencyVersionId.java
@@ -0,0 +1,96 @@
+/*
+ * 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.internal;
+
+import org.gradle.plugins.ide.internal.IdeDependenciesExtractor;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/25/13
+ */
+public class DependencyVersionId {
+  private final IdeDependenciesExtractor.IdeDependency myIdeDependency;
+  private final String myName;
+  private final String myGroup;
+  private final String myVersion;
+  private final String myClassifier;
+
+  public DependencyVersionId(IdeDependenciesExtractor.IdeDependency dependency,
+                             String name,
+                             String group,
+                             String version,
+                             String classifier) {
+    myIdeDependency = dependency;
+    myName = name;
+    myGroup = group;
+    myVersion = version;
+    myClassifier = classifier;
+  }
+
+  public String getName() {
+    return myName;
+  }
+
+  public String getGroup() {
+    return myGroup;
+  }
+
+  public String getVersion() {
+    return myVersion;
+  }
+
+  public String getClassifier() {
+    return myClassifier;
+  }
+
+  public IdeDependenciesExtractor.IdeDependency getIdeDependency() {
+    return myIdeDependency;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (!(o instanceof DependencyVersionId)) return false;
+
+    DependencyVersionId id = (DependencyVersionId)o;
+
+    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 (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 = myName != null ? myName.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{" +
+           "name='" + myName + '\'' +
+           ", group='" + myGroup + '\'' +
+           ", version='" + myVersion + '\'' +
+           ", classifier='" + myClassifier + '\'' +
+           '}';
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaDependencyScopeImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaDependencyScopeImpl.java
new file mode 100644
index 0000000..aa7f5af
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaDependencyScopeImpl.java
@@ -0,0 +1,61 @@
+/*
+ * 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.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/src/org/jetbrains/plugins/gradle/model/internal/IdeaModuleDependencyImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaModuleDependencyImpl.java
new file mode 100644
index 0000000..6890ebd
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaModuleDependencyImpl.java
@@ -0,0 +1,48 @@
+/*
+ * 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.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/src/org/jetbrains/plugins/gradle/model/internal/IdeaSingleEntryLibraryDependencyImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaSingleEntryLibraryDependencyImpl.java
new file mode 100644
index 0000000..7012a36
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/IdeaSingleEntryLibraryDependencyImpl.java
@@ -0,0 +1,75 @@
+/*
+ * 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.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/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ModuleExtendedModelImpl.java
similarity index 97%
rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelImpl.java
rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ModuleExtendedModelImpl.java
index d915e6a..b8bce40 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ModuleExtendedModelImpl.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ModuleExtendedModelImpl.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.impl;
+package org.jetbrains.plugins.gradle.model.internal;
 
 import org.gradle.tooling.model.DomainObjectSet;
 import org.gradle.tooling.model.internal.ImmutableDomainObjectSet;
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ProjectDependenciesModelImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ProjectDependenciesModelImpl.java
similarity index 79%
rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ProjectDependenciesModelImpl.java
rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ProjectDependenciesModelImpl.java
index 2285b22..533c350 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/ProjectDependenciesModelImpl.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/ProjectDependenciesModelImpl.java
@@ -13,8 +13,9 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model.impl;
+package org.jetbrains.plugins.gradle.model.internal;
 
+import org.gradle.tooling.model.idea.IdeaDependency;
 import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
 
 import java.util.List;
@@ -25,9 +26,9 @@
  */
 public class ProjectDependenciesModelImpl implements ProjectDependenciesModel {
   private final String projectName;
-  private final List<GradleDependency> myDependencies;
+  private final List<IdeaDependency> myDependencies;
 
-  public ProjectDependenciesModelImpl(String projectName, List<GradleDependency> dependencies) {
+  public ProjectDependenciesModelImpl(String projectName, List<IdeaDependency> dependencies) {
     this.projectName = projectName;
     myDependencies = dependencies;
   }
@@ -38,7 +39,7 @@
   }
 
   @Override
-  public List<GradleDependency> getDependencies() {
+  public List<IdeaDependency> getDependencies() {
     return myDependencies;
   }
 
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/Scopes.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/Scopes.java
new file mode 100644
index 0000000..cc0155e
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/Scopes.java
@@ -0,0 +1,84 @@
+/*
+ * 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.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 ||
+                   scope == GradleDependencyScope.PROVIDED;
+  }
+
+  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 ||
+                   scope == GradleDependencyScope.PROVIDED;
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/StubIdeaModule.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/StubIdeaModule.java
new file mode 100644
index 0000000..0e8d2bc
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/StubIdeaModule.java
@@ -0,0 +1,81 @@
+/*
+ * 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.internal;
+
+import org.gradle.tooling.model.DomainObjectSet;
+import org.gradle.tooling.model.GradleProject;
+import org.gradle.tooling.model.HierarchicalElement;
+import org.gradle.tooling.model.idea.*;
+
+import java.io.Serializable;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/25/13
+ */
+public class StubIdeaModule implements IdeaModule, Serializable {
+
+  private final String name;
+
+  public StubIdeaModule(String name) {
+    this.name = name;
+  }
+
+  @Override
+  public DomainObjectSet<? extends IdeaContentRoot> getContentRoots() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public GradleProject getGradleProject() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public IdeaProject getParent() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public DomainObjectSet<? extends HierarchicalElement> getChildren() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public IdeaProject getProject() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public IdeaCompilerOutput getCompilerOutput() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public DomainObjectSet<? extends IdeaDependency> getDependencies() {
+    throw new UnsupportedOperationException();
+  }
+
+  @Override
+  public String getName() {
+    return name;
+  }
+
+  @Override
+  public String getDescription() {
+    throw new UnsupportedOperationException();
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/WarModelImpl.java
similarity index 97%
rename from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java
rename to plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/WarModelImpl.java
index 56aa6d3..6ebe710 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/WarModelImpl.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/model/internal/WarModelImpl.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.impl;
+package org.jetbrains.plugins.gradle.model.internal;
 
 import org.jetbrains.plugins.gradle.model.WarModel;
 
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java
index fa6660b5..ae2dda0 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/remote/impl/GradleLibraryNamesMixer.java
@@ -87,13 +87,13 @@
   private static boolean doMixNames(@NotNull Collection<Wrapped> libraries, @NotNull Map<String, Wrapped> cache) {
     cache.clear();
     for (Wrapped current : libraries) {
-      Wrapped previous = cache.remove(current.library.getName());
+      Wrapped previous = cache.remove(current.library.getExternalName());
       if (previous == null) {
-        cache.put(current.library.getName(), current);
+        cache.put(current.library.getExternalName(), current);
       }
       else {
         mixNames(current, previous);
-        return current.library.getName().equals(previous.library.getName()); // Stop processing if it's not possible to generate
+        return current.library.getExternalName().equals(previous.library.getExternalName()); // Stop processing if it's not possible to generate
       }
     }
     return true;
@@ -143,17 +143,17 @@
       if (file1 == null) {
         wrapped1.nextFile();
       }
-      else if (!wrapped1.library.getName().startsWith(file1.getName())) {
-        wrapped1.library.setName(file1.getName() + NAME_SEPARATOR + wrapped1.library.getName());
+      else if (!wrapped1.library.getExternalName().startsWith(file1.getName())) {
+        wrapped1.library.setExternalName(file1.getName() + NAME_SEPARATOR + wrapped1.library.getExternalName());
       }
       if (file2 == null) {
         wrapped2.nextFile();
       }
-      else if (!wrapped2.library.getName().startsWith(file2.getName())) {
-        wrapped2.library.setName(file2.getName() + NAME_SEPARATOR + wrapped2.library.getName());
+      else if (!wrapped2.library.getExternalName().startsWith(file2.getName())) {
+        wrapped2.library.setExternalName(file2.getName() + NAME_SEPARATOR + wrapped2.library.getExternalName());
       }
 
-      if (wrapped1.library.getName().equals(wrapped2.library.getName())) {
+      if (wrapped1.library.getExternalName().equals(wrapped2.library.getExternalName())) {
         if (wrapped1AltText != null) {
           diversifyName(wrapped1AltText, wrapped1, file1);
           return;
@@ -175,7 +175,7 @@
 
   @SuppressWarnings("ConstantConditions")
   private static void diversifyName(@NotNull String changeText, @NotNull Wrapped wrapped, @Nullable File file) {
-    String name = wrapped.library.getName();
+    String name = wrapped.library.getExternalName();
     int i = file == null ? - 1 : name.indexOf(file.getName());
     final String newName;
     if (i >= 0) {
@@ -184,7 +184,7 @@
     else {
       newName = changeText + NAME_SEPARATOR + name;
     }
-    wrapped.library.setName(newName);
+    wrapped.library.setExternalName(newName);
   }
 
   /**
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 b1c444b..0a28fccd 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
@@ -26,6 +26,7 @@
 import com.intellij.openapi.externalSystem.model.project.*;
 import com.intellij.openapi.externalSystem.model.task.TaskData;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemDebugEnvironment;
 import com.intellij.openapi.externalSystem.util.Order;
 import com.intellij.openapi.module.EmptyModuleType;
 import com.intellij.openapi.module.JavaModuleType;
@@ -34,7 +35,6 @@
 import com.intellij.openapi.roots.DependencyScope;
 import com.intellij.openapi.util.KeyValue;
 import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.util.BooleanFunction;
 import com.intellij.util.PathUtil;
@@ -43,6 +43,7 @@
 import com.intellij.util.containers.ContainerUtilRt;
 import com.intellij.util.net.HttpConfigurable;
 import com.intellij.util.text.CharArrayUtil;
+import groovy.lang.GroovyObject;
 import org.gradle.tooling.ProjectConnection;
 import org.gradle.tooling.model.DomainObjectSet;
 import org.gradle.tooling.model.GradleTask;
@@ -53,7 +54,6 @@
 import org.jetbrains.plugins.gradle.model.ExtIdeaContentRoot;
 import org.jetbrains.plugins.gradle.model.ModuleExtendedModel;
 import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
-import org.jetbrains.plugins.gradle.model.impl.GradleDependency;
 import org.jetbrains.plugins.gradle.util.GradleBundle;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
 import org.jetbrains.plugins.gradle.util.GradleUtil;
@@ -102,10 +102,7 @@
   public ProjectData createProject() {
     final String projectDirPath = resolverCtx.getProjectPath();
     final IdeaProject ideaProject = resolverCtx.getModels().getIdeaProject();
-
-    ProjectData projectData = new ProjectData(GradleConstants.SYSTEM_ID, projectDirPath, projectDirPath);
-    projectData.setName(ideaProject.getName());
-    return projectData;
+    return new ProjectData(GradleConstants.SYSTEM_ID, ideaProject.getName(), projectDirPath, projectDirPath);
   }
 
   @NotNull
@@ -130,7 +127,13 @@
     }
     final String moduleConfigPath = GradleUtil.getConfigPath(gradleModule.getGradleProject(), projectData.getLinkedExternalProjectPath());
 
-    ModuleData moduleData = new ModuleData(GradleConstants.SYSTEM_ID,
+    if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
+      LOG.info(String.format(
+        "Creating module data ('%s') with the external config path: '%s'", gradleModule.getGradleProject().getPath(), moduleConfigPath
+      ));
+    }
+    ModuleData moduleData = new ModuleData(gradleModule.getGradleProject().getPath(),
+                                           GradleConstants.SYSTEM_ID,
                                            StdModuleTypes.JAVA.getId(),
                                            moduleName,
                                            moduleConfigPath,
@@ -222,10 +225,11 @@
 
     ProjectDependenciesModel dependenciesModel = resolverCtx.getExtraProject(gradleModule, ProjectDependenciesModel.class);
 
-    DomainObjectSet<? extends IdeaDependency> dependencies = gradleModule.getDependencies();
-    if (dependencies == null) {
-      return;
-    }
+    final List<? extends IdeaDependency> dependencies =
+      dependenciesModel != null ? dependenciesModel.getDependencies() : gradleModule.getDependencies().getAll();
+
+    if (dependencies == null) return;
+
     for (IdeaDependency dependency : dependencies) {
       if (dependency == null) {
         continue;
@@ -243,10 +247,6 @@
       else if (dependency instanceof IdeaSingleEntryLibraryDependency) {
         LibraryDependencyData d = buildDependency(ideModule, (IdeaSingleEntryLibraryDependency)dependency, ideProject);
         d.setExported(dependency.getExported());
-        if (dependenciesModel != null) {
-          DependencyScope providedScope = parseProvidedScope(d, dependenciesModel.getDependencies());
-          scope = providedScope == null ? scope : providedScope;
-        }
         if (scope != null) {
           d.setScope(scope);
         }
@@ -338,6 +338,7 @@
     }
 
     List<String> additionalEntries = ContainerUtilRt.newArrayList();
+    ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(GroovyObject.class));
     ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(JavaProjectData.class));
     ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(LanguageLevel.class));
     ContainerUtilRt.addIfNotNull(additionalEntries, PathUtil.getJarPathForClass(StdModuleTypes.class));
@@ -412,7 +413,7 @@
     Set<String> registeredModuleNames = ContainerUtilRt.newHashSet();
     Collection<DataNode<ModuleData>> modulesDataNode = ExternalSystemApiUtil.getChildren(ideProject, ProjectKeys.MODULE);
     for (DataNode<ModuleData> moduleDataNode : modulesDataNode) {
-      String name = moduleDataNode.getData().getName();
+      String name = moduleDataNode.getData().getExternalName();
       registeredModuleNames.add(name);
       if (name.equals(moduleName)) {
         return new ModuleDependencyData(ownerModule.getData(), moduleDataNode.getData());
@@ -497,19 +498,4 @@
   private static boolean isIdeaTask(final String taskName) {
     return taskName.toLowerCase().contains("idea");
   }
-
-  @Nullable
-  private static DependencyScope parseProvidedScope(LibraryDependencyData libraryDependencyData, List<GradleDependency> dependencies) {
-    for (GradleDependency dependency : dependencies) {
-      String s = dependency.getDependencyName() + '-' + dependency.getDependencyVersion();
-      if (libraryDependencyData.getName().equals(s)) {
-        String configurationName = dependency.getConfigurationName();
-        if (StringUtil.startsWith(configurationName, "provided")) {
-          return DependencyScope.PROVIDED;
-        }
-      }
-    }
-
-    return null;
-  }
 }
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 6edaee4..578398b 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
@@ -23,10 +23,7 @@
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.util.ArrayUtilRt;
-import com.intellij.util.Function;
-import com.intellij.util.PathUtil;
-import com.intellij.util.SystemProperties;
+import com.intellij.util.*;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.util.containers.ContainerUtilRt;
 import org.gradle.StartParameter;
@@ -47,8 +44,10 @@
 import java.io.InputStream;
 import java.io.OutputStream;
 import java.lang.reflect.Field;
+import java.util.Collection;
 import java.util.Collections;
 import java.util.List;
+import java.util.Set;
 import java.util.concurrent.TimeUnit;
 
 /**
@@ -78,25 +77,9 @@
                                         @NotNull ProjectConnection connection,
                                         @Nullable GradleExecutionSettings settings,
                                         @NotNull ExternalSystemTaskNotificationListener listener,
-                                        @Nullable final String vmOptions) {
+                                        @NotNull final List<String> vmOptions) {
     BuildLauncher result = connection.newBuild();
-    List<String> extraJvmArgs = vmOptions == null ? Collections.<String>emptyList() : ContainerUtil.newArrayList(vmOptions.trim());
-    prepare(result, id, settings, listener, extraJvmArgs, connection);
-    return result;
-  }
-
-  @SuppressWarnings({"MethodMayBeStatic", "UnusedDeclaration"})
-  @NotNull
-  public BuildLauncher getBuildLauncher(@NotNull final ExternalSystemTaskId id,
-                                        @NotNull ProjectConnection connection,
-                                        @Nullable GradleExecutionSettings settings,
-                                        @NotNull ExternalSystemTaskNotificationListener listener,
-                                        @Nullable final String vmOptions,
-                                        @NotNull final OutputStream standardOutput,
-                                        @NotNull final OutputStream standardError) {
-    BuildLauncher result = connection.newBuild();
-    List<String> extraJvmArgs = vmOptions == null ? ContainerUtil.<String>emptyList() : ContainerUtil.newArrayList(vmOptions.trim());
-    prepare(result, id, settings, listener, extraJvmArgs, connection, standardOutput, standardError);
+    prepare(result, id, settings, listener, vmOptions, connection);
     return result;
   }
 
@@ -125,7 +108,7 @@
       return;
     }
 
-    List<String> jvmArgs = ContainerUtilRt.newArrayList();
+    Set<String> jvmArgs = ContainerUtilRt.newHashSet();
 
     String vmOptions = settings.getDaemonVmOptions();
     if (!StringUtil.isEmpty(vmOptions)) {
@@ -142,9 +125,18 @@
 
     if (!jvmArgs.isEmpty()) {
       BuildEnvironment buildEnvironment = getBuildEnvironment(connection);
-      List<String> merged =
+      Collection<String> merged =
         buildEnvironment != null ? mergeJvmArgs(buildEnvironment.getJava().getJvmArguments(), jvmArgs) : jvmArgs;
-      operation.setJvmArguments(ArrayUtilRt.toStringArray(merged));
+
+      // filter nulls and empty strings
+      List<String> filteredArgs = ContainerUtil.mapNotNull(merged, new Function<String, String>() {
+        @Override
+        public String fun(String s) {
+          return StringUtil.isEmpty(s) ? null : s;
+        }
+      });
+
+      operation.setJvmArguments(ArrayUtil.toStringArray(filteredArgs));
     }
 
     listener.onStart(id);
@@ -191,7 +183,7 @@
       return f.fun(connection);
     }
     catch (Throwable e) {
-      throw new ExternalSystemException(e);
+      throw new ExternalSystemException(ExceptionUtil.getMessage(e));
     }
     finally {
       try {
@@ -212,15 +204,13 @@
                                      @NotNull GradleExecutionSettings settings,
                                      @NotNull ExternalSystemTaskNotificationListener listener) {
 
-    if (!settings.getDistributionType().isWrapped()) return;
+    // use it only for customized wrapper
+    // TODO works correctly only or root project
+    if (settings.getDistributionType() != DistributionType.WRAPPED) return;
 
-    if (settings.getDistributionType() == DistributionType.DEFAULT_WRAPPED &&
-        GradleUtil.findDefaultWrapperPropertiesFile(projectPath) != null) {
-      return;
-    }
     ProjectConnection connection = getConnection(projectPath, settings);
     try {
-      BuildLauncher launcher = getBuildLauncher(id, connection, settings, listener, null);
+      BuildLauncher launcher = getBuildLauncher(id, connection, settings, listener, ContainerUtil.<String>newArrayList());
       try {
         final File tempFile = FileUtil.createTempFile("wrap", ".gradle");
         tempFile.deleteOnExit();
@@ -259,7 +249,7 @@
     }
   }
 
-  private static List<String> mergeJvmArgs(List<String> jvmArgs1, List<String> jvmArgs2) {
+  private static List<String> mergeJvmArgs(Iterable<String> jvmArgs1, Iterable<String> jvmArgs2) {
     JvmOptions jvmOptions = new JvmOptions(null);
     jvmOptions.setAllJvmArgs(ContainerUtil.concat(jvmArgs1, jvmArgs2));
     return jvmOptions.getAllJvmArgs();
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleNotification.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleNotification.java
new file mode 100644
index 0000000..32f37d1
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleNotification.java
@@ -0,0 +1,69 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.gradle.service.project;
+
+import com.intellij.notification.Notification;
+import com.intellij.notification.NotificationGroup;
+import com.intellij.notification.NotificationListener;
+import com.intellij.notification.NotificationType;
+import com.intellij.openapi.components.ServiceManager;
+import com.intellij.openapi.project.Project;
+import com.intellij.ui.AppUIUtil;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 12/10/13
+ */
+public class GradleNotification {
+  private static final NotificationGroup NOTIFICATION_GROUP = NotificationGroup.balloonGroup("Gradle Notification Group");
+
+  @Nullable private Notification myNotification;
+  @NotNull private final Project myProject;
+
+  @NotNull
+  public static GradleNotification getInstance(@NotNull Project project) {
+    return ServiceManager.getService(project, GradleNotification.class);
+  }
+
+  public GradleNotification(@NotNull Project project) {
+    myProject = project;
+  }
+
+  public void showBalloon(@NotNull final String title,
+                          @NotNull final String message,
+                          @NotNull final NotificationType type,
+                          @Nullable final NotificationListener listener) {
+    Runnable notificationTask = new Runnable() {
+      @Override
+      public void run() {
+        if (!myProject.isDisposed() && myProject.isOpen()) {
+          Notification notification = NOTIFICATION_GROUP.createNotification(title, message, type, listener);
+          Notification old = myNotification;
+          if (old != null && old.getContent().equals(notification.getContent())) {
+            old.expire();
+          }
+          myNotification = notification;
+          notification.notify(myProject);
+        }
+      }
+    };
+
+    AppUIUtil.invokeLaterIfProjectAlive(myProject, notificationTask);
+  }
+}
+
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
index 4cde2be..1b1997b 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleProjectResolver.java
@@ -29,6 +29,7 @@
 import com.intellij.openapi.externalSystem.model.task.TaskData;
 import com.intellij.openapi.externalSystem.service.project.ExternalSystemProjectResolver;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
+import com.intellij.openapi.externalSystem.util.ExternalSystemDebugEnvironment;
 import com.intellij.openapi.util.KeyValue;
 import com.intellij.openapi.util.Pair;
 import com.intellij.util.Function;
@@ -124,6 +125,12 @@
     });
   }
 
+  @Override
+  public boolean cancelTask(@NotNull ExternalSystemTaskId id, @NotNull ExternalSystemTaskNotificationListener listener) {
+    // TODO implement cancellation using gradle API invocation when it will be ready, see http://issues.gradle.org/browse/GRADLE-1539
+    return false;
+  }
+
   @NotNull
   private DataNode<ProjectData> doResolveProjectInfo(@NotNull final ProjectResolverContext resolverCtx,
                                                      @NotNull final GradleProjectResolverExtension projectResolverChain)
@@ -204,6 +211,11 @@
       if (gradleModule == null) {
         continue;
       }
+
+      if (ExternalSystemDebugEnvironment.DEBUG_ORPHAN_MODULES_PROCESSING) {
+        LOG.info(String.format("Importing module data: %s", gradleModule));
+      }
+
       final String moduleName = gradleModule.getName();
       if (moduleName == null) {
         throw new IllegalStateException("Module with undefined name detected: " + gradleModule);
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java
new file mode 100644
index 0000000..623a797
--- /dev/null
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/GradleStartupActivity.java
@@ -0,0 +1,100 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.gradle.service.project;
+
+import com.intellij.ide.actions.ImportModuleAction;
+import com.intellij.ide.util.PropertiesComponent;
+import com.intellij.ide.util.newProjectWizard.AddModuleWizard;
+import com.intellij.notification.Notification;
+import com.intellij.notification.NotificationListener;
+import com.intellij.notification.NotificationType;
+import com.intellij.openapi.components.ServiceManager;
+import com.intellij.openapi.externalSystem.model.ExternalSystemDataKeys;
+import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataManager;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.startup.StartupActivity;
+import com.intellij.openapi.util.io.FileUtil;
+import com.intellij.openapi.vfs.VfsUtilCore;
+import org.jetbrains.annotations.NonNls;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportBuilder;
+import org.jetbrains.plugins.gradle.service.project.wizard.GradleProjectImportProvider;
+import org.jetbrains.plugins.gradle.settings.GradleSettings;
+import org.jetbrains.plugins.gradle.util.GradleBundle;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+
+import javax.swing.event.HyperlinkEvent;
+import java.io.File;
+import java.io.FilenameFilter;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 12/10/13
+ */
+public class GradleStartupActivity implements StartupActivity {
+
+  @NonNls private static final String SHOW_UNLINKED_GRADLE_POPUP = "show.inlinked.gradle.project.popup";
+  private static final String IMPORT_EVENT_DESCRIPTION = "import";
+  private static final String DO_NOT_SHOW_EVENT_DESCRIPTION = "do.not.show";
+
+  @Override
+  public void runActivity(@NotNull Project project) {
+    showNotificationForUnlinkedGradleProject(project);
+  }
+
+  private static void showNotificationForUnlinkedGradleProject(@NotNull final Project project) {
+    if (!PropertiesComponent.getInstance(project).getBoolean(SHOW_UNLINKED_GRADLE_POPUP, true)
+        || !GradleSettings.getInstance(project).getLinkedProjectsSettings().isEmpty()
+        || project.getUserData(ExternalSystemDataKeys.NEWLY_IMPORTED_PROJECT) == Boolean.TRUE) {
+      return;
+    }
+
+    File baseDir = VfsUtilCore.virtualToIoFile(project.getBaseDir());
+    final File[] files = baseDir.listFiles(new FilenameFilter() {
+      @Override
+      public boolean accept(File dir, String name) {
+        return FileUtil.namesEqual(GradleConstants.DEFAULT_SCRIPT_NAME, name);
+      }
+    });
+
+    if (files != null && files.length != 0) {
+      String message = String.format("%s<br>\n%s",
+                                     GradleBundle.message("gradle.notifications.unlinked.project.found.msg", IMPORT_EVENT_DESCRIPTION),
+                                     GradleBundle.message("gradle.notifications.do.not.show", DO_NOT_SHOW_EVENT_DESCRIPTION));
+
+      GradleNotification.getInstance(project).showBalloon(
+        GradleBundle.message("gradle.notifications.unlinked.project.found.title"),
+        message, NotificationType.INFORMATION, new NotificationListener.Adapter() {
+          @Override
+          protected void hyperlinkActivated(@NotNull Notification notification, @NotNull HyperlinkEvent e) {
+            if (IMPORT_EVENT_DESCRIPTION.equals(e.getDescription())) {
+              final ProjectDataManager projectDataManager = ServiceManager.getService(ProjectDataManager.class);
+              GradleProjectImportBuilder gradleProjectImportBuilder = new GradleProjectImportBuilder(projectDataManager);
+              final GradleProjectImportProvider gradleProjectImportProvider = new GradleProjectImportProvider(gradleProjectImportBuilder);
+              AddModuleWizard wizard = new AddModuleWizard(null, files[0].getPath(), gradleProjectImportProvider);
+              if ((wizard.getStepCount() <= 0 || wizard.showAndGet())) {
+                ImportModuleAction.createFromWizard(project, wizard);
+              }
+            }
+            else if (DO_NOT_SHOW_EVENT_DESCRIPTION.equals(e.getDescription())) {
+              PropertiesComponent.getInstance(project).setValue(SHOW_UNLINKED_GRADLE_POPUP, Boolean.FALSE.toString());
+            }
+          }
+        }
+      );
+    }
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java
index ac26037..fe6f0c5 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/project/ProjectImportAction.java
@@ -15,6 +15,7 @@
  */
 package org.jetbrains.plugins.gradle.service.project;
 
+import com.intellij.openapi.externalSystem.model.ExternalSystemException;
 import org.gradle.tooling.BuildAction;
 import org.gradle.tooling.BuildController;
 import org.gradle.tooling.model.build.BuildEnvironment;
@@ -62,11 +63,20 @@
 
     for (IdeaModule module : ideaProject.getModules()) {
       for (Class aClass : myExtraProjectModelClasses) {
-        Object extraProject = controller.findModel(module, aClass);
-        if (extraProject == null) continue;
-        allModels.addExtraProject(extraProject, aClass, module);
+        try {
+          Object extraProject = controller.findModel(module, aClass);
+          if (extraProject == null) continue;
+          allModels.addExtraProject(extraProject, aClass, module);
+        }
+        catch (Exception e) {
+          // do not fail project import in a preview mode
+          if (!myIsPreviewMode) {
+            throw new ExternalSystemException(e);
+          }
+        }
       }
     }
+
     return allModels;
   }
 
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java
index a1376f3..535565c 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/resolve/GradleResolverUtil.java
@@ -15,7 +15,8 @@
  */
 package org.jetbrains.plugins.gradle.service.resolve;
 
-import com.intellij.openapi.util.Key;
+import com.intellij.openapi.util.Computable;
+import com.intellij.openapi.util.RecursionManager;
 import com.intellij.psi.*;
 import com.intellij.psi.scope.PsiScopeProcessor;
 import com.intellij.psi.util.PsiTreeUtil;
@@ -43,7 +44,6 @@
  * @since 8/30/13
  */
 public class GradleResolverUtil {
-  private static final Key<Integer> TYPE_RESOLVE_IN_PROGRESS_KEY = Key.create("TYPE_RESOLVE_IN_PROGRESS_KEY");
 
   public static int getGrMethodArumentsCount(@NotNull GrArgumentList args) {
     int argsCount = 0;
@@ -235,17 +235,13 @@
   }
 
   @Nullable
-  public static PsiType getTypeOf(@Nullable GrExpression expression) {
-    PsiType psiType = null;
-    if (expression != null) {
-      Integer count = expression.getUserData(TYPE_RESOLVE_IN_PROGRESS_KEY);
-      if (count == null) count = 0;
-      if (count < 15) {
-        expression.putUserData(TYPE_RESOLVE_IN_PROGRESS_KEY, ++count);
-        psiType = expression.getNominalType();
-        expression.putUserData(TYPE_RESOLVE_IN_PROGRESS_KEY, null);
+  public static PsiType getTypeOf(@Nullable final GrExpression expression) {
+    if (expression == null) return null;
+    return RecursionManager.doPreventingRecursion(expression, true, new Computable<PsiType>() {
+      @Override
+      public PsiType compute() {
+        return expression.getNominalType();
       }
-    }
-    return psiType;
+    });
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java
index aede765..adb4356 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/settings/GradleProjectSettingsControl.java
@@ -225,29 +225,34 @@
     String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText());
     if (StringUtil.isEmpty(gradleHomePath)) {
       settings.setGradleHome(null);
-      getInitialSettings().setGradleHome(null);
     }
     else {
       settings.setGradleHome(gradleHomePath);
-      getInitialSettings().setGradleHome(gradleHomePath);
       GradleUtil.storeLastUsedGradleHome(gradleHomePath);
     }
 
     if (myUseLocalDistributionButton.isSelected()) {
       settings.setDistributionType(DistributionType.LOCAL);
-      getInitialSettings().setDistributionType(DistributionType.LOCAL);
     } else if(myUseWrapperButton.isSelected()) {
       settings.setDistributionType(DistributionType.DEFAULT_WRAPPED);
+    } else if(myUseWrapperWithVerificationButton.isSelected() || myUseBundledDistributionButton.isSelected()) {
+      settings.setDistributionType(DistributionType.WRAPPED);
+    }
+  }
+
+  @Override
+  protected void updateInitialExtraSettings() {
+    String gradleHomePath = FileUtil.toCanonicalPath(myGradleHomePathField.getText());
+    getInitialSettings().setGradleHome(StringUtil.isEmpty(gradleHomePath) ? null : gradleHomePath);
+    if (myUseLocalDistributionButton.isSelected()) {
+      getInitialSettings().setDistributionType(DistributionType.LOCAL);
+    } else if(myUseWrapperButton.isSelected()) {
       getInitialSettings().setDistributionType(DistributionType.DEFAULT_WRAPPED);
-    } else if(myUseWrapperWithVerificationButton.isSelected()) {
-      settings.setDistributionType(DistributionType.WRAPPED);
-      getInitialSettings().setDistributionType(DistributionType.WRAPPED);
-    } else if (myUseBundledDistributionButton.isSelected()) {
-      settings.setDistributionType(DistributionType.WRAPPED);
+    } else if(myUseWrapperWithVerificationButton.isSelected() || myUseBundledDistributionButton.isSelected()) {
       getInitialSettings().setDistributionType(DistributionType.WRAPPED);
     }
   }
-  
+
   @Override
   protected boolean isExtraSettingModified() {
     DistributionType distributionType = getInitialSettings().getDistributionType();
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java
index 757f047..c69e132 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManager.java
@@ -15,11 +15,11 @@
  */
 package org.jetbrains.plugins.gradle.service.task;
 
-import com.intellij.openapi.extensions.ExtensionPointName;
 import com.intellij.openapi.externalSystem.model.ExternalSystemException;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationEvent;
 import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListener;
+import com.intellij.openapi.externalSystem.task.AbstractExternalSystemTaskManager;
 import com.intellij.openapi.externalSystem.task.ExternalSystemTaskManager;
 import com.intellij.openapi.externalSystem.util.ExternalSystemApiUtil;
 import com.intellij.openapi.util.io.FileUtil;
@@ -32,38 +32,58 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper;
-import org.jetbrains.plugins.gradle.service.project.GradleProjectResolverExtension;
 import org.jetbrains.plugins.gradle.settings.GradleExecutionSettings;
 import org.jetbrains.plugins.gradle.util.GradleConstants;
 
 import java.io.File;
 import java.io.IOException;
-import java.io.OutputStream;
 import java.util.List;
 
 /**
  * @author Denis Zhdanov
  * @since 3/14/13 5:09 PM
  */
-public class GradleTaskManager implements ExternalSystemTaskManager<GradleExecutionSettings> {
+public class GradleTaskManager extends AbstractExternalSystemTaskManager<GradleExecutionSettings>
+  implements ExternalSystemTaskManager<GradleExecutionSettings> {
 
   private final GradleExecutionHelper myHelper = new GradleExecutionHelper();
 
+  /**
+   * TODO: remove the method in 13.1
+   */
+  @Override
+  public void executeTasks(@NotNull ExternalSystemTaskId id,
+                           @NotNull List<String> taskNames,
+                           @NotNull String projectPath,
+                           @Nullable GradleExecutionSettings settings,
+                           @Nullable String vmOptions,
+                           @Nullable String debuggerSetup,
+                           @NotNull ExternalSystemTaskNotificationListener listener) throws ExternalSystemException {
+    throw new UnsupportedOperationException();
+  }
+
   @Override
   public void executeTasks(@NotNull final ExternalSystemTaskId id,
                            @NotNull final List<String> taskNames,
                            @NotNull String projectPath,
                            @Nullable final GradleExecutionSettings settings,
-                           @Nullable final String vmOptions,
+                           @NotNull final List<String> vmOptions,
+                           @NotNull final List<String> scriptParameters,
                            @Nullable final String debuggerSetup,
                            @NotNull final ExternalSystemTaskNotificationListener listener) throws ExternalSystemException {
 
-    if(settings != null) {
+    if (settings != null) {
       myHelper.ensureInstalledWrapper(id, projectPath, settings, listener);
     }
 
-    for (GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) {
-      if(gradleTaskManagerExtension.executeTasks(id, taskNames, projectPath, settings, vmOptions, debuggerSetup, listener)) return;
+    // TODO add support for external process mode
+    if (ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) {
+      for (GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) {
+        if (gradleTaskManagerExtension.executeTasks(
+          id, taskNames, projectPath, settings, vmOptions, scriptParameters, debuggerSetup, listener)) {
+          return;
+        }
+      }
     }
 
     Function<ProjectConnection, Void> f = new Function<ProjectConnection, Void>() {
@@ -81,12 +101,18 @@
               "}}",
             };
             FileUtil.writeToFile(tempFile, StringUtil.join(lines, SystemProperties.getLineSeparator()));
-            launcher.withArguments("--init-script", tempFile.getAbsolutePath());
+
+            scriptParameters.add("--init-script");
+            scriptParameters.add(tempFile.getAbsolutePath());
           }
           catch (IOException e) {
             throw new ExternalSystemException(e);
           }
         }
+
+        if (!scriptParameters.isEmpty()) {
+          launcher.withArguments(ArrayUtil.toStringArray(scriptParameters));
+        }
         launcher.forTasks(ArrayUtil.toStringArray(taskNames));
         launcher.run();
         return null;
@@ -96,17 +122,18 @@
   }
 
   @Override
-  public void cancelTask(@NotNull ExternalSystemTaskId id, @NotNull ExternalSystemTaskNotificationListener listener)
+  public boolean cancelTask(@NotNull ExternalSystemTaskId id, @NotNull ExternalSystemTaskNotificationListener listener)
     throws ExternalSystemException {
 
     for (GradleTaskManagerExtension gradleTaskManagerExtension : GradleTaskManagerExtension.EP_NAME.getExtensions()) {
-      if(gradleTaskManagerExtension.cancelTask(id, listener)) return;
+      if (gradleTaskManagerExtension.cancelTask(id, listener)) return true;
     }
 
     // TODO replace with cancellation gradle API invocation when it will be ready, see http://issues.gradle.org/browse/GRADLE-1539
     if (!ExternalSystemApiUtil.isInProcessMode(GradleConstants.SYSTEM_ID)) {
       listener.onStatusChange(new ExternalSystemTaskNotificationEvent(id, "Cancelling the task...\n"));
-      System.exit(-1);
+      System.exit(0);
     }
+    return false;
   }
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java
index 082e8e1..bd2176a 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java
+++ b/plugins/gradle/src/org/jetbrains/plugins/gradle/service/task/GradleTaskManagerExtension.java
@@ -37,7 +37,8 @@
                        @NotNull final List<String> taskNames,
                        @NotNull String projectPath,
                        @Nullable final GradleExecutionSettings settings,
-                       @Nullable final String vmOptions,
+                       @NotNull final List<String> vmOptions,
+                       @NotNull final List<String> scriptParameters,
                        @Nullable final String debuggerSetup,
                        @NotNull final ExternalSystemTaskNotificationListener listener) throws ExternalSystemException;
 
diff --git a/plugins/gradle/testData/testDefaultDependenciesModel/build.gradle b/plugins/gradle/testData/testDefaultDependenciesModel/build.gradle
new file mode 100644
index 0000000..849b1b4
--- /dev/null
+++ b/plugins/gradle/testData/testDefaultDependenciesModel/build.gradle
@@ -0,0 +1,11 @@
+//noinspection GrPackage
+
+allprojects{
+  apply plugin: 'java'
+}
+
+project(":group2:subgroup11:project") {
+  dependencies {
+    compile project(":project")
+  }
+}
\ No newline at end of file
diff --git a/plugins/gradle/testData/testDefaultDependenciesModel/settings.gradle b/plugins/gradle/testData/testDefaultDependenciesModel/settings.gradle
new file mode 100644
index 0000000..cf870fe
--- /dev/null
+++ b/plugins/gradle/testData/testDefaultDependenciesModel/settings.gradle
@@ -0,0 +1,5 @@
+//noinspection GrPackage
+
+include 'group1:subgroup11:project'
+include 'group2:subgroup11:project'
+include 'project'
\ No newline at end of file
diff --git a/plugins/gradle/testData/testDefaultWarModel/build.gradle b/plugins/gradle/testData/testDefaultWarModel/build.gradle
new file mode 100644
index 0000000..f66f30f
--- /dev/null
+++ b/plugins/gradle/testData/testDefaultWarModel/build.gradle
@@ -0,0 +1,3 @@
+//noinspection GrPackage
+
+apply plugin: 'war'
diff --git a/plugins/gradle/testData/testDefaultWarModel/settings.gradle b/plugins/gradle/testData/testDefaultWarModel/settings.gradle
new file mode 100644
index 0000000..395429b
--- /dev/null
+++ b/plugins/gradle/testData/testDefaultWarModel/settings.gradle
@@ -0,0 +1,3 @@
+//noinspection GrPackage
+
+include 'project'
\ No newline at end of file
diff --git a/plugins/gradle/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle b/plugins/gradle/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
new file mode 100644
index 0000000..6f9afa4
--- /dev/null
+++ b/plugins/gradle/testData/testGradleIdeaPluginPlusScopesDependenciesModel/build.gradle
@@ -0,0 +1,38 @@
+//noinspection GrPackage
+
+allprojects {
+  apply plugin: 'java'
+  apply plugin: 'idea'
+
+  version = '1.0'
+
+  sourceCompatibility = 1.6
+
+  configurations {
+    provided
+  }
+
+  sourceSets {
+    main {
+      compileClasspath += configurations.provided
+    }
+  }
+
+  idea {
+    module {
+      scopes.PROVIDED.plus += configurations.provided
+    }
+  }
+}
+
+project(":service") {
+  dependencies {
+    compile  (project(':api'))
+  }
+}
+
+project(":api") {
+  dependencies {
+    provided(project(':lib'))
+  }
+}
\ No newline at end of file
diff --git a/plugins/gradle/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle b/plugins/gradle/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle
new file mode 100644
index 0000000..271f734
--- /dev/null
+++ b/plugins/gradle/testData/testGradleIdeaPluginPlusScopesDependenciesModel/settings.gradle
@@ -0,0 +1,4 @@
+//noinspection GrPackage
+include "lib"
+include "api"
+include "service"
\ No newline at end of file
diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/AbstractModelBuilderTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/AbstractModelBuilderTest.java
new file mode 100644
index 0000000..835d730
--- /dev/null
+++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/AbstractModelBuilderTest.java
@@ -0,0 +1,96 @@
+/*
+ * 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.builder;
+
+import com.intellij.openapi.util.io.FileUtil;
+import org.gradle.tooling.BuildActionExecuter;
+import org.gradle.tooling.GradleConnector;
+import org.gradle.tooling.ProjectConnection;
+import org.gradle.tooling.internal.consumer.DefaultGradleConnector;
+import org.jetbrains.plugins.gradle.service.project.GradleExecutionHelper;
+import org.jetbrains.plugins.gradle.service.project.ProjectImportAction;
+import org.jetbrains.plugins.gradle.util.GradleConstants;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.rules.TestName;
+
+import java.io.File;
+import java.util.Set;
+
+import static org.junit.Assert.assertNotNull;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/29/13
+ */
+public abstract class AbstractModelBuilderTest {
+  private static File ourTempDir;
+  protected File testDir;
+  protected ProjectImportAction.AllModels allModels;
+
+  @Rule public TestName name = new TestName();
+
+  @Before
+  public void setUp() throws Exception {
+    ensureTempDirCreated();
+    testDir = new File(ourTempDir, name.getMethodName());
+    testDir.mkdirs();
+
+    FileUtil.writeToFile(
+      new File(testDir, GradleConstants.DEFAULT_SCRIPT_NAME),
+      FileUtil.loadTextAndClose(getClass().getResourceAsStream(
+        String.format("/%s/%s", name.getMethodName(), GradleConstants.DEFAULT_SCRIPT_NAME))
+      )
+    );
+
+    FileUtil.writeToFile(
+      new File(testDir, GradleConstants.SETTINGS_FILE_NAME),
+      FileUtil.loadTextAndClose(getClass().getResourceAsStream(
+        String.format("/%s/%s", name.getMethodName(), GradleConstants.SETTINGS_FILE_NAME))
+      )
+    );
+
+    GradleConnector connector = GradleConnector.newConnector();
+
+    DefaultGradleConnector gradleConnector = (DefaultGradleConnector)connector;
+    gradleConnector.forProjectDirectory(testDir);
+    ProjectConnection connection = gradleConnector.connect();
+
+    final ProjectImportAction projectImportAction = new ProjectImportAction(true);
+    projectImportAction.addExtraProjectModelClasses(getModels());
+    BuildActionExecuter<ProjectImportAction.AllModels> buildActionExecutor = connection.action(projectImportAction);
+    GradleExecutionHelper.setInitScript(buildActionExecutor);
+
+    allModels = buildActionExecutor.run();
+    assertNotNull(allModels);
+  }
+
+  @After
+  public void tearDown() throws Exception {
+    FileUtil.delete(testDir);
+  }
+
+  protected abstract Set<Class> getModels();
+
+  private static void ensureTempDirCreated() {
+    if (ourTempDir != null) return;
+
+    ourTempDir = new File(FileUtil.getTempDirectory(), "gradleTests");
+    FileUtil.delete(ourTempDir);
+    ourTempDir.mkdirs();
+  }
+}
diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImplTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImplTest.java
new file mode 100644
index 0000000..6bb9b6f
--- /dev/null
+++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/ModelDependenciesBuilderImplTest.java
@@ -0,0 +1,109 @@
+/*
+ * 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.builder;
+
+import com.intellij.openapi.util.Condition;
+import com.intellij.util.containers.ContainerUtil;
+import org.gradle.tooling.model.DomainObjectSet;
+import org.gradle.tooling.model.idea.IdeaDependency;
+import org.gradle.tooling.model.idea.IdeaModule;
+import org.gradle.tooling.model.idea.IdeaModuleDependency;
+import org.jetbrains.plugins.gradle.model.GradleDependencyScope;
+import org.jetbrains.plugins.gradle.model.ProjectDependenciesModel;
+import org.junit.Test;
+
+import java.util.Set;
+
+import static org.junit.Assert.*;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/29/13
+ */
+public class ModelDependenciesBuilderImplTest extends AbstractModelBuilderTest {
+
+  @Test
+  public void testDefaultDependenciesModel() throws Exception {
+    ModelDependenciesBuilderImpl dependenciesBuilder = new ModelDependenciesBuilderImpl();
+    assertTrue(dependenciesBuilder.canBuild("org.jetbrains.plugins.gradle.model.ProjectDependenciesModel"));
+
+    DomainObjectSet<? extends IdeaModule> ideaModules = allModels.getIdeaProject().getModules();
+
+    IdeaModule ideaModule = ContainerUtil.find(ideaModules, new Condition<IdeaModule>() {
+      @Override
+      public boolean value(IdeaModule module) {
+        return module.getName().equals("group2-subgroup11-project");
+      }
+    });
+
+    assertNotNull(ideaModule);
+
+    DomainObjectSet<? extends IdeaDependency> dependencies = ideaModule.getDependencies();
+    assertEquals(1, dependencies.size());
+  }
+
+  @Test
+  public void testGradleIdeaPluginPlusScopesDependenciesModel() throws Exception {
+    ModelDependenciesBuilderImpl dependenciesBuilder = new ModelDependenciesBuilderImpl();
+    assertTrue(dependenciesBuilder.canBuild("org.jetbrains.plugins.gradle.model.ProjectDependenciesModel"));
+
+    DomainObjectSet<? extends IdeaModule> ideaModules = allModels.getIdeaProject().getModules();
+
+    // test api module dependencies
+    IdeaModule apiModule = ContainerUtil.find(ideaModules, new Condition<IdeaModule>() {
+      @Override
+      public boolean value(IdeaModule module) {
+        return module.getName().equals("api");
+      }
+    });
+    assertNotNull(apiModule);
+
+    DomainObjectSet<? extends IdeaDependency> dependencies = apiModule.getDependencies();
+    assertEquals(1, dependencies.size());
+    IdeaDependency libDependency = dependencies.getAt(0);
+    assertEquals(GradleDependencyScope.PROVIDED.name(), libDependency.getScope().getScope());
+    assertTrue(libDependency instanceof IdeaModuleDependency);
+
+    IdeaModuleDependency libModuleDependency = (IdeaModuleDependency)libDependency;
+    assertNotNull(libModuleDependency.getDependencyModule());
+    assertEquals("lib", libModuleDependency.getDependencyModule().getName());
+
+
+    // test service module dependencies
+    IdeaModule serviceModule = ContainerUtil.find(ideaModules, new Condition<IdeaModule>() {
+      @Override
+      public boolean value(IdeaModule module) {
+        return module.getName().equals("service");
+      }
+    });
+    assertNotNull(serviceModule);
+
+    DomainObjectSet<? extends IdeaDependency> serviceModuleDependencies = serviceModule.getDependencies();
+    assertEquals(1, serviceModuleDependencies.size());
+    IdeaDependency apiDependency = serviceModuleDependencies.getAt(0);
+    assertEquals(GradleDependencyScope.COMPILE.name(), apiDependency.getScope().getScope());
+    assertTrue(apiDependency instanceof IdeaModuleDependency);
+
+    IdeaModuleDependency apiModuleDependency = (IdeaModuleDependency)apiDependency;
+    assertNotNull(apiModuleDependency.getDependencyModule());
+    assertEquals("api", apiModuleDependency.getDependencyModule().getName());
+  }
+
+  @Override
+  protected Set<Class> getModels() {
+    return ContainerUtil.<Class>set(ProjectDependenciesModel.class);
+  }
+}
diff --git a/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImplTest.java b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImplTest.java
new file mode 100644
index 0000000..e0aff59
--- /dev/null
+++ b/plugins/gradle/testSources/org/jetbrains/plugins/gradle/model/builder/WarModelBuilderImplTest.java
@@ -0,0 +1,61 @@
+/*
+ * 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.builder;
+
+import com.intellij.util.Function;
+import com.intellij.util.containers.ContainerUtil;
+import org.gradle.tooling.model.DomainObjectSet;
+import org.gradle.tooling.model.idea.IdeaModule;
+import org.jetbrains.plugins.gradle.model.WarModel;
+import org.junit.Test;
+
+import java.util.List;
+import java.util.Set;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
+/**
+ * @author Vladislav.Soroka
+ * @since 11/29/13
+ */
+public class WarModelBuilderImplTest extends AbstractModelBuilderTest {
+
+  @Test
+  public void testDefaultWarModel() throws Exception {
+    WarModelBuilderImpl warModelBuilder = new WarModelBuilderImpl();
+    assertTrue(warModelBuilder.canBuild("org.jetbrains.plugins.gradle.model.WarModel"));
+
+    DomainObjectSet<? extends IdeaModule> ideaModules = allModels.getIdeaProject().getModules();
+
+    List<WarModel> ideaModule = ContainerUtil.mapNotNull(ideaModules, new Function<IdeaModule, WarModel>() {
+      @Override
+      public WarModel fun(IdeaModule module) {
+        return allModels.getExtraProject(module, WarModel.class);
+      }
+    });
+
+    assertEquals(1, ideaModule.size());
+    WarModel warModel = ideaModule.get(0);
+
+    assertEquals("src/main/webapp", warModel.getWebAppDirName());
+  }
+
+  @Override
+  protected Set<Class> getModels() {
+    return ContainerUtil.<Class>set(WarModel.class);
+  }
+}
diff --git a/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java
index 8030a30..d2efa81 100644
--- a/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java
+++ b/plugins/groovy/jps-plugin/src/org/jetbrains/jps/incremental/groovy/GroovyBuilder.java
@@ -56,7 +56,6 @@
 import java.io.File;
 import java.io.IOException;
 import java.util.*;
-import java.util.concurrent.ConcurrentHashMap;
 import java.util.concurrent.Future;
 
 /**
@@ -237,7 +236,7 @@
   private static void rememberStubSources(CompileContext context, Map<ModuleBuildTarget, Collection<GroovycOSProcessHandler.OutputItem>> compiled) {
     Map<String, String> stubToSrc = STUB_TO_SRC.get(context);
     if (stubToSrc == null) {
-      STUB_TO_SRC.set(context, stubToSrc = new ConcurrentHashMap<String, String>());
+      STUB_TO_SRC.set(context, stubToSrc = new HashMap<String, String>());
     }
     for (Collection<GroovycOSProcessHandler.OutputItem> items : compiled.values()) {
       for (GroovycOSProcessHandler.OutputItem item : items) {
@@ -374,7 +373,7 @@
     return toCompile;
   }
 
-  private static boolean updateDependencies(CompileContext context,
+  private boolean updateDependencies(CompileContext context,
                                             ModuleChunk chunk,
                                             DirtyFilesHolder<JavaSourceRootDescriptor, ModuleBuildTarget> dirtyFilesHolder,
                                             List<File> toCompile,
@@ -394,7 +393,17 @@
           final String outputPath = FileUtil.toSystemIndependentName(item.outputPath);
           final File outputFile = new File(outputPath);
           outputConsumer.registerOutputFile(target, outputFile, Collections.singleton(sourcePath));
-          callback.associate(outputPath, sourcePath, new ClassReader(FileUtil.loadFileBytes(outputFile)));
+          try {
+            callback.associate(outputPath, sourcePath, new ClassReader(FileUtil.loadFileBytes(outputFile)));
+          }
+          catch (Throwable e) {
+            // need this to make sure that unexpected errors in, for example, ASM will not ruin the compilation  
+            final String message = "Class dependency information may be incomplete! Error parsing generated class " + item.outputPath;
+            LOG.info(message, e);
+            context.processMessage(new CompilerMessage(
+              myBuilderName, BuildMessage.Kind.WARNING, message + "\n" + CompilerMessage.getTextFromThrowable(e), sourcePath)
+            );
+          }
           successfullyCompiledFiles.add(new File(sourcePath));
         }
       }
diff --git a/plugins/groovy/src/META-INF/plugin.xml b/plugins/groovy/src/META-INF/plugin.xml
index 41f78cf..da7ed7e 100644
--- a/plugins/groovy/src/META-INF/plugin.xml
+++ b/plugins/groovy/src/META-INF/plugin.xml
@@ -1555,12 +1555,14 @@
             icon="JetgroovyIcons.Groovy.GroovyDoc">
       <add-to-group group-id="ToolsMenu" anchor="last"/>
     </action>
+<!--
     <action id="Groovy.Shell"
             class="org.jetbrains.plugins.groovy.console.GroovyShellAction"
             text="Groovy Shell..." description="Launch Groovy Shell"
             icon="JetgroovyIcons.Groovy.Groovy_16x16">
       <add-to-group group-id="ToolsMenu" anchor="last"/>
     </action>
+-->
 
     <action id="Groovy.Console"
             class="org.jetbrains.plugins.groovy.console.GroovyConsoleAction"
diff --git a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java
index 5f3a421..de8841f 100644
--- a/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java
+++ b/plugins/groovy/src/org/intellij/plugins/intelliLang/inject/groovy/GrConcatenationAwareInjector.java
@@ -48,10 +48,10 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
 import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.annotation.GrAnnotationNameValuePair;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.literals.GrStringInjection;
-import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
 
 import java.util.LinkedList;
@@ -124,7 +124,7 @@
     void processInjections() {
       final PsiElement firstOperand = myOperands[0];
       final PsiElement topBlock = ControlFlowUtils.findControlFlowOwner(firstOperand);
-      final LocalSearchScope searchScope = new LocalSearchScope(new PsiElement[]{topBlock instanceof PsiCodeBlock
+      final LocalSearchScope searchScope = new LocalSearchScope(new PsiElement[]{topBlock instanceof GrCodeBlock
                                                                                  ? topBlock : firstOperand.getContainingFile()}, "", true);
       final THashSet<PsiModifierListOwner> visitedVars = new THashSet<PsiModifierListOwner>();
       final LinkedList<PsiElement> places = new LinkedList<PsiElement>();
@@ -135,8 +135,8 @@
           assert list != null;
 
           final String methodName;
-          if (methodCall instanceof GrMethodCallExpression) {
-            GrExpression invoked = ((GrMethodCallExpression)methodCall).getInvokedExpression();
+          if (methodCall instanceof GrMethodCall) {
+            GrExpression invoked = ((GrMethodCall)methodCall).getInvokedExpression();
             final String referenceName = invoked instanceof GrReferenceExpression? ((GrReferenceExpression)invoked).getReferenceName() : null;
             if ("super".equals(referenceName) || "this".equals(referenceName)) { // constructor call
               final PsiClass psiClass = PsiTreeUtil.getParentOfType(methodCall, PsiClass.class, true);
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GrReassignedLocalVarsChecker.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GrReassignedLocalVarsChecker.java
index d15268b..313347d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GrReassignedLocalVarsChecker.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInsight/GrReassignedLocalVarsChecker.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -19,19 +19,25 @@
 import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.NullableComputable;
 import com.intellij.openapi.util.RecursionManager;
+import com.intellij.openapi.util.Ref;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiManager;
 import com.intellij.psi.PsiReference;
 import com.intellij.psi.PsiType;
 import com.intellij.psi.search.searches.ReferencesSearch;
-import com.intellij.psi.util.CachedValue;
-import com.intellij.psi.util.CachedValueProvider;
-import com.intellij.psi.util.CachedValuesManager;
-import com.intellij.psi.util.PsiModificationTracker;
+import com.intellij.psi.util.*;
+import com.intellij.util.containers.ContainerUtil;
+import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.groovy.codeInspection.utils.ControlFlowUtils;
 import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElement;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyRecursiveElementVisitor;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.GrVariable;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrAssignmentExpression;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrReferenceExpression;
 import org.jetbrains.plugins.groovy.lang.psi.dataFlow.types.TypeInferenceHelper;
@@ -40,15 +46,79 @@
 import org.jetbrains.plugins.groovy.refactoring.GroovyRefactoringUtil;
 
 import java.util.Collection;
+import java.util.Set;
 
 /**
  * @author Max Medvedev
  */
 public class GrReassignedLocalVarsChecker {
   private static final Key<CachedValue<PsiType>> LEAST_UPPER_BOUND_TYPE = Key.create("least upper bound type");
+  private static final Key<CachedValue<Set<String>>> ASSIGNED_VARS = Key.create("assigned vars inside block");
+  private static final Key<CachedValue<Boolean>> REASSIGNED_VAR = Key.create("least upper bound type");
 
   @Nullable
-  public static PsiType checkReassignedVar(GrReferenceExpression refExpr, boolean honorCompileStatic) {
+  public static Boolean isReassignedVar(final GrReferenceExpression refExpr) {
+    if (!PsiUtil.isCompileStatic(refExpr)) {
+      return false;
+    }
+
+    if (refExpr.getQualifier() != null) {
+      return false;
+    }
+
+    final PsiElement resolved = refExpr.resolve();
+    if (!GroovyRefactoringUtil.isLocalVariable(resolved)) {
+      return false;
+    }
+
+    assert resolved != null;
+    CachedValue<Boolean> data = resolved.getUserData(REASSIGNED_VAR);
+    if (data == null) {
+      data = CachedValuesManager.getManager(refExpr.getProject()).createCachedValue(new CachedValueProvider<Boolean>() {
+        @Nullable
+        @Override
+        public Result<Boolean> compute() {
+          return Result.create(isReassignedVarImpl((GrVariable)resolved), PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(resolved.getProject()));
+        }
+      }, false);
+      resolved.putUserData(REASSIGNED_VAR, data);
+    }
+    return data.getValue();
+  }
+
+  private static boolean isReassignedVarImpl(final GrVariable resolved) {
+    final GrControlFlowOwner variableScope = PsiTreeUtil.getParentOfType(resolved, GrCodeBlock.class, GroovyFile.class);
+    if (variableScope == null) return false;
+
+    final String name = resolved.getName();
+    final Ref<Boolean> isReassigned = Ref.create(false);
+    for (PsiElement scope = resolved.getParent().getNextSibling(); scope != null; scope = scope.getNextSibling()) {
+      if (scope instanceof GroovyPsiElement) {
+        ((GroovyPsiElement)scope).accept(new GroovyRecursiveElementVisitor() {
+          @Override
+          public void visitClosure(GrClosableBlock closure) {
+            if (getAssignedVarsInsideBlock(closure).contains(name)) {
+              isReassigned.set(true);
+            }
+          }
+
+          @Override
+          public void visitElement(GroovyPsiElement element) {
+            if (isReassigned.get()) return;
+            super.visitElement(element);
+          }
+        });
+
+        if (isReassigned.get()) break;
+      }
+    }
+
+    return isReassigned.get();
+  }
+
+
+  @Nullable
+  public static PsiType getReassignedVarType(GrReferenceExpression refExpr, boolean honorCompileStatic) {
     if (honorCompileStatic && !PsiUtil.isCompileStatic(refExpr) || refExpr.getQualifier() != null) {
       return null;
     }
@@ -69,10 +139,10 @@
       data = CachedValuesManager.getManager(resolved.getProject()).createCachedValue(new CachedValueProvider<PsiType>() {
         @Override
         public Result<PsiType> compute() {
-          return Result.create(getLeastUpperBoundByVarImpl(resolved), PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(
-            resolved.getProject()));
+          return Result.create(getLeastUpperBoundByVarImpl(resolved), PsiModificationTracker.MODIFICATION_COUNT, ProjectRootManager.getInstance(resolved.getProject()));
         }
       }, false);
+      resolved.putUserData(LEAST_UPPER_BOUND_TYPE, data);
     }
     return data.getValue();
   }
@@ -82,22 +152,7 @@
     return RecursionManager.doPreventingRecursion(resolved, false, new NullableComputable<PsiType>() {
       @Override
       public PsiType compute() {
-        final GrControlFlowOwner flowOwner = ControlFlowUtils.findControlFlowOwner(resolved);
         final Collection<PsiReference> all = ReferencesSearch.search(resolved, resolved.getResolveScope()).findAll();
-        boolean hasClosureReassigns = false;
-        for (PsiReference reference : all) {
-          final PsiElement ref = reference.getElement();
-          if (ref instanceof GrReferenceExpression &&
-              PsiUtil.isLValue(((GrReferenceExpression)ref)) &&
-              ControlFlowUtils.findControlFlowOwner(ref) != flowOwner) {
-            hasClosureReassigns = true;
-            break;
-          }
-        }
-
-        if (!hasClosureReassigns) {
-          return null;
-        }
 
         final GrExpression initializer = resolved.getInitializerGroovy();
         PsiType result = initializer != null ? initializer.getType() : null;
@@ -105,8 +160,7 @@
         final PsiManager manager = resolved.getManager();
         for (PsiReference reference : all) {
           final PsiElement ref = reference.getElement();
-          if (ref instanceof GrReferenceExpression &&
-              PsiUtil.isLValue(((GrReferenceExpression)ref))) {
+          if (ref instanceof GrReferenceExpression && PsiUtil.isLValue(((GrReferenceExpression)ref))) {
             result = TypesUtil.getLeastUpperBoundNullable(result, TypeInferenceHelper.getInitializerFor(ref), manager);
           }
         }
@@ -114,4 +168,47 @@
       }
     });
   }
+
+  @NotNull
+  private static Set<String> getAssignedVarsInsideBlock(@NotNull final GrCodeBlock block) {
+    CachedValue<Set<String>> data = block.getUserData(ASSIGNED_VARS);
+
+    if (data == null) {
+      data = CachedValuesManager.getManager(block.getProject()).createCachedValue(new CachedValueProvider<Set<String>>() {
+        @Nullable
+        @Override
+        public Result<Set<String>> compute() {
+          final Set<String> result = ContainerUtil.newHashSet();
+
+          block.acceptChildren(new GroovyRecursiveElementVisitor() {
+            @Override
+            public void visitAssignmentExpression(GrAssignmentExpression expression) {
+              super.visitAssignmentExpression(expression);
+
+              GrExpression lValue = expression.getLValue();
+              if (lValue instanceof GrReferenceExpression && !((GrReferenceExpression)lValue).isQualified()) {
+                result.add(((GrReferenceExpression)lValue).getReferenceName());
+              }
+            }
+
+            @Override
+            public void visitOpenBlock(GrOpenBlock openBlock) {
+              result.addAll(getAssignedVarsInsideBlock(openBlock));
+            }
+
+            @Override
+            public void visitClosure(GrClosableBlock closure) {
+              result.addAll(getAssignedVarsInsideBlock(closure));
+            }
+          });
+
+          return Result.create(result, block);
+        }
+      }, false);
+      block.putUserData(ASSIGNED_VARS, data);
+    }
+
+    return data.getValue();
+  }
+
 }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrReassignedInClosureLocalVarInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrReassignedInClosureLocalVarInspection.java
index 54579db..6f16535 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrReassignedInClosureLocalVarInspection.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/GrReassignedInClosureLocalVarInspection.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -58,8 +58,7 @@
     return true;
   }
 
-
-
+  @NotNull
   @Override
   protected BaseInspectionVisitor buildVisitor() {
     return new BaseInspectionVisitor() {
@@ -71,7 +70,7 @@
         final PsiElement resolved = referenceExpression.resolve();
         if (!GroovyRefactoringUtil.isLocalVariable(resolved)) return;
 
-        final PsiType checked = GrReassignedLocalVarsChecker.checkReassignedVar(referenceExpression, false);
+        final PsiType checked = GrReassignedLocalVarsChecker.getReassignedVarType(referenceExpression, false);
         if (checked == null) return;
 
         final GrControlFlowOwner varFlowOwner = ControlFlowUtils.findControlFlowOwner(resolved);
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/UnnecessaryQualifiedReferenceInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/UnnecessaryQualifiedReferenceInspection.java
index 49ec3ce..b175cbc 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/UnnecessaryQualifiedReferenceInspection.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/confusing/UnnecessaryQualifiedReferenceInspection.java
@@ -18,10 +18,7 @@
 import com.intellij.codeInspection.ProblemDescriptor;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiMember;
-import com.intellij.psi.PsiModifier;
+import com.intellij.psi.*;
 import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.IncorrectOperationException;
@@ -143,6 +140,8 @@
   }
 
   private static boolean canBeSimplified(PsiElement element) {
+    if (PsiTreeUtil.getParentOfType(element, PsiComment.class) != null) return false;
+
     if (element instanceof GrCodeReferenceElement) {
       if (PsiTreeUtil.getParentOfType(element, GrImportStatement.class, GrPackageDefinition.class) != null) return false;
     }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
index fc23c01..31a9740 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/codeInspection/noReturnMethod/MissingReturnInspection.java
@@ -16,6 +16,7 @@
 package org.jetbrains.plugins.groovy.codeInspection.noReturnMethod;
 
 import com.intellij.codeInspection.ProblemsHolder;
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
@@ -29,16 +30,26 @@
 import org.jetbrains.plugins.groovy.lang.psi.GrControlFlowOwner;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementVisitor;
+import org.jetbrains.plugins.groovy.lang.psi.api.GroovyResolveResult;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrCodeBlock;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrOpenBlock;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.branch.GrReturnStatement;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrExpression;
+import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrMethodCall;
 import org.jetbrains.plugins.groovy.lang.psi.api.statements.typedef.members.GrMethod;
 import org.jetbrains.plugins.groovy.lang.psi.controlFlow.Instruction;
 import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.MaybeReturnInstruction;
 import org.jetbrains.plugins.groovy.lang.psi.controlFlow.impl.ThrowingInstruction;
 import org.jetbrains.plugins.groovy.lang.psi.expectedTypes.GroovyExpectedTypesProvider;
+import org.jetbrains.plugins.groovy.lang.psi.impl.signatures.GrClosureSignatureUtil;
+import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
 
 /**
  * @author ven
@@ -67,7 +78,7 @@
 
     public static ReturnStatus getReturnStatus(PsiElement subject) {
       if (subject instanceof GrClosableBlock) {
-        final PsiType inferredReturnType = GroovyExpectedTypesProvider.getExpectedClosureReturnType((GrClosableBlock)subject);
+        final PsiType inferredReturnType = getExpectedClosureReturnType((GrClosableBlock)subject);
         if (inferredReturnType instanceof PsiClassType) {
           PsiClass resolved = ((PsiClassType)inferredReturnType).resolve();
           if (resolved != null && !(resolved instanceof PsiTypeParameter)) return mustReturnValue;
@@ -83,6 +94,55 @@
     }
   }
 
+  @Nullable
+  public static PsiType getExpectedClosureReturnType(GrClosableBlock closure) {
+    List<PsiType> expectedReturnTypes = new ArrayList<PsiType>();
+
+    PsiElement parent = closure.getParent();
+    if (parent instanceof GrArgumentList && parent.getParent() instanceof GrMethodCall || parent instanceof GrMethodCall) {
+      GrMethodCall call = (GrMethodCall)(parent instanceof GrArgumentList ? parent.getParent() : parent);
+
+      GroovyResolveResult[] variants = call.getCallVariants(null);
+
+      for (GroovyResolveResult variant : variants) {
+        Map<GrExpression,Pair<PsiParameter,PsiType>> map =
+          GrClosureSignatureUtil.mapArgumentsToParameters(variant, closure, true, true, call.getNamedArguments(), call.getExpressionArguments(), call.getClosureArguments());
+
+        if (map != null) {
+          Pair<PsiParameter, PsiType> pair = map.get(closure);
+          if (pair == null) continue;
+
+          PsiParameter parameter = pair.getFirst();
+
+          PsiType type = parameter.getType();
+          if (TypesUtil.isPsiClassTypeToClosure(type)) {
+            PsiType[] parameters = ((PsiClassType)type).getParameters();
+            if (parameters.length == 1) {
+              expectedReturnTypes.add(parameters[0]);
+            }
+          }
+        }
+      }
+    }
+    else {
+      final Set<PsiType> expectedTypes = GroovyExpectedTypesProvider.getDefaultExpectedTypes(closure);
+
+      for (PsiType expectedType : expectedTypes) {
+        if (TypesUtil.isPsiClassTypeToClosure(expectedType)) {
+          PsiType[] parameters = ((PsiClassType)expectedType).getParameters();
+          if (parameters.length == 1) {
+            expectedReturnTypes.add(parameters[0]);
+          }
+        }
+      }
+    }
+
+    for (PsiType type : expectedReturnTypes) {
+      if (PsiType.VOID.equals(type)) return PsiType.VOID;
+    }
+    return TypesUtil.getLeastUpperBoundNullable(expectedReturnTypes, closure.getManager());
+  }
+
   @NotNull
   public PsiElementVisitor buildVisitor(@NotNull final ProblemsHolder problemsHolder, boolean onTheFly) {
     return new GroovyPsiElementVisitor(new GroovyElementVisitor() {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/DefaultGroovyShellRunner.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/DefaultGroovyShellRunner.java
index 39aa7a0..db046d1 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/DefaultGroovyShellRunner.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/DefaultGroovyShellRunner.java
@@ -49,7 +49,7 @@
   @Override
   public JavaParameters createJavaParameters(@NotNull Module module) throws ExecutionException {
     JavaParameters res = GroovyScriptRunConfiguration.createJavaParametersWithSdk(module);
-    boolean useBundled = !hasGroovyAll(module);
+    boolean useBundled = !hasGroovyWithNeededJars(module);
     DefaultGroovyScriptRunner.configureGenericGroovyRunner(res, module, "org.codehaus.groovy.tools.shell.Main", false, true);
     if (useBundled) {
       String libRoot = GroovyUtils.getBundledGroovyJar().getParent();
@@ -76,21 +76,25 @@
   @Override
   public String getTitle(@NotNull Module module) {
     String homePath = LibrariesUtil.getGroovyHomePath(module);
-    boolean bundled = false;
-    if (homePath == null || !hasGroovyAll(module)) {
+    boolean bundled = !hasGroovyWithNeededJars(module);
+    if (bundled) {
       homePath = GroovyUtils.getBundledGroovyJar().getParentFile().getParent();
-      bundled = true;
     }
+    else {
+      assert homePath != null;
+    }
+
     String version = GroovyConfigUtils.getInstance().getSDKVersion(homePath);
     return version == AbstractConfigUtils.UNDEFINED_VERSION ? "" : " (" + (bundled ? "Bundled " : "") + "Groovy " + version + ")";
   }
 
-  private static boolean hasGroovyAll(Module module) {
+  private static boolean hasGroovyWithNeededJars(Module module) {
     GlobalSearchScope scope = GlobalSearchScope.moduleWithDependenciesAndLibrariesScope(module);
     JavaPsiFacade facade = JavaPsiFacade.getInstance(module.getProject());
     return (facade.findClass("org.apache.commons.cli.CommandLineParser", scope) != null ||
             facade.findClass("groovyjarjarcommonscli.CommandLineParser", scope) != null) &&
-           facade.findClass("groovy.ui.GroovyMain", scope) != null;
+           facade.findClass("groovy.ui.GroovyMain", scope) != null  &&
+           facade.findClass("org.fusesource.jansi.AnsiConsole", scope) != null;
   }
 
   @NotNull
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyShellActionBase.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyShellActionBase.java
index 54f8d51..4713c37 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyShellActionBase.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/console/GroovyShellActionBase.java
@@ -112,7 +112,7 @@
     final Map<Module, String> versions = new HashMap<Module, String>();
 
     for (Module module : getGroovyCompatibleModules(project)) {
-      GroovyShellRunner runner = GroovyShellRunner.getAppropriateRunner(module);
+      GroovyShellRunner runner = getRunner(module);
       if (runner != null) {
         modules.add(module);
         versions.put(module, runner.getTitle(module));
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyHotSwapper.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyHotSwapper.java
index c4e8fad..583cbaa 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyHotSwapper.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/debugger/GroovyHotSwapper.java
@@ -18,17 +18,18 @@
 import com.intellij.openapi.roots.LanguageLevelProjectExtension;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.pom.java.LanguageLevel;
-import com.intellij.psi.search.FilenameIndex;
+import com.intellij.psi.search.FileTypeIndex;
 import com.intellij.psi.search.GlobalSearchScope;
+import com.intellij.psi.util.CachedValueProvider;
+import com.intellij.psi.util.CachedValuesManager;
+import com.intellij.psi.util.PsiModificationTracker;
 import com.intellij.util.PathUtil;
 import org.jetbrains.annotations.Nullable;
-import org.jetbrains.plugins.groovy.GroovyFileTypeLoader;
+import org.jetbrains.plugins.groovy.GroovyFileType;
 import org.jetbrains.plugins.groovy.debugger.filters.GroovyDebuggerSettings;
 
 import java.io.File;
 import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
 import java.util.jar.Attributes;
 import java.util.regex.Pattern;
 
@@ -42,29 +43,15 @@
 
   private static final Pattern SPRING_LOADED_PATTERN = Pattern.compile("-javaagent:.+springloaded-core-[^/\\\\]+\\.jar");
   
-  private static boolean endsWithAny(String s, List<String> endings) {
-    for (String extension : endings) {
-      if (s.endsWith(extension)) {
-        return true;
+  private static boolean containsGroovyClasses(final Project project) {
+    return CachedValuesManager.getManager(project).getCachedValue(project, new CachedValueProvider<Boolean>() {
+      @Nullable
+      @Override
+      public Result<Boolean> compute() {
+        return Result.create(FileTypeIndex.containsFileOfType(GroovyFileType.GROOVY_FILE_TYPE, GlobalSearchScope.projectScope(project)), 
+                             PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT);
       }
-    }
-    return false;
-  }
-
-  private static boolean containsGroovyClasses(Project project) {
-    final List<String> extensions = new ArrayList<String>();
-    for (String extension : GroovyFileTypeLoader.getAllGroovyExtensions()) {
-      extensions.add("." + extension);
-    }
-    final GlobalSearchScope scope = GlobalSearchScope.projectScope(project);
-    for (String fileName : FilenameIndex.getAllFilenames(project)) {
-      if (endsWithAny(fileName, extensions)) {
-        if (!FilenameIndex.getVirtualFilesByName(project, fileName, scope).isEmpty()) {
-          return true;
-        }
-      }
-    }
-    return false;
+    });
   }
 
   private static boolean hasSpringLoadedReloader(JavaParameters javaParameters) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java
index a210716..224c5b4 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/dgm/DGMMemberContributor.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,10 +17,14 @@
 
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Pair;
-import com.intellij.psi.*;
+import com.intellij.psi.PsiClass;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiType;
+import com.intellij.psi.ResolveState;
 import com.intellij.psi.scope.PsiScopeProcessor;
 import com.intellij.psi.search.GlobalSearchScope;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager;
 import org.jetbrains.plugins.groovy.lang.resolve.NonCodeMembersContributor;
 
 import java.util.List;
@@ -37,15 +41,15 @@
                                      ResolveState state) {
     Project project = place.getProject();
     GlobalSearchScope resolveScope = place.getResolveScope();
-    JavaPsiFacade facade = JavaPsiFacade.getInstance(project);
+    GroovyPsiManager groovyPsiManager = GroovyPsiManager.getInstance(project);
 
     Pair<List<String>, List<String>> extensions = GroovyExtensionProvider.getInstance(project).collectExtensions(resolveScope);
 
     List<String> instanceCategories = extensions.getFirst();
     List<String> staticCategories = extensions.getSecond();
 
-    if (!processCategories(qualifierType, processor, state, project, resolveScope, facade, instanceCategories, false)) return;
-    if (!processCategories(qualifierType, processor, state, project, resolveScope, facade, staticCategories, true)) return;
+    if (!processCategories(qualifierType, processor, state, project, resolveScope, groovyPsiManager, instanceCategories, false)) return;
+    if (!processCategories(qualifierType, processor, state, project, resolveScope, groovyPsiManager, staticCategories, true)) return;
   }
 
   private static boolean processCategories(PsiType qualifierType,
@@ -53,11 +57,10 @@
                                            ResolveState state,
                                            Project project,
                                            GlobalSearchScope resolveScope,
-                                           JavaPsiFacade facade,
-                                           List<String> instanceCategories,
+                                           GroovyPsiManager groovyPsiManager, List<String> instanceCategories,
                                            boolean isStatic) {
     for (String category : instanceCategories) {
-      PsiClass clazz = facade.findClass(category, resolveScope);
+      PsiClass clazz = groovyPsiManager.findClassWithCache(category, resolveScope);
       if (clazz != null) {
         if (!GdkMethodHolder.getHolderForClass(clazz, isStatic, resolveScope).processMethods(processor, state, qualifierType, project)) {
           return false;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/gpp/GppTypeConverter.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/gpp/GppTypeConverter.java
index 7c87148..0b4e639 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/gpp/GppTypeConverter.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/gpp/GppTypeConverter.java
@@ -73,10 +73,13 @@
 
       final PsiType expectedComponent = PsiUtil.extractIterableTypeParameter(lType, false);
       if (expectedComponent != null && isMethodCallConversion(context)) {
-        PsiType tupleComponent = tupleType.getParameters()[0];
-        if (tupleComponent != null &&
-            TypesUtil.isAssignable(expectedComponent, tupleComponent, context) && hasDefaultConstructor(lType)) {
-          return true;
+        PsiType[] parameters = tupleType.getParameters();
+        if (parameters.length == 1) {
+          PsiType tupleComponent = parameters[0];
+          if (tupleComponent != null &&
+              TypesUtil.isAssignable(expectedComponent, tupleComponent, context) && hasDefaultConstructor(lType)) {
+            return true;
+          }
         }
       }
 
@@ -88,10 +91,10 @@
       final PsiType lKeyType = PsiUtil.substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_MAP, 0, false);
       final PsiType lValueType = PsiUtil.substituteTypeParameter(lType, CommonClassNames.JAVA_UTIL_MAP, 1, false);
       final PsiType[] parameters = ((GrMapType)rType).getParameters();
-      if (lKeyType != null && lValueType != null &&
+      if (parameters.length == 2 && lKeyType != null && lValueType != null &&
           parameters[0] != null && parameters[1] != null &&
-          (!TypesUtil.isAssignable(lKeyType, parameters[0], context) || !TypesUtil
-            .isAssignable(lValueType, parameters[1], context))) {
+          (!TypesUtil.isAssignable(lKeyType, parameters[0], context) ||
+           !TypesUtil.isAssignable(lValueType, parameters[1], context))) {
         return null;
       }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java
index 0499c68..faa4955 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/griffon/GriffonFramework.java
@@ -202,15 +202,18 @@
   }
 
   @Override
+  protected boolean isCoreJar(@NotNull VirtualFile localFile) {
+    return GriffonLibraryPresentationProvider.isGriffonCoreJar(localFile);
+  }
+
+  @Override
   public VirtualFile getSdkRoot(@Nullable Module module) {
     VirtualFile coreJar = findCoreJar(module);
     if (coreJar == null) return null;
 
-    if (GriffonLibraryPresentationProvider.isGriffonCoreJar(coreJar)) {
-      final VirtualFile parent = coreJar.getParent();
-      if (parent != null) {
-        return parent.getParent();
-      }
+    final VirtualFile parent = coreJar.getParent();
+    if (parent != null) {
+      return parent.getParent();
     }
     return null;
   }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java
index 5610d74..58ee7a9 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/completion/GroovyCompletionContributor.java
@@ -65,6 +65,7 @@
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameter;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrTypeParameterList;
 import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.CompleteReferenceExpression;
+import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrBindingVariable;
 import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils;
 import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
 import org.jetbrains.plugins.groovy.refactoring.DefaultGroovyVariableNameValidator;
@@ -450,6 +451,10 @@
           object = ((GroovyResolveResult)object).getElement();
         }
 
+        if (object instanceof GrBindingVariable && ((GrBindingVariable)object).getName().contains(CompletionInitializationContext.DUMMY_IDENTIFIER_TRIMMED)) {
+          return;
+        }
+
         if (!(lookupElement instanceof LookupElementBuilder) && inheritorsHolder.alreadyProcessed(lookupElement)) {
           return;
         }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java
index 699393b..bc96a54 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyElementTypes.java
@@ -181,7 +181,7 @@
       return new GrEnumConstantListImpl(stub);
     }
   };
-  GroovyElementType IMPORT_STATEMENT = new GroovyElementType("Import statement");
+  GrImportStatementElementType IMPORT_STATEMENT = new GrImportStatementElementType("Import statement");
   //Branch statements
   GroovyElementType BREAK_STATEMENT = new GroovyElementType("Break statement");
   GroovyElementType CONTINUE_STATEMENT = new GroovyElementType("Continue statement");
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyParser.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyParser.java
index 5c84fe4..e59463d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyParser.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/GroovyParser.java
@@ -34,7 +34,6 @@
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.AssignmentExpression;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.ConditionalExpression;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.ExpressionStatement;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.StrictContextExpression;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.imports.ImportStatement;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.typeDefinitions.TypeDefinition;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.toplevel.CompilationUnit;
@@ -192,7 +191,7 @@
       return true;
     }
 
-    if (!StrictContextExpression.parse(builder, this)) {
+    if (!ExpressionStatement.argParse(builder, this)) {
       builder.error(GroovyBundle.message("expression.expected"));
     }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/ForStatement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/ForStatement.java
index 5fb6053..f8aea34 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/ForStatement.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/ForStatement.java
@@ -23,8 +23,8 @@
 import org.jetbrains.plugins.groovy.lang.parser.GroovyParser;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.modifiers.Modifiers;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.parameters.ParameterDeclaration;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.StrictContextExpression;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.arithmetic.ShiftExpression;
+import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.ConditionalExpression;
+import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.ExpressionStatement;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.types.TypeSpec;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils;
 
@@ -44,15 +44,15 @@
     if (!ParameterDeclaration.parseTraditionalForParameter(builder, parser)) {
       marker.rollbackTo();
       marker = builder.mark();
-      StrictContextExpression.parse(builder, parser);
+      ExpressionStatement.argParse(builder, parser);
     }
 
     ParserUtils.getToken(builder, mSEMI, GroovyBundle.message("semi.expected"));
-    StrictContextExpression.parse(builder, parser);
+    ExpressionStatement.argParse(builder, parser);
     ParserUtils.getToken(builder, mSEMI, GroovyBundle.message("semi.expected"));
     ParserUtils.getToken(builder, mNLS);
     if (!mRPAREN.equals(builder.getTokenType())) {
-      StrictContextExpression.parse(builder, parser);
+      ExpressionStatement.argParse(builder, parser);
     }
     marker.done(FOR_TRADITIONAL_CLAUSE);
     return true;
@@ -99,7 +99,7 @@
       return false;
     }
 
-    if (!ShiftExpression.parse(builder, parser)) {
+    if (!ConditionalExpression.parse(builder, parser)) {
       builder.error(GroovyBundle.message("expression.expected"));
     }
     marker.done(FOR_IN_CLAUSE);
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SwitchStatement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SwitchStatement.java
index 7755763..ce16425 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SwitchStatement.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SwitchStatement.java
@@ -23,7 +23,7 @@
 import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
 import org.jetbrains.plugins.groovy.lang.parser.GroovyParser;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.AssignmentExpression;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.StrictContextExpression;
+import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.ExpressionStatement;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils;
 
 /**
@@ -41,7 +41,7 @@
       marker.done(SWITCH_STATEMENT);
       return;
     }
-    if (!StrictContextExpression.parse(builder, parser)) {
+    if (!ExpressionStatement.argParse(builder, parser)) {
       builder.error(GroovyBundle.message("expression.expected"));
     }
     ParserUtils.getToken(builder, mNLS);
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SynchronizedStatement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SynchronizedStatement.java
index a1dfe32..88e5c94 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SynchronizedStatement.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/SynchronizedStatement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -21,7 +21,7 @@
 import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
 import org.jetbrains.plugins.groovy.lang.parser.GroovyParser;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.blocks.OpenOrClosableBlock;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.StrictContextExpression;
+import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions.ExpressionStatement;
 import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils;
 
 /**
@@ -39,7 +39,7 @@
       return false;
     }
 
-    if (!StrictContextExpression.parse(builder, parser)) {
+    if (!ExpressionStatement.argParse(builder, parser)) {
       builder.error(GroovyBundle.message("expression.expected"));
     }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/expressions/StrictContextExpression.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/expressions/StrictContextExpression.java
deleted file mode 100644
index c1c505c..0000000
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/parser/parsing/statements/expressions/StrictContextExpression.java
+++ /dev/null
@@ -1,88 +0,0 @@
-/*
- * 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.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-package org.jetbrains.plugins.groovy.lang.parser.parsing.statements.expressions;
-
-import com.intellij.lang.PsiBuilder;
-import org.jetbrains.plugins.groovy.GroovyBundle;
-import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
-import org.jetbrains.plugins.groovy.lang.parser.GroovyParser;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.VariableInitializer;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.annotations.Annotation;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.auxiliary.modifiers.Modifiers;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.BranchStatement;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.statements.declaration.Declaration;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.types.TypeSpec;
-import org.jetbrains.plugins.groovy.lang.parser.parsing.util.ParserUtils;
-
-import static org.jetbrains.plugins.groovy.lang.parser.parsing.statements.typeDefinitions.ReferenceElement.ReferenceElementResult.FAIL;
-
-/**
- * @autor: Dmitry.Krasilschikov, ilyas
- */
-public class StrictContextExpression implements GroovyElementTypes {
-  public static boolean parse(PsiBuilder builder, GroovyParser parser) {
-
-    if (BranchStatement.BRANCH_KEYWORDS.contains(builder.getTokenType())) {
-      return BranchStatement.parse(builder, parser);
-    }
-    if (mAT.equals(builder.getTokenType())) {
-      return Annotation.parse(builder, parser);
-    }
-
-
-    PsiBuilder.Marker declStartMarker = builder.mark();
-
-    if (Declaration.parse(builder, false, false, null, parser)) {
-      declStartMarker.rollbackTo();
-      singleDeclarationParse(builder, parser);
-      return true;
-    }
-    else {
-      declStartMarker.rollbackTo();
-      return ExpressionStatement.argParse(builder, parser);
-    }
-  }
-
-  public static void singleDeclarationParse(PsiBuilder builder, GroovyParser parser) {
-
-    PsiBuilder.Marker marker = builder.mark();
-    if (Modifiers.parse(builder, parser)) {
-      PsiBuilder.Marker rb = builder.mark();
-      TypeSpec.parse(builder);
-      if (!mIDENT.equals(builder.getTokenType())) {
-        rb.rollbackTo();
-      } else {
-        rb.drop();
-      }
-      ParserUtils.getToken(builder, mIDENT, GroovyBundle.message("identifier.expected"));
-      if (mASSIGN.equals(builder.getTokenType())) {
-        VariableInitializer.parse(builder, parser);
-      }
-      marker.done(VARIABLE_DEFINITION);
-    } else {
-      if (TypeSpec.parse(builder) != FAIL) {
-        ParserUtils.getToken(builder, mIDENT, GroovyBundle.message("identifier.expected"));
-        if (mASSIGN.equals(builder.getTokenType())) {
-          VariableInitializer.parse(builder, parser);
-        }
-        marker.done(VARIABLE_DEFINITION);
-      } else {
-        builder.error(GroovyBundle.message("type.specification.expected"));
-      }
-    }
-  }
-}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java
index 592f450..b656806 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/api/toplevel/imports/GrImportStatement.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@
 
 import com.intellij.psi.PsiClass;
 import com.intellij.psi.PsiElement;
+import com.intellij.util.ArrayFactory;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
@@ -29,6 +30,15 @@
  */
 public interface GrImportStatement extends GrTopStatement {
   GrImportStatement[] EMPTY_ARRAY = new GrImportStatement[0];
+
+  ArrayFactory<GrImportStatement> ARRAY_FACTORY = new ArrayFactory<GrImportStatement>() {
+    @NotNull
+    @Override
+    public GrImportStatement[] create(int count) {
+      return new GrImportStatement[count];
+    }
+  };
+
   @Nullable
   GrCodeReferenceElement getImportReference();
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java
index d03a710..f3779a1 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/expectedTypes/GroovyExpectedTypesProvider.java
@@ -105,32 +105,6 @@
     return result;
   }
 
-  @Nullable
-  public static PsiType getExpectedClosureReturnType(GrClosableBlock closure) {
-  final Set<PsiType> expectedTypes = getDefaultExpectedTypes(closure);
-
-  List<PsiType> expectedReturnTypes = new ArrayList<PsiType>();
-  for (PsiType expectedType : expectedTypes) {
-    if (!(expectedType instanceof PsiClassType)) return null;
-
-    final PsiClassType.ClassResolveResult resolveResult = ((PsiClassType)expectedType).resolveGenerics();
-    final PsiClass resolved = resolveResult.getElement();
-    if (resolved == null || !(GroovyCommonClassNames.GROOVY_LANG_CLOSURE.equals(resolved.getQualifiedName()))) return null;
-
-    final PsiTypeParameter[] typeParameters = resolved.getTypeParameters();
-    if (typeParameters.length != 1) return null;
-
-    final PsiTypeParameter expected = typeParameters[0];
-    final PsiType expectedReturnType = resolveResult.getSubstitutor().substitute(expected);
-    if (expectedReturnType == PsiType.VOID || expectedReturnType == null) return null;
-
-    expectedReturnTypes.add(expectedReturnType);
-  }
-
-  return TypesUtil.getLeastUpperBoundNullable(expectedReturnTypes, closure.getManager());
-}
-
-
   private static class MyCalculator extends GroovyElementVisitor {
     private TypeConstraint[] myResult;
     private final GrExpression myExpression;
@@ -214,7 +188,7 @@
           final GrExpression[] expressionArgs = argumentList == null ? GrExpression.EMPTY_ARRAY : argumentList.getExpressionArguments();
           try {
             final Map<GrExpression, Pair<PsiParameter, PsiType>> map =
-              GrClosureSignatureUtil.mapArgumentsToParameters(variant, methodCall, true, true, namedArgs, expressionArgs, closureArgs);
+              GrClosureSignatureUtil.mapArgumentsToParameters(variant, methodCall, true, false, namedArgs, expressionArgs, closureArgs);
             addConstraintsFromMap(constraints, map);
           }
           catch (RuntimeException e) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java
index 0d15b2b..6d59dd8 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrClosureType.java
@@ -39,7 +39,7 @@
  * @author ven
  */
 public class GrClosureType extends GrLiteralClassType {
-  private final @NotNull GrSignature mySignature;
+  private final GrSignature mySignature;
   private PsiType[] myTypeArgs = null;
 
   private GrClosureType(@NotNull LanguageLevel languageLevel,
@@ -52,21 +52,22 @@
     if (!shouldInferTypeParameters) myTypeArgs = PsiType.EMPTY_ARRAY;
   }
 
+  private GrClosureType(@NotNull LanguageLevel level,
+                        @NotNull GlobalSearchScope scope,
+                        @NotNull JavaPsiFacade facade,
+                        @NotNull GrSignature signature,
+                        @NotNull PsiType[] typeArgs) {
+    super(level, scope, facade);
+
+    mySignature = signature;
+    myTypeArgs = typeArgs;
+  }
+
   @NotNull
   public String getClassName() {
     return "Closure";
   }
 
-  @Override
-  public int getParameterCount() {
-    if (myTypeArgs != null) {
-      return myTypeArgs.length;
-    }
-
-    final PsiClass psiClass = resolve();
-    return psiClass != null && psiClass.getTypeParameters().length == 1 ? 1 : 0;
-  }
-
   @NotNull
   public PsiType[] getParameters() {
     if (myTypeArgs == null) {
@@ -79,8 +80,8 @@
     final PsiClass psiClass = resolve();
     if (psiClass != null && psiClass.getTypeParameters().length == 1) {
       final PsiType type = GrClosureSignatureUtil.getReturnType(mySignature);
-      if (type == PsiType.NULL) {
-        return EMPTY_ARRAY;
+      if (type == PsiType.NULL || type == null) {
+        return new PsiType[]{null};
       }
       else {
         return new PsiType[]{TypesUtil.boxPrimitiveType(type, getPsiManager(), getResolveScope(), true)};
@@ -129,9 +130,7 @@
 
   @NotNull
   public PsiClassType setLanguageLevel(@NotNull final LanguageLevel languageLevel) {
-    final GrClosureType result = create(mySignature, myScope, myFacade, languageLevel, true);
-    result.myTypeArgs = this.myTypeArgs;
-    return result;
+    return new GrClosureType(languageLevel, myScope, myFacade, mySignature, myTypeArgs);
   }
 
   public static GrClosureType create(GroovyResolveResult[] results, GroovyPsiElement context) {
@@ -187,9 +186,7 @@
   public PsiType curry(@NotNull PsiType[] args, int position, @NotNull GroovyPsiElement context) {
     final GrSignature newSignature = mySignature.curry(args, position, context);
     if (newSignature == null) return null;
-    final GrClosureType result = create(newSignature, myScope, myFacade, myLanguageLevel, true);
-    result.myTypeArgs = this.myTypeArgs;
-    return result;
+    return new GrClosureType(myLanguageLevel, myScope, myFacade, newSignature, myTypeArgs);
   }
 
   @NotNull
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java
index 55c8d34..3595f8d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrLiteralClassType.java
@@ -46,20 +46,7 @@
   @NotNull
   public ClassResolveResult resolveGenerics() {
     final PsiClass myBaseClass = resolve();
-    final PsiSubstitutor substitutor;
-    if (myBaseClass != null) {
-      final PsiType[] typeArgs = getParameters();
-      final PsiTypeParameter[] typeParams = myBaseClass.getTypeParameters();
-      if (typeParams.length == typeArgs.length) {
-        substitutor = PsiSubstitutor.EMPTY.putAll(myBaseClass, typeArgs);
-      }
-      else {
-        substitutor = PsiSubstitutor.EMPTY;
-      }
-    }
-    else {
-      substitutor = PsiSubstitutor.EMPTY;
-    }
+    final PsiSubstitutor substitutor = inferSubstitutor(myBaseClass);
 
     return new ClassResolveResult() {
 
@@ -94,6 +81,23 @@
     };
   }
 
+  @NotNull
+  private PsiSubstitutor inferSubstitutor(@Nullable PsiClass myBaseClass) {
+    if (myBaseClass != null) {
+      final PsiType[] typeArgs = getParameters();
+      final PsiTypeParameter[] typeParams = myBaseClass.getTypeParameters();
+      if (typeParams.length == typeArgs.length) {
+        return PsiSubstitutor.EMPTY.putAll(myBaseClass, typeArgs);
+      }
+      else {
+        return PsiSubstitutor.EMPTY.putAll(myBaseClass, new PsiType[typeParams.length]);
+      }
+    }
+    else {
+      return PsiSubstitutor.EMPTY;
+    }
+  }
+
   @Override
   @NotNull
   public abstract String getClassName() ;
@@ -161,7 +165,7 @@
   }
 
   @NotNull
-  protected PsiType getLeastUpperBound(PsiType[] psiTypes) {
+  protected PsiType getLeastUpperBound(PsiType... psiTypes) {
     PsiType result = null;
     final PsiManager manager = getPsiManager();
     for (final PsiType other : psiTypes) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapType.java
index 69f1176..3387f98 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrMapType.java
@@ -37,8 +37,6 @@
  * @author peter
  */
 public class GrMapType extends GrLiteralClassType {
-  private static final PsiType[] RAW_PARAMETERS = new PsiType[]{null, null};
-  
   private final Map<String, PsiType> myStringEntries;
   private final List<Pair<PsiType, PsiType>> myOtherEntries;
   private final String myJavaClassName;
@@ -85,12 +83,6 @@
 
   @NotNull
   @Override
-  public PsiClassType rawType() {
-    return new GrMapType(myFacade, getResolveScope(), Collections.<String, PsiType>emptyMap(), Collections.<Pair<PsiType,PsiType>>emptyList(), getLanguageLevel());
-  }
-
-  @NotNull
-  @Override
   protected String getJavaClassName() {
     return myJavaClassName;
   }
@@ -136,7 +128,7 @@
     final PsiType[] keyTypes = getAllKeyTypes();
     final PsiType[] valueTypes = getAllValueTypes();
     if (keyTypes.length == 0 && valueTypes.length == 0) {
-      return RAW_PARAMETERS;
+      return EMPTY_ARRAY;
     }
 
     return new PsiType[]{getLeastUpperBound(keyTypes), getLeastUpperBound(valueTypes)};
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrRangeType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrRangeType.java
index bdd9368..ed887ff 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrRangeType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrRangeType.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2011 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -18,6 +18,7 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.pom.java.LanguageLevel;
 import com.intellij.psi.JavaPsiFacade;
+import com.intellij.psi.PsiClass;
 import com.intellij.psi.PsiClassType;
 import com.intellij.psi.PsiType;
 import com.intellij.psi.search.GlobalSearchScope;
@@ -38,6 +39,8 @@
   private final PsiType myIterationType;
   private final String myQualifiedName;
 
+  private final PsiType[] myParameters;
+
   public GrRangeType(LanguageLevel languageLevel,
                      GlobalSearchScope scope,
                      JavaPsiFacade facade,
@@ -53,6 +56,8 @@
     else {
       myQualifiedName = GroovyCommonClassNames.GROOVY_LANG_OBJECT_RANGE;
     }
+
+    myParameters = inferParameters();
   }
 
   public GrRangeType(GlobalSearchScope scope, JavaPsiFacade facade, @Nullable PsiType left, @Nullable PsiType right) {
@@ -74,7 +79,16 @@
   @NotNull
   @Override
   public PsiType[] getParameters() {
-    return PsiType.EMPTY_ARRAY;
+    return myParameters;
+  }
+
+  private PsiType[] inferParameters() {
+    if (myIterationType == null) return EMPTY_ARRAY;
+
+    PsiClass resolved = resolve();
+    if (resolved == null || resolved.getTypeParameters().length == 0) return EMPTY_ARRAY;
+
+    return new PsiType[]{myIterationType};
   }
 
   @NotNull
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrSpreadType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrSpreadType.java
deleted file mode 100644
index 99b1556..0000000
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrSpreadType.java
+++ /dev/null
@@ -1,78 +0,0 @@
-/*
- * 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.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-package org.jetbrains.plugins.groovy.lang.psi.impl;
-
-import com.intellij.openapi.project.Project;
-import com.intellij.pom.java.LanguageLevel;
-import com.intellij.psi.JavaPsiFacade;
-import com.intellij.psi.PsiClassType;
-import com.intellij.psi.PsiType;
-import com.intellij.psi.search.GlobalSearchScope;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil;
-
-/**
- * @author Max Medvedev
- */
-public class GrSpreadType extends GrLiteralClassType {
-
-  private PsiType myType;
-
-  public GrSpreadType(PsiType original, PsiType containerType, GlobalSearchScope scope) {
-    this(original, containerType, LanguageLevel.JDK_1_5, scope, JavaPsiFacade.getInstance(scope.getProject()));
-  }
-
-  public GrSpreadType(PsiType original, PsiType containerType, LanguageLevel languageLevel, GlobalSearchScope scope, JavaPsiFacade facade) {
-    super(languageLevel, scope, facade);
-
-    final Project project = facade.getProject();
-    myType = TypesUtil.createSimilarCollection(containerType, project, original);
-  }
-
-  @NotNull
-  @Override
-  protected String getJavaClassName() {
-    return null;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @NotNull
-  @Override
-  public String getClassName() {
-    return null;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @NotNull
-  @Override
-  public PsiType[] getParameters() {
-    return new PsiType[0];  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @NotNull
-  @Override
-  public PsiClassType setLanguageLevel(@NotNull LanguageLevel languageLevel) {
-    return null;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @Override
-  public String getInternalCanonicalText() {
-    return null;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-
-  @Override
-  public boolean isValid() {
-    return false;  //To change body of implemented methods use File | Settings | File Templates.
-  }
-}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTupleType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTupleType.java
index 0be4a66..9d1b305d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTupleType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GrTupleType.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2009 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -31,8 +31,8 @@
  * @author ven
  */
 public class GrTupleType extends GrLiteralClassType {
-  private static final PsiType[] RAW_PARAMETERS = new PsiType[]{null};
   private final PsiType[] myComponentTypes;
+  private final PsiType[] myParameters;
 
   public GrTupleType(PsiType[] componentTypes, JavaPsiFacade facade, GlobalSearchScope scope) {
     this(componentTypes, facade, scope,LanguageLevel.JDK_1_5);
@@ -40,6 +40,8 @@
   public GrTupleType(PsiType[] componentTypes, JavaPsiFacade facade, GlobalSearchScope scope,LanguageLevel languageLevel) {
     super(languageLevel, scope, facade);
     myComponentTypes = componentTypes;
+
+    myParameters = inferParameters();
   }
 
   @NotNull
@@ -49,21 +51,19 @@
   }
 
   @NotNull
-  @Override
-  public PsiClassType rawType() {
-    return new GrTupleType(RAW_PARAMETERS, myFacade, getResolveScope(), getLanguageLevel());
-  }
-
-  @NotNull
   public String getClassName() {
     return StringUtil.getShortName(getJavaClassName());
   }
 
   @NotNull
   public PsiType[] getParameters() {
-    if (myComponentTypes.length == 0) return RAW_PARAMETERS;
+    return myParameters;
+  }
+
+  private PsiType[] inferParameters() {
+    if (myComponentTypes.length == 0) return PsiType.EMPTY_ARRAY;
     final PsiType leastUpperBound = getLeastUpperBound(myComponentTypes);
-    if (leastUpperBound == PsiType.NULL) return RAW_PARAMETERS;
+    if (leastUpperBound == PsiType.NULL) return EMPTY_ARRAY;
     return new PsiType[]{leastUpperBound};
   }
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java
index b59c3ce..e4da17d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/GroovyFileImpl.java
@@ -64,9 +64,7 @@
 import org.jetbrains.plugins.groovy.lang.resolve.processors.ClassHint;
 
 import javax.swing.*;
-import java.util.ArrayList;
 import java.util.Comparator;
-import java.util.List;
 import java.util.concurrent.ConcurrentMap;
 
 import static org.jetbrains.plugins.groovy.editor.GroovyImportHelper.processImplicitImports;
@@ -296,11 +294,12 @@
   }
 
   public GrImportStatement[] getImportStatements() {
-    List<GrImportStatement> result = new ArrayList<GrImportStatement>();
-    for (PsiElement child : getChildren()) {
-      if (child instanceof GrImportStatement) result.add((GrImportStatement)child);
+    final StubElement<?> stub = getStub();
+    if (stub != null) {
+      return stub.getChildrenByType(GroovyElementTypes.IMPORT_STATEMENT, GrImportStatement.ARRAY_FACTORY);
     }
-    return result.toArray(new GrImportStatement[result.size()]);
+
+    return calcTreeElement().getChildrenAsPsiElements(GroovyElementTypes.IMPORT_STATEMENT, GrImportStatement.ARRAY_FACTORY);
   }
 
   @Nullable
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java
index 583ba9b..268f080 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/GrReferenceExpressionImpl.java
@@ -696,9 +696,6 @@
   private static final class OurTypesCalculator implements Function<GrReferenceExpressionImpl, PsiType> {
     @Nullable
     public PsiType fun(GrReferenceExpressionImpl refExpr) {
-      PsiType result = GrReassignedLocalVarsChecker.checkReassignedVar(refExpr, true);
-      if (result != null) return result;
-
       if (GrUnresolvedAccessInspection.isClassReference(refExpr)) {
         GrExpression qualifier = refExpr.getQualifier();
         LOG.assertTrue(qualifier != null);
@@ -706,8 +703,14 @@
       }
 
       final PsiElement resolved = refExpr.resolve();
-      final PsiType inferred = getInferredTypes(refExpr, resolved);
       final PsiType nominal = refExpr.getNominalType();
+
+      Boolean reassigned = GrReassignedLocalVarsChecker.isReassignedVar(refExpr);
+      if (reassigned != null && reassigned.booleanValue()) {
+        return GrReassignedLocalVarsChecker.getReassignedVarType(refExpr, true);
+      }
+
+      final PsiType inferred = getInferredTypes(refExpr, resolved);
       if (inferred == null || PsiType.NULL.equals(inferred)) {
         if (nominal == null) {
           //inside nested closure we could still try to infer from variable initializer. Not sound, but makes sense
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
index b3955ee..ad3219c 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/TypesUtil.java
@@ -913,4 +913,13 @@
     if (!changed) return null;
     return JavaPsiFacade.getElementFactory(project).createType(element, parameters);
   }
+
+  public static boolean isPsiClassTypeToClosure(PsiType type) {
+    if (!(type instanceof PsiClassType)) return false;
+
+    final PsiClass psiClass = ((PsiClassType)type).resolve();
+    if (psiClass == null) return false;
+
+    return GROOVY_LANG_CLOSURE.equals(psiClass.getQualifiedName());
+  }
 }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/DefaultCallExpressionTypeCalculator.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/DefaultCallExpressionTypeCalculator.java
index 7c6c7b9..b8d1ded 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/DefaultCallExpressionTypeCalculator.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/DefaultCallExpressionTypeCalculator.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -109,7 +109,7 @@
     if (type instanceof GrClosureType) {
       returnType = GrClosureSignatureUtil.getReturnType(((GrClosureType)type).getSignature(), callExpression);
     }
-    else if (isPsiClassTypeToClosure(type)) {
+    else if (TypesUtil.isPsiClassTypeToClosure(type)) {
       assert type instanceof PsiClassType;
       final PsiType[] parameters = ((PsiClassType)type).getParameters();
       if (parameters.length == 1) {
@@ -131,15 +131,6 @@
   }
 
 
-  private static boolean isPsiClassTypeToClosure(PsiType type) {
-    if (!(type instanceof PsiClassType)) return false;
-
-    final PsiClass psiClass = ((PsiClassType)type).resolve();
-    if (psiClass == null) return false;
-
-    return GroovyCommonClassNames.GROOVY_LANG_CLOSURE.equals(psiClass.getQualifiedName());
-  }
-
   private static final Set<String> CLOSURE_METHODS = new HashSet<String>();
   static {
     CLOSURE_METHODS.add("call");
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java
index 0de1c35..a50f7ae 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/statements/expressions/path/GrIndexPropertyImpl.java
@@ -420,7 +420,7 @@
     @NotNull
     @Override
     public ResolveResult[] multiResolve(boolean incompleteCode) {
-      return resolveImpl(incompleteCode, null, null);
+      return GrIndexPropertyImpl.this.multiResolve(incompleteCode);
     }
   }
 }
\ No newline at end of file
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/toplevel/imports/GrImportStatementImpl.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/toplevel/imports/GrImportStatementImpl.java
index 0d739b4..6e51ce6 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/toplevel/imports/GrImportStatementImpl.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/impl/toplevel/imports/GrImportStatementImpl.java
@@ -1,5 +1,5 @@
 /*
- * Copyright 2000-2012 JetBrains s.r.o.
+ * Copyright 2000-2013 JetBrains s.r.o.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
@@ -17,13 +17,16 @@
 package org.jetbrains.plugins.groovy.lang.psi.impl.toplevel.imports;
 
 import com.intellij.lang.ASTNode;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.psi.scope.NameHint;
 import com.intellij.psi.scope.PsiScopeProcessor;
+import com.intellij.psi.stubs.IStubElementType;
 import com.intellij.psi.util.CachedValueProvider;
 import com.intellij.psi.util.CachedValuesManager;
 import com.intellij.psi.util.PsiModificationTracker;
 import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.util.ObjectUtils;
 import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -31,10 +34,12 @@
 import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyElementVisitor;
 import org.jetbrains.plugins.groovy.lang.psi.GroovyFile;
+import org.jetbrains.plugins.groovy.lang.psi.GroovyPsiElementFactory;
 import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierList;
 import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement;
 import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
-import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiElementImpl;
+import org.jetbrains.plugins.groovy.lang.psi.impl.GrStubElementBase;
+import org.jetbrains.plugins.groovy.lang.psi.stubs.GrImportStatementStub;
 import org.jetbrains.plugins.groovy.lang.psi.util.GroovyPropertyUtils;
 import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil;
 import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil;
@@ -45,12 +50,22 @@
 /**
  * @author ilyas
  */
-public class GrImportStatementImpl extends GroovyPsiElementImpl implements GrImportStatement {
+public class GrImportStatementImpl extends GrStubElementBase<GrImportStatementStub> implements GrImportStatement, StubBasedPsiElement<GrImportStatementStub> {
 
   public GrImportStatementImpl(@NotNull ASTNode node) {
     super(node);
   }
 
+  public GrImportStatementImpl(GrImportStatementStub stub, IStubElementType nodeType) {
+    super(stub, nodeType);
+  }
+
+
+  @Override
+  public PsiElement getParent() {
+    return getParentByStub();
+  }
+
   public void accept(GroovyElementVisitor visitor) {
     visitor.visitImportStatement(this);
   }
@@ -240,6 +255,16 @@
   }
 
   public GrCodeReferenceElement getImportReference() {
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      String referenceText = stub.getReferenceText();
+      if (referenceText == null) {
+        return null;
+      }
+
+      return GroovyPsiElementFactory.getInstance(getProject()).createCodeReferenceElementFromText(referenceText);
+    }
+
     return (GrCodeReferenceElement)findChildByType(GroovyElementTypes.REFERENCE_ELEMENT);
   }
 
@@ -247,6 +272,20 @@
   public String getImportedName() {
     if (isOnDemand()) return null;
 
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      String name = stub.getAliasName();
+      if (name != null) {
+        return name;
+      }
+
+      String referenceText = stub.getReferenceText();
+      if (referenceText == null) return null;
+
+      return StringUtil.getShortName(referenceText);
+    }
+
+
     PsiElement aliasNameElement = getAliasNameElement();
     if (aliasNameElement != null) {
       return aliasNameElement.getText();
@@ -257,19 +296,36 @@
   }
 
   public boolean isStatic() {
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      return stub.isStatic();
+    }
+
     return findChildByType(GroovyTokenTypes.kSTATIC) != null;
   }
 
   public boolean isAliasedImport() {
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      return stub.getAliasName() != null;
+    }
     return getAliasNameElement() != null;
   }
 
   public boolean isOnDemand() {
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      return stub.isOnDemand();
+    }
     return findChildByType(GroovyTokenTypes.mSTAR) != null;
   }
 
   @NotNull
   public GrModifierList getAnnotationList() {
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      return ObjectUtils.assertNotNull(getStubOrPsiChild(GroovyElementTypes.MODIFIERS));
+    }
     return findNotNullChildByClass(GrModifierList.class);
   }
 
@@ -293,6 +349,15 @@
   @Nullable
   @Override
   public PsiElement getAliasNameElement() {
+    GrImportStatementStub stub = getStub();
+    if (stub != null) {
+      String alias = stub.getAliasName();
+      if (alias == null) return null;
+
+      GrImportStatement imp = GroovyPsiElementFactory.getInstance(getProject()).createImportStatementFromText("import A as " + alias);
+      return imp.getAliasNameElement();
+    }
+
     return findChildByType(GroovyTokenTypes.mIDENT);
   }
 }
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrImportStatementStub.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrImportStatementStub.java
new file mode 100644
index 0000000..dd678bb
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/GrImportStatementStub.java
@@ -0,0 +1,74 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.groovy.lang.psi.stubs;
+
+import com.intellij.psi.stubs.IStubElementType;
+import com.intellij.psi.stubs.StubBase;
+import com.intellij.psi.stubs.StubElement;
+import org.jetbrains.annotations.Nullable;
+import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement;
+
+/**
+ * Created by Max Medvedev on 11/29/13
+ */
+public class GrImportStatementStub extends StubBase<GrImportStatement> implements StubElement<GrImportStatement> {
+  private static final byte STATIC_MASK = 0x1;
+  private static final byte ON_DEMAND_MASK = 0x2;
+
+  private final byte myFlags;
+  private final String myReferenceText;
+  private final String myAliasName;
+
+  public GrImportStatementStub(StubElement parent,
+                               IStubElementType elementType,
+                               @Nullable String referenceText,
+                               @Nullable String aliasName,
+                               byte flags) {
+    super(parent, elementType);
+
+    myFlags = flags;
+
+    myReferenceText = referenceText;
+    myAliasName = aliasName;
+  }
+
+  public static byte buildFlags(boolean isStatic, boolean isOnDemand) {
+    return (byte)((isStatic ? 1 : 0) * STATIC_MASK +
+                  (isOnDemand ? 1 : 0) * ON_DEMAND_MASK);
+  }
+
+  public boolean isStatic() {
+    return (myFlags & STATIC_MASK) != 0;
+  }
+
+  public boolean isOnDemand() {
+    return (myFlags & ON_DEMAND_MASK) != 0;
+  }
+
+  @Nullable
+  public String getReferenceText() {
+    return myReferenceText;
+  }
+
+  @Nullable
+  public String getAliasName() {
+    return myAliasName;
+  }
+
+  public byte getFlags() {
+    return myFlags;
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java
new file mode 100644
index 0000000..6662470
--- /dev/null
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrImportStatementElementType.java
@@ -0,0 +1,71 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.groovy.lang.psi.stubs.elements;
+
+import com.intellij.psi.stubs.StubElement;
+import com.intellij.psi.stubs.StubInputStream;
+import com.intellij.psi.stubs.StubOutputStream;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement;
+import org.jetbrains.plugins.groovy.lang.psi.api.types.GrCodeReferenceElement;
+import org.jetbrains.plugins.groovy.lang.psi.impl.toplevel.imports.GrImportStatementImpl;
+import org.jetbrains.plugins.groovy.lang.psi.stubs.GrImportStatementStub;
+import org.jetbrains.plugins.groovy.lang.psi.stubs.GrStubUtils;
+
+import java.io.IOException;
+
+/**
+ * Created by Max Medvedev on 11/29/13
+ */
+public class GrImportStatementElementType extends GrStubElementType<GrImportStatementStub, GrImportStatement> {
+
+  public GrImportStatementElementType(String debugName) {
+    super(debugName);
+  }
+
+  @Override
+  public GrImportStatement createPsi(@NotNull GrImportStatementStub stub) {
+    return new GrImportStatementImpl(stub, this);
+  }
+
+  @Override
+  public GrImportStatementStub createStub(@NotNull GrImportStatement psi, StubElement parentStub) {
+    GrCodeReferenceElement ref = psi.getImportReference();
+    return new GrImportStatementStub(parentStub,
+                                     this,
+                                     ref != null ? ref.getText() : null,
+                                     psi.isAliasedImport() ? psi.getImportedName() : null,
+                                     GrImportStatementStub.buildFlags(psi.isStatic(), psi.isOnDemand())
+    );
+  }
+
+  @Override
+  public void serialize(@NotNull GrImportStatementStub stub, @NotNull StubOutputStream dataStream) throws IOException {
+    GrStubUtils.writeNullableString(dataStream, stub.getReferenceText());
+    GrStubUtils.writeNullableString(dataStream, stub.getAliasName());
+    dataStream.writeByte(stub.getFlags());
+  }
+
+  @NotNull
+  @Override
+  public GrImportStatementStub deserialize(@NotNull StubInputStream dataStream, StubElement parentStub) throws IOException {
+    String referenceText = GrStubUtils.readNullableString(dataStream);
+    String aliasName = GrStubUtils.readNullableString(dataStream);
+    byte flags = dataStream.readByte();
+
+    return new GrImportStatementStub(parentStub, this, referenceText, aliasName, flags);
+  }
+}
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrStubFileElementType.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrStubFileElementType.java
index 9e888cc..10e803e 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrStubFileElementType.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/stubs/elements/GrStubFileElementType.java
@@ -55,7 +55,7 @@
 
   @Override
   public int getStubVersion() {
-    return super.getStubVersion() + 18;
+    return super.getStubVersion() + 19;
   }
 
   @NotNull
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/ClosureParameterEnhancer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/ClosureParameterEnhancer.java
index 6266c82..c7c1c23 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/ClosureParameterEnhancer.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/typeEnhancers/ClosureParameterEnhancer.java
@@ -84,6 +84,7 @@
     simpleTypes.put("replaceAll", "java.util.regex.Matcher");
     simpleTypes.put("replaceFirst", "java.util.regex.Matcher");
     simpleTypes.put("splitEachLine", "java.util.List<java.lang.String>");
+    simpleTypes.put("withBatch", "groovy.sql.BatchingStatementWrapper");
 
     iterations.add("each");
     iterations.add("any");
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrStringUtil.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrStringUtil.java
index 11348e7..4cc4db12 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrStringUtil.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/lang/psi/util/GrStringUtil.java
@@ -690,6 +690,10 @@
           break;
         default:
           outChars.append('\\').append(c);
+          if (sourceOffsets != null) {
+            sourceOffsets[outChars.length() - outOffset] = index;
+          }
+
       }
     }
     return true;
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java
index aa0eb3e..992b078 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcFramework.java
@@ -226,18 +226,25 @@
 
   public abstract String getUserLibraryName();
 
+  protected abstract boolean isCoreJar(@NotNull VirtualFile localFile);
+
   @Nullable
   protected VirtualFile findCoreJar(@Nullable Module module) {
     if (module == null) return null;
 
     JavaPsiFacade javaFacade = JavaPsiFacade.getInstance(module.getProject());
-    PsiClass aClass = javaFacade.findClass(getSomeFrameworkClass(), GlobalSearchScope.moduleWithLibrariesScope(module));
-    if (aClass == null) return null;
 
-    VirtualFile virtualFile = aClass.getContainingFile().getVirtualFile();
-    if (virtualFile == null || !(virtualFile.getFileSystem() instanceof JarFileSystem)) return null;
+    for (PsiClass aClass : javaFacade.findClasses(getSomeFrameworkClass(), GlobalSearchScope.moduleWithLibrariesScope(module))) {
+      VirtualFile virtualFile = aClass.getContainingFile().getVirtualFile();
+      if (virtualFile != null && virtualFile.getFileSystem() instanceof JarFileSystem) {
+        VirtualFile localFile = PathUtil.getLocalFile(virtualFile);
+        if (isCoreJar(localFile)) {
+          return localFile;
+        }
+      }
+    }
 
-    return PathUtil.getLocalFile(virtualFile);
+    return null;
   }
 
   protected List<File> getImplicitClasspathRoots(@NotNull Module module) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java
index a29e9d3..b2d0257 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/mvc/MvcModuleStructureSynchronizer.java
@@ -349,7 +349,9 @@
     SyncLibrariesInPluginsModule {
       @Override
       void doAction(Module module, MvcFramework framework) {
-        framework.syncSdkAndLibrariesInPluginsModule(module);
+        if (MvcModuleStructureUtil.isEnabledStructureUpdate()) {
+          framework.syncSdkAndLibrariesInPluginsModule(module);
+        }
       }
     },
 
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/navbar/GrNavBarModelExtension.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/navbar/GrNavBarModelExtension.java
index 7285445..71d99c1 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/navbar/GrNavBarModelExtension.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/navbar/GrNavBarModelExtension.java
@@ -49,7 +49,7 @@
   public PsiElement adjustElement(PsiElement psiElement) {
     final ProjectFileIndex index = ProjectRootManager.getInstance(psiElement.getProject()).getFileIndex();
     final PsiFile containingFile = psiElement.getContainingFile();
-    if (containingFile != null) {
+    if (containingFile instanceof GroovyFileBase) {
       final VirtualFile file = containingFile.getVirtualFile();
       if (file != null && (index.isUnderSourceRootOfType(file, JavaModuleSourceRootTypes.SOURCES) || index.isInLibraryClasses(file) || index.isInLibrarySource(file))) {
         if (psiElement instanceof GroovyFileBase) {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrInplaceConstantIntroducer.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrInplaceConstantIntroducer.java
index df6623b..a23723a 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrInplaceConstantIntroducer.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrInplaceConstantIntroducer.java
@@ -16,6 +16,7 @@
 package org.jetbrains.plugins.groovy.refactoring.introduce.constant;
 
 import com.intellij.psi.*;
+import com.intellij.refactoring.JavaRefactoringSettings;
 import com.intellij.refactoring.introduce.inplace.OccurrencesChooser;
 import com.intellij.refactoring.introduceField.IntroduceConstantHandler;
 import com.intellij.ui.components.JBCheckBox;
@@ -164,6 +165,34 @@
     return ((PsiField)getVariable()).getContainingClass();
   }
 
+
+  @Override
+  protected boolean performRefactoring() {
+    JavaRefactoringSettings.getInstance().INTRODUCE_CONSTANT_MOVE_TO_ANOTHER_CLASS = myPanel.isMoveToAnotherClass();
+    if (myPanel.isMoveToAnotherClass()) {
+      try {
+        myEditor.putUserData(INTRODUCE_RESTART, true);
+        myEditor.putUserData(ACTIVE_INTRODUCE, this);
+        final GrIntroduceConstantHandler constantHandler = new GrIntroduceConstantHandler();
+        final PsiLocalVariable localVariable = (PsiLocalVariable)getLocalVariable();
+        constantHandler.getContextAndInvoke(myProject, myEditor, ((GrExpression)myExpr), (GrVariable)localVariable, null);
+      }
+      finally {
+        myEditor.putUserData(INTRODUCE_RESTART, false);
+        myEditor.putUserData(ACTIVE_INTRODUCE, null);
+        releaseResources();
+        if (myLocalMarker != null) {
+          myLocalMarker.dispose();
+        }
+        if (myExprMarker != null) {
+          myExprMarker.dispose();
+        }
+      }
+      return false;
+    }
+    return super.performRefactoring();
+  }
+
   /**
    * Created by Max Medvedev on 8/29/13
    */
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrIntroduceConstantHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrIntroduceConstantHandler.java
index 9d03af8..95db618d 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrIntroduceConstantHandler.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/constant/GrIntroduceConstantHandler.java
@@ -15,6 +15,7 @@
  */
 package org.jetbrains.plugins.groovy.refactoring.introduce.constant;
 
+import com.intellij.openapi.util.Ref;
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.refactoring.HelpID;
@@ -93,9 +94,14 @@
   }
 
   @Override
-  protected GrAbstractInplaceIntroducer<GrIntroduceConstantSettings> getIntroducer(@NotNull GrIntroduceContext context,
-                                                                                   OccurrencesChooser.ReplaceChoice choice) {
-    return new GrInplaceConstantIntroducer(context, choice);
+  protected GrAbstractInplaceIntroducer<GrIntroduceConstantSettings> getIntroducer(@NotNull GrIntroduceContext context, @NotNull OccurrencesChooser.ReplaceChoice choice) {
+    final Ref<GrIntroduceContext> contextRef = Ref.create(context);
+
+    if (context.getStringPart() != null) {
+      extractStringPart(contextRef);
+    }
+
+    return new GrInplaceConstantIntroducer(contextRef.get(), choice);
   }
 
   private static class ConstantChecker extends GroovyRecursiveElementVisitor {
diff --git a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java
index 8392482..50667f1 100644
--- a/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java
+++ b/plugins/groovy/src/org/jetbrains/plugins/groovy/refactoring/introduce/parameter/GrIntroduceParameterHandler.java
@@ -215,14 +215,17 @@
 
     CommandProcessor.getInstance().executeCommand(info.getProject(), new Runnable() {
       public void run() {
-        List<RangeMarker> occurrences = ContainerUtil.newArrayList();
         Document document = context.getEditor().getDocument();
-        for (PsiElement element : context.getOccurrences()) {
-          occurrences.add(createRange(document, element));
+
+        List<RangeMarker> occurrences = ContainerUtil.newArrayList();
+        if (settings.replaceAllOccurrences()) {
+          for (PsiElement element : context.getOccurrences()) {
+            occurrences.add(createRange(document, element));
+          }
         }
-        RangeMarker expressionRangeMarker = createRange(document, context.getExpression());
-        RangeMarker stringPartRangeMarker = createRange(document, context.getStringPart());
-        RangeMarker varRangeMarker = createRange(document, context.getVar());
+        else if (context.getExpression() != null) {
+          occurrences.add(createRange(document, context.getExpression()));
+        }
 
         GrExpressionWrapper expr = new GrExpressionWrapper(GroovyIntroduceParameterUtil.findExpr(settings));
 
@@ -240,8 +243,13 @@
                 false, project);
               GroovyPsiElementFactory factory = GroovyPsiElementFactory.getInstance(project);
 
-              for (PsiElement element : context.getOccurrences()) {
-                element.replace(factory.createReferenceExpressionFromText(name));
+              if (settings.replaceAllOccurrences()) {
+                for (PsiElement element : context.getOccurrences()) {
+                  element.replace(factory.createReferenceExpressionFromText(name));
+                }
+              }
+              else {
+                context.getExpression().replace(factory.createReferenceExpressionFromText(name));
               }
               return SmartPointerManager.getInstance(project).createSmartPsiElementPointer(parameter);
             }
@@ -249,8 +257,7 @@
         GrVariable parameter = pointer != null ? pointer.getElement() : null;
 
         if (parameter != null) {
-          GrInplaceIntroducer introducer = getIntroducer(parameter, context, settings, occurrences, varRangeMarker, expressionRangeMarker, stringPartRangeMarker,
-                                                         expr);
+          GrInplaceIntroducer introducer = getIntroducer(parameter, context, settings, occurrences, expr);
           PsiDocumentManager.getInstance(info.getProject()).doPostponedOperationsAndUnblockDocument(context.getEditor().getDocument());
           introducer.performInplaceRefactoring(introducer.suggestNames(context));
         }
@@ -263,9 +270,6 @@
                                                    GrIntroduceContext context,
                                                    GrIntroduceParameterSettings settings,
                                                    List<RangeMarker> occurrences,
-                                                   RangeMarker varRangeMarker,
-                                                   RangeMarker expressionRangeMarker,
-                                                   RangeMarker stringPartRangeMarker,
                                                    GrExpressionWrapper expr) {
     //return new GrInplaceVariableIntroducer(parameter, context.getEditor(), context.getProject(), REFACTORING_NAME, occurrences, parameter);
     return new GrInplaceParameterIntroducer(parameter, context.getEditor(), context.getProject(), REFACTORING_NAME, occurrences, context.getPlace(), settings, expr);
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy
index f573a25..7ab9a5c 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/completion/GroovyCompletionTest.groovy
@@ -1888,4 +1888,13 @@
 }
 """, "o", CompletionType.BASIC, CompletionResult.equal, 0)
   }
+
+  void testIntellijIdeaRulezzzNotInCompletion() {
+    doVariantableTest('''\
+def foo() {
+  def var
+  va<caret>r = 'abc'
+}
+''', '', CompletionType.BASIC, CompletionResult.notContain, 1, 'vaIntellijIdeaRulezzzr')
+  }
 }
\ No newline at end of file
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GppFunctionalTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GppFunctionalTest.groovy
index 3287b76..39e4703 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GppFunctionalTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GppFunctionalTest.groovy
@@ -405,41 +405,6 @@
     assertEquals 1, multiResolveReference().size()
   }
 
-  public void testGotoSuperConstructorFromLiteralOnsets() throws Exception {
-    PsiClass point = myFixture.addClass("""
-class Point {
-  Point() {}
-  Point(int y) {}
-}""")
-
-    configureGppScript "Point p = <caret>[super: 2]"
-    assertEquals point.constructors[1], resolveReference()
-
-    configureGppScript "Point p = <caret>[2]"
-    assertEquals point.constructors[1], resolveReference()
-
-    configureGppScript "Point p = <caret>[]"
-    assertEquals point.constructors[0], resolveReference()
-
-    configureGppScript "Point p = <caret>[:]"
-    assertEquals point.constructors[0], resolveReference()
-
-    configureGppScript "Point p = <caret>[239, 42]"
-    assertEquals 2, multiResolveReference().size()
-
-    configureGppScript """
-def foo(Point p) {}
-foo(<caret>[2, 3])
-"""
-    assertEquals 2, multiResolveReference().size()
-
-    configureGppScript """
-def foo(Point... p) {}
-foo(<caret>['super':[2, 3]])
-"""
-    assertEquals 2, multiResolveReference().size()
-  }
-
   public void testGotoClassFromLiteralOnsetsWhenNoConstructorsPresent() throws Exception {
     PsiClass point = myFixture.addClass(""" class Point { }""")
     configureGppScript "Point p = <caret>[super: 2]"
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyRegexFindExpressionTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyRegexFindExpressionTest.groovy
index 617dd41..73ea917 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyRegexFindExpressionTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyRegexFindExpressionTest.groovy
@@ -53,4 +53,10 @@
 
     myFixture.checkHighlighting(true, false, true)
   }
+
+  public void testRegex() {
+    myFixture.configureByText('a.groovy', '\'foo\' =~ /\\s/')
+    myFixture.checkHighlighting(true, false, true)
+  }
+
 }
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyStressPerformanceTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyStressPerformanceTest.groovy
index 648617c..6192a38 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyStressPerformanceTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/GroovyStressPerformanceTest.groovy
@@ -135,6 +135,21 @@
     measureHighlighting(defs + text, 10000)
   }
 
+  public void testDeeplyNestedClosuresInCompileStatic() {
+    RecursionManager.assertOnRecursionPrevention(testRootDisposable)
+
+    String text = "println 'hi'"
+    String defs = ""
+    for (i in 1..10) {
+      text = "foo$i {a = 5; $text }"
+      defs += "def foo$i(Closure cl) {}\n"
+    }
+    myFixture.enableInspections(new MissingReturnInspection())
+
+    addCompileStatic()
+    measureHighlighting(defs + "\n @groovy.transform.CompileStatic def compiledStatically() {\ndef a = ''\n" + text + "\n}", 10000)
+  }
+
   public void testDeeplyNestedClosuresInGenericCalls() {
     RecursionManager.assertOnRecursionPrevention(testRootDisposable)
     String text = "println it"
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/LiteralConstructorUsagesTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/LiteralConstructorUsagesTest.groovy
index d24fa7d..f56c2cb 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/LiteralConstructorUsagesTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/LiteralConstructorUsagesTest.groovy
@@ -42,7 +42,7 @@
     myFixture.addFileToProject "a.gpp", "Foo x = []"
     assertOneElement(ReferencesSearch.search(foo.constructors[0]).findAll())
   }
-  
+
   public void testList_ReturnValue() throws Exception {
     def foo = myFixture.addClass("""class Foo {
     Foo() {}
@@ -97,98 +97,6 @@
     assertEquals(2, ReferencesSearch.search(foo.constructors[0]).findAll().size())
   }
 
-  public void testList_GppMethodCall() throws Exception {
-    //------------------------declarations
-    def foo = myFixture.addClass("""
-    package z;
-    class Foo {
-        public Foo() {}
-    }
-    """)
-
-    myFixture.addClass("""
-    package z;
-    public class Bar {
-      public static void giveMeFoo(int a, Foo f) {}
-    }
-""")
-    myFixture.addFileToProject("Decl.groovy", "static def giveMeFooAsWell(z.Foo f) {}")
-
-    //----------------------usages
-    myFixture.addFileToProject "a.gpp", "z.Bar.giveMeFoo(2, []) //usage"
-    myFixture.addFileToProject "b.groovy", """
-      @Typed package aa;
-      z.Bar.giveMeFoo(3, []) //usage
-      """
-    myFixture.addFileToProject "c.groovy", """
-      @Typed def someMethod() {
-        z.Bar.giveMeFoo 4, [] //usage
-        Decl.giveMeFooAsWell([]) //usage
-      }
-      z.Bar.giveMeFoo 5, [] //non-typed context
-      Decl.giveMeFooAsWell([])
-      """
-    myFixture.addFileToProject "invalid.gpp", "z.Bar.giveMeFoo 42, 239, []"
-    myFixture.addFileToProject "nonGpp.groovy", "z.Bar.giveMeFoo(6, [])"
-    assertEquals(4, ReferencesSearch.search(foo.constructors[0]).findAll().size())
-  }
-
-  public void testList_GppConstructorCallWithSeveralParameters() throws Exception {
-    def foo = myFixture.addClass("""
-      class Foo {
-          Foo() {}
-      }
-      """)
-
-    myFixture.addClass("""
-    class Bar {
-      Bar(Foo f1, Foo f2, Foo f3) {}
-    }
-    """)
-    myFixture.addFileToProject "a.gpp", "new Bar([],[],[])"
-    assertEquals(3, ReferencesSearch.search(foo.constructors[0]).findAll().size())
-  }
-
-  public void testMap_GppOverloads() throws Exception {
-    def foo = myFixture.addClass("""
-      class Foo {
-          Foo() {}
-          Foo(int a) {}
-      }
-      """)
-
-    myFixture.addClass("""
-    class Bar {
-      static void foo(Foo f1, Foo f2) {}
-    }
-    """)
-    myFixture.addFileToProject "a.gpp", "Bar.foo([:], [super:2])"
-    assertEquals(1, ReferencesSearch.search(foo.constructors[0]).findAll().size())
-    assertEquals(1, ReferencesSearch.search(foo.constructors[1]).findAll().size())
-  }
-  
-  public void testGppCallVarargs() throws Exception {
-    def foo = myFixture.addClass("""
-      class Foo {
-          Foo() {}
-          Foo(int a) {}
-      }
-      """)
-
-    myFixture.addClass("""
-    class Bar {
-      static void foo(Foo f1, Foo f2) {}
-      static void doo(int a, Foo f1, Foo f2) {}
-    }
-    """)
-    myFixture.addFileToProject "a.gpp", """
-      Bar.foo([:], [super:2])
-      Bar.doo 3, [:], [super:2]
-      """
-    assertEquals(2, ReferencesSearch.search(foo.constructors[0]).findAll().size())
-    assertEquals(2, ReferencesSearch.search(foo.constructors[1]).findAll().size())
-  }
-
   public void testOverloadedConstructorUsages() throws Exception {
     def foo = myFixture.addClass("""
       class Foo {
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy
index 544bbd4..f31fa14 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/formatter/FormatterTest.groovy
@@ -763,7 +763,7 @@
   }
 
   void testGDocAfterImports() { doTest() }
-  void testGDocAfterImports2() { doTest() }
+  void testGroovyDocAfterImports2() { doTest() }
 
   void testRegexExpressions() { doTest() }
 
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy
index 31c881f..edae8f8 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/highlighting/GroovyHighlightingTest.groovy
@@ -576,13 +576,13 @@
 ''')
   }
 
-  void testReassignedVarInClosure() {
+  void testReassignedVarInClosure1() {
     addCompileStatic()
     testHighlighting("""
 $IMPORT_COMPILE_STATIC
 
 @CompileStatic
-test() {
+def test() {
     def var = "abc"
     def cl = {
         var = new Date()
@@ -593,6 +593,65 @@
 """, GrUnresolvedAccessInspection)
   }
 
+  void testReassignedVarInClosure2() {
+    addCompileStatic()
+    testHighlighting("""
+$IMPORT_COMPILE_STATIC
+
+@CompileStatic
+def test() {
+    def cl = {
+        def var
+        var = new Date()
+    }
+    def var = "abc"
+
+    cl()
+    var.toUpperCase()  //no errors
+}
+""", GrUnresolvedAccessInspection)
+  }
+
+  void testReassignedVarInClosure3() {
+    addCompileStatic()
+    testHighlighting("""
+$IMPORT_COMPILE_STATIC
+
+@CompileStatic
+def test() {
+    def var = "abc"
+    def cl = new Closure(this, this){
+      def call() {
+        var = new Date()
+      }
+    }
+    cl()
+    var.toUpperCase() //no errors
+}
+""", GrUnresolvedAccessInspection)
+  }
+
+  void testReassignedVarInClosure4() {
+    addCompileStatic()
+    testHighlighting("""
+$IMPORT_COMPILE_STATIC
+
+class X {
+  def var
+}
+
+@CompileStatic
+def test() {
+    def var = "abc"
+    new X().with {
+        var = new Date()
+    }
+
+    var.<error descr="Cannot resolve symbol 'toUpperCase'">toUpperCase</error>()
+}
+""", GrUnresolvedAccessInspection)
+  }
+
   void testOverrideForVars() {
     testHighlighting('''\
 class S {
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/parser/StatementsParsingTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/parser/StatementsParsingTest.groovy
index f4086fe..e15f174 100644
--- a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/parser/StatementsParsingTest.groovy
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/parser/StatementsParsingTest.groovy
@@ -72,6 +72,7 @@
   public void testFor$for10() throws Throwable { doTest(); }
   public void testFor$for11() throws Throwable { doTest(); }
   public void testFor$for12() throws Throwable { doTest(); }
+  public void testFor$for13() throws Throwable { doTest(); }
   public void testFor$for2() throws Throwable { doTest(); }
   public void testFor$for3() throws Throwable { doTest(); }
   public void testFor$for4() throws Throwable { doTest(); }
@@ -105,7 +106,6 @@
   public void testLoop$while2() throws Throwable { doTest(); }
   public void testLoop$while3() throws Throwable { doTest(); }
   public void testLoop$while4() throws Throwable { doTest(); }
-  public void testLoop$while5() throws Throwable { doTest(); }
   public void testLoop$while6() throws Throwable { doTest(); }
   public void testMethods$method1() throws Throwable { doTest(); }
   public void testMethods$method2() throws Throwable { doTest(); }
diff --git a/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/GrStubAstSwitchTest.groovy b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/GrStubAstSwitchTest.groovy
new file mode 100644
index 0000000..30030f2
--- /dev/null
+++ b/plugins/groovy/test/org/jetbrains/plugins/groovy/lang/psi/GrStubAstSwitchTest.groovy
@@ -0,0 +1,47 @@
+/*
+ * Copyright 2000-2013 JetBrains s.r.o.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.jetbrains.plugins.groovy.lang.psi
+
+import com.intellij.psi.PsiClass
+import com.intellij.testFramework.fixtures.LightCodeInsightFixtureTestCase
+import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyFileImpl
+
+/**
+ * Created by Max Medvedev on 12/4/13
+ */
+class GrStubAstSwitchTest extends LightCodeInsightFixtureTestCase {
+  void testDontLoadContentWhenProcessingImports() {
+    GroovyFileImpl file = (GroovyFileImpl) myFixture.addFileToProject("A.groovy", """
+import java.util.concurrent.ConcurrentHashMap
+
+class MyMap extends ConcurrentHashMap {}
+class B extends ConcurrentHashMap {
+  void foo() {
+    print 4
+  }
+}
+""")
+    assert !file.contentsLoaded
+    PsiClass bClass = file.classes[1]
+    assert !file.contentsLoaded
+
+    def fooMethod = bClass.methods[0]
+    assert !file.contentsLoaded
+
+    fooMethod.findDeepestSuperMethods()
+    assert !file.contentsLoaded
+  }
+}
diff --git a/plugins/groovy/testdata/groovy/formatter/GDocAfterImports2.test b/plugins/groovy/testdata/groovy/formatter/groovyDocAfterImports2.test
similarity index 100%
rename from plugins/groovy/testdata/groovy/formatter/GDocAfterImports2.test
rename to plugins/groovy/testdata/groovy/formatter/groovyDocAfterImports2.test
diff --git a/plugins/groovy/testdata/groovy/stubs/slurper.test b/plugins/groovy/testdata/groovy/stubs/slurper.test
index 5675b9c..7d48d65 100644
--- a/plugins/groovy/testdata/groovy/stubs/slurper.test
+++ b/plugins/groovy/testdata/groovy/stubs/slurper.test
@@ -275,8 +275,10 @@
 [Groovy script]
   [Package definition]
     [Modifiers]
-  [Modifiers]
-  [Modifiers]
+  [Import statement]
+    [Modifiers]
+  [Import statement]
+    [Modifiers]
   [Class definition : ConfigSlurper]
     [Modifiers]
     [Extends clause]
diff --git a/plugins/groovy/testdata/parsing/groovy/statements/for/for13.test b/plugins/groovy/testdata/parsing/groovy/statements/for/for13.test
new file mode 100644
index 0000000..305e2ead
--- /dev/null
+++ b/plugins/groovy/testdata/parsing/groovy/statements/for/for13.test
@@ -0,0 +1,31 @@
+for(i : 5 ?: 5) {
+
+}
+-----
+Groovy script
+  For statement
+    PsiElement(for)('for')
+    PsiElement(()('(')
+    In clause
+      Parameter
+        Modifiers
+          <empty list>
+        PsiElement(identifier)('i')
+      PsiWhiteSpace(' ')
+      PsiElement(:)(':')
+      PsiWhiteSpace(' ')
+      Elvis expression
+        Literal
+          PsiElement(Integer)('5')
+        PsiWhiteSpace(' ')
+        PsiElement(?:)('?:')
+        PsiWhiteSpace(' ')
+        Literal
+          PsiElement(Integer)('5')
+    PsiElement())(')')
+    PsiWhiteSpace(' ')
+    Block statement
+      Open block
+        PsiElement({)('{')
+        PsiWhiteSpace('\n\n')
+        PsiElement(})('}')
\ No newline at end of file
diff --git a/plugins/groovy/testdata/parsing/groovy/statements/loop/while5.test b/plugins/groovy/testdata/parsing/groovy/statements/loop/while5.test
deleted file mode 100644
index f70711c..0000000
--- a/plugins/groovy/testdata/parsing/groovy/statements/loop/while5.test
+++ /dev/null
@@ -1,36 +0,0 @@
-while (def A a = 2+3){doo()}
------
-Groovy script
-  WHILE statement
-    PsiElement(while)('while')
-    PsiWhiteSpace(' ')
-    PsiElement(()('(')
-    Variable definitions
-      Modifiers
-        PsiElement(def)('def')
-      PsiWhiteSpace(' ')
-      Type element
-        Reference element
-          PsiElement(identifier)('A')
-      PsiWhiteSpace(' ')
-      PsiElement(identifier)('a')
-      PsiWhiteSpace(' ')
-      PsiElement(=)('=')
-      PsiWhiteSpace(' ')
-      Additive expression
-        Literal
-          PsiElement(Integer)('2')
-        PsiElement(+)('+')
-        Literal
-          PsiElement(Integer)('3')
-    PsiElement())(')')
-    Block statement
-      Open block
-        PsiElement({)('{')
-        Method call
-          Reference expression
-            PsiElement(identifier)('doo')
-          Arguments
-            PsiElement(()('(')
-            PsiElement())(')')
-        PsiElement(})('}')
\ No newline at end of file
diff --git a/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyList.java b/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyList.java
index f1283b8..8f64cd1 100644
--- a/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyList.java
+++ b/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyList.java
@@ -1,3 +1,3 @@
-java.util.ArrayList<java.lang.Object> list = new java.util.ArrayList<java.lang.Object>();
+java.util.ArrayList list = new java.util.ArrayList();
 java.lang.Integer[] arr = new java.lang.Integer[0];
 java.util.List<java.lang.String> strings = new java.util.ArrayList<java.lang.String>();
diff --git a/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyMap.java b/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyMap.java
index ea2a48f..75eabcd 100644
--- a/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyMap.java
+++ b/plugins/groovy/testdata/refactoring/convertGroovyToJava/codeBlock/emptyMap.java
@@ -1,2 +1,2 @@
-java.util.Map<java.lang.Object, java.lang.Object> map = new java.util.Map<java.lang.Object, java.lang.Object>();
+java.util.Map map = new java.util.Map();
 print(map.get(1));
diff --git a/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/dynamicMethodsAccess.java b/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/dynamicMethodsAccess.java
index 61cfcc9..6a5310f 100644
--- a/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/dynamicMethodsAccess.java
+++ b/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/dynamicMethodsAccess.java
@@ -8,7 +8,7 @@
 org.codehaus.groovy.runtime.DefaultGroovyMethods.invokeMethod(s, "bar", new java.lang.Object[]{4});
 org.codehaus.groovy.runtime.DefaultGroovyMethods.print(this, org.codehaus.groovy.runtime.DefaultGroovyMethods.invokeMethod(s, "bar", new java.lang.Object[]{5}));
 
-return org.codehaus.groovy.runtime.DefaultGroovyMethods.invokeMethod(s, "anme", new java.util.ArrayList<java.lang.Object>());
+return org.codehaus.groovy.runtime.DefaultGroovyMethods.invokeMethod(s, "anme", new java.util.ArrayList());
 }
 
 }
diff --git a/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/reflectedMethodWithEllipsis.java b/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/reflectedMethodWithEllipsis.java
index 3abffed..6ae1849 100644
--- a/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/reflectedMethodWithEllipsis.java
+++ b/plugins/groovy/testdata/refactoring/convertGroovyToJava/file/reflectedMethodWithEllipsis.java
@@ -2,7 +2,7 @@
 public void foo(java.util.Map args, java.lang.String a, java.lang.String... b) {}
 
 public void foo(java.lang.String a, java.lang.String... b) {
-foo(new java.util.LinkedHashMap<java.lang.Object, java.lang.Object>(), a, b);
+foo(new java.util.LinkedHashMap(), a, b);
 }
 
 }
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgLogCommand.java b/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgLogCommand.java
index 3a3c644..484aadc 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgLogCommand.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/command/HgLogCommand.java
@@ -240,8 +240,8 @@
   }
 
   @Nullable
-  private HgCommandResult execute(@NotNull VirtualFile repo, @NotNull String template, int limit, HgFile hgFile,
-                                  @Nullable List<String> argsForCmd) {
+  public HgCommandResult execute(@NotNull VirtualFile repo, @NotNull String template, int limit, HgFile hgFile,
+                                 @Nullable List<String> argsForCmd) {
     List<String> arguments = new LinkedList<String>();
     if (myIncludeRemoved) {
       // There is a bug in mercurial that causes --follow --removed <file> to cause
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java b/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java
index ebb8842..388456c 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/log/HgLogProvider.java
@@ -123,7 +123,7 @@
     }
     String currentRevision = repository.getCurrentRevision();
     if (currentRevision != null) { // null => fresh repository
-      refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(currentRevision), "HEAD", HgRefManager.HEAD, root));
+      refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(currentRevision), "tip", HgRefManager.HEAD, root));
     }
     for (HgNameWithHashInfo tagInfo : tags) {
       refs.add(myVcsObjectsFactory.createRef(myVcsObjectsFactory.createHash(tagInfo.getHash()), tagInfo.getName(), HgRefManager.TAG, root));
@@ -239,6 +239,12 @@
     return userName == null ? null : myVcsObjectsFactory.createUser(userArgs.get(0), userArgs.get(1));
   }
 
+  @NotNull
+  @Override
+  public Collection<String> getContainingBranches(@NotNull VirtualFile root, @NotNull Hash commitHash) throws VcsException {
+    return HgHistoryUtil.getDescendingHeadsOfBranches(myProject, root, commitHash);
+  }
+
   private static String prepareParameter(String paramName, String value) {
     return "--" + paramName + "=" + value; // no value escaping needed, because the parameter itself will be quoted by GeneralCommandLine
   }
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryImpl.java b/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryImpl.java
index b786ae4..c95eb59 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryImpl.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryImpl.java
@@ -154,7 +154,7 @@
 
   @NotNull
   private HgRepoInfo readRepoInfo() {
-    myIsFresh = myIsFresh && myReader.checkIsFresh();
+    myIsFresh = myIsFresh && myReader.isFresh();
     //in GitRepositoryImpl there are temporary state object for reader fields storing! Todo Check;
     return
       new HgRepoInfo(myReader.readCurrentBranch(), myReader.readCurrentRevision(), myReader.readState(), myReader.readBranches(),
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java b/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java
index aaf7fb5..bed7480 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/repo/HgRepositoryReader.java
@@ -24,6 +24,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.zmlx.hg4idea.HgNameWithHashInfo;
+import org.zmlx.hg4idea.HgVcs;
 
 import java.io.File;
 import java.util.*;
@@ -42,7 +43,8 @@
   private static Pattern HASH_NAME = Pattern.compile("\\s*([0-9a-fA-F]+)\\s+(.+)");
 
   @NotNull private final File myHgDir;            // .hg
-  @NotNull private final File myBranchHeadsFile;  // .hg/cache/branchheads (does not exist before first commit)
+  @NotNull private final File myBranchHeadsFile;  // .hg/cache/branchheads
+  @NotNull private final File myCacheDir; // .hg/cache (does not exist before first commit)
   @NotNull private final File myCurrentBranch;    // .hg/branch
   @NotNull private final File myBookmarksFile; //.hg/bookmarks
   @NotNull private final File myCurrentBookmark; //.hg/bookmarks.current
@@ -53,9 +55,8 @@
   public HgRepositoryReader(@NotNull Project project, @NotNull File hgDir) {
     myHgDir = hgDir;
     RepositoryUtil.assertFileExists(myHgDir, ".hg directory not found in " + myHgDir);
-    File branchesFile = new File(new File(myHgDir, "cache"), "branchheads-served");  //branchheads-served exist after mercurial 2.5,
-    //before 2.5 only branchheads exist
-    myBranchHeadsFile = branchesFile.exists() ? branchesFile : new File(new File(myHgDir, "cache"), "branchheads");
+    myCacheDir = new File(myHgDir, "cache");
+    myBranchHeadsFile = identifyBranchHeadFile(project, myCacheDir);
     myCurrentBranch = new File(myHgDir, "branch");
     myBookmarksFile = new File(myHgDir, "bookmarks");
     myCurrentBookmark = new File(myHgDir, "bookmarks.current");
@@ -65,13 +66,28 @@
   }
 
   /**
+   * Identify file with branches and heads information depends on hg version;
+   *
+   * @param project
+   * @param parentCacheFile
+   * @return
+   */
+  @NotNull
+  private static File identifyBranchHeadFile(@NotNull Project project, @NotNull File parentCacheFile) {
+    File branchesFile = new File(parentCacheFile, "branchheads-served");  //branchheads-served exist after mercurial 2.5,
+    //before 2.5 only branchheads exist
+    HgVcs vcs = HgVcs.getInstance(project);
+    return vcs != null && vcs.getVersion().hasBranchHeadsServed() ? branchesFile : new File(parentCacheFile, "branchheads");
+  }
+
+  /**
    * Finds current revision value.
    *
    * @return The current revision hash, or <b>{@code null}</b> if current revision is unknown - it is the initial repository state.
    */
   @Nullable
   public String readCurrentRevision() {
-    if (checkIsFresh()) return null;
+    if (!isBranchInfoAvailable()) return null;
     String[] branchesWithHeads = RepositoryUtil.tryLoadFile(myBranchHeadsFile).split("\n");
     String head = branchesWithHeads[0];
     Matcher matcher = HASH_NAME.matcher(head);
@@ -81,6 +97,10 @@
     return null;
   }
 
+  private boolean isBranchInfoAvailable() {
+    return !isFresh() && myBranchHeadsFile.exists();
+  }
+
   /**
    * Return current branch
    */
@@ -93,7 +113,7 @@
   public Collection<HgNameWithHashInfo> readBranches() {
     List<HgNameWithHashInfo> branches = new ArrayList<HgNameWithHashInfo>();
     // Set<String> branchNames = new HashSet<String>();
-    if (!checkIsFresh()) {
+    if (isBranchInfoAvailable()) {
       String[] branchesWithHeads = RepositoryUtil.tryLoadFile(myBranchHeadsFile).split("\n");
       // first one - is a head revision: head hash + head number;
       for (int i = 1; i < branchesWithHeads.length; ++i) {
@@ -118,8 +138,8 @@
     return isMergeInProgress() ? Repository.State.MERGING : Repository.State.NORMAL;
   }
 
-  public boolean checkIsFresh() {
-    return !myBranchHeadsFile.exists();
+  public boolean isFresh() {
+    return !myCacheDir.exists();
   }
 
   public boolean branchExist() {
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgHistoryUtil.java b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgHistoryUtil.java
index 8e2fb64..7deafd2 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgHistoryUtil.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgHistoryUtil.java
@@ -34,6 +34,7 @@
 import org.zmlx.hg4idea.action.HgCommandResultNotifier;
 import org.zmlx.hg4idea.command.HgLogCommand;
 import org.zmlx.hg4idea.execution.HgCommandException;
+import org.zmlx.hg4idea.execution.HgCommandResult;
 import org.zmlx.hg4idea.log.HgContentRevisionFactory;
 import org.zmlx.hg4idea.provider.HgCommittedChangeList;
 
@@ -206,4 +207,29 @@
     //todo change ugly style
     return new String[]{"--rev", builder.toString()};
   }
+
+  @NotNull
+  public static Collection<String> getDescendingHeadsOfBranches(@NotNull Project project, @NotNull VirtualFile root, @NotNull Hash hash)
+    throws VcsException {
+    //hg log -r "descendants(659db54c1b6865c97c4497fa867194bcd759ca76) and head() " --template "{branch} {bookmarks}\n"
+    Set<String> branchHeads = new HashSet<String>();
+    List<String> params = new ArrayList<String>();
+    params.add("-r");
+    params.add("descendants(" + hash.asString() + ") and head()");
+    HgFile hgFile = new HgFile(root, VcsUtil.getFilePath(root.getPath()));
+    HgLogCommand hgLogCommand = new HgLogCommand(project);
+    hgLogCommand.setLogFile(false);
+    String template = HgChangesetUtil.makeTemplate("{branch}", "{bookmarks}");
+    HgCommandResult logResult = hgLogCommand.execute(root, template, -1, hgFile, params);
+    if (logResult == null || logResult.getExitValue() != 0) {
+      throw new VcsException("Couldn't get commit details: log command execution error.");
+    }
+    String output = logResult.getRawOutput();
+    String[] changeSets = output.split(HgChangesetUtil.CHANGESET_SEPARATOR);
+    for (String line : changeSets) {
+      String[] attributes = line.split(HgChangesetUtil.ITEM_SEPARATOR);
+      branchHeads.addAll(Arrays.asList(attributes));
+    }
+    return branchHeads;
+  }
 }
diff --git a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java
index 5e758f5..c869ffd 100644
--- a/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java
+++ b/plugins/hg4idea/src/org/zmlx/hg4idea/util/HgVersion.java
@@ -48,6 +48,7 @@
   // since 2.3 - 2.5.3 hg has bug with join function with file_copies
   // see http://mercurial.808500.n3.nabble.com/Bug-3887-New-hg-log-template-quot-rev-join-file-copies-n-quot-prints-literal-quot-sourcename-quot-fos-td4000129.html
   public static final HgVersion BUILT_IN_FUNCTION_SUPPORTED = new HgVersion(2, 6, 0);
+  public static final HgVersion BRANCH_HEADS_SERVED_FILE_EXIST = new HgVersion(2, 5, 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);
@@ -123,6 +124,10 @@
   public boolean isLargeFilesWithFollowSupported() {
     return !isNull() && compareTo(LARGEFILES_WITH_FOLLOW_SUPPORTED) >= 0;
   }
+  
+  public boolean hasBranchHeadsServed() {
+    return !isNull() && compareTo(BRANCH_HEADS_SERVED_FILE_EXIST) >= 0;
+  }
 
   /**
    * Note: this class has a natural ordering that is inconsistent with equals.
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/HgPlatformTest.java b/plugins/hg4idea/testSrc/hg4idea/test/HgPlatformTest.java
index 95c834c..1b4519a8 100644
--- a/plugins/hg4idea/testSrc/hg4idea/test/HgPlatformTest.java
+++ b/plugins/hg4idea/testSrc/hg4idea/test/HgPlatformTest.java
@@ -55,6 +55,7 @@
   protected VirtualFile myProjectRoot;
   protected VirtualFile myRepository;
   protected VirtualFile myChildRepo;
+  protected HgVcs myVcs;
 
   protected static final String COMMIT_MESSAGE = "text";
 
@@ -79,9 +80,10 @@
     hg("version");
 
     createRepository(myProjectRoot);
-    HgVcs hgVcs = HgVcs.getInstance(myProject);
-    assertNotNull(hgVcs);
-    hgVcs.getGlobalSettings().setHgExecutable(HgExecutor.getHgExecutable());
+    myVcs = HgVcs.getInstance(myProject);
+    assertNotNull(myVcs);
+    myVcs.getGlobalSettings().setHgExecutable(HgExecutor.getHgExecutable());
+    myVcs.checkVersion();
     myRepository = myProjectRoot;
     setUpHgrc(myRepository);
   }
diff --git a/plugins/hg4idea/testSrc/hg4idea/test/history/HgLogHistoryTest.java b/plugins/hg4idea/testSrc/hg4idea/test/history/HgLogHistoryTest.java
new file mode 100644
index 0000000..3c215ae
--- /dev/null
+++ b/plugins/hg4idea/testSrc/hg4idea/test/history/HgLogHistoryTest.java
@@ -0,0 +1,76 @@
+/*
+ * 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 hg4idea.test.history;
+
+import com.intellij.openapi.vcs.VcsException;
+import com.intellij.openapi.vcs.VcsTestUtil;
+import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.vcs.log.Hash;
+import com.intellij.vcs.log.impl.HashImpl;
+import hg4idea.test.HgPlatformTest;
+import org.jetbrains.annotations.NotNull;
+import org.zmlx.hg4idea.util.HgHistoryUtil;
+
+import java.util.Arrays;
+import java.util.Collection;
+
+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.hg;
+
+/**
+ * @author Nadya Zabrodina
+ */
+public class HgLogHistoryTest extends HgPlatformTest {
+
+  @Override
+  public void setUp() throws Exception {
+    super.setUp();
+    createBookmarksAndBranches(myRepository);
+  }
+
+  public void testContainedInBranchesInLogInfos() throws VcsException {
+    Hash testHashForFirstCommit = HashImpl.build("0");
+    Collection<String> branches = HgHistoryUtil.getDescendingHeadsOfBranches(myProject, myRepository, testHashForFirstCommit);
+    //B_Bookmark should not be listed - it is inactive and not head//
+    VcsTestUtil.assertEqualCollections(branches, Arrays.asList("default", "branchA", "branchB", "A_BookMark", "C_BookMark"));
+  }
+
+  private static void createBookmarksAndBranches(@NotNull VirtualFile repositoryRoot) {
+    cd(repositoryRoot);
+    hg("bookmark A_BookMark");
+    hg("tag tag1");
+    String aFile = "A.txt";
+    touch(aFile, "base");
+    hg("add " + aFile);
+    hg("commit -m 'create file'");
+    hg("branch branchA");
+    hg("tag tag2");
+    echo(aFile, " modify with a");
+    hg("commit -m 'create branchA'");
+    hg("bookmark B_BookMark --inactive");
+    echo(aFile, " modify with AA");
+    hg("commit -m 'modify branchA'");
+    hg("up default");
+    hg("branch branchB");
+    hg("tag -l localTag");
+    echo(aFile, " modify with b");
+    hg("commit -m 'modify file in branchB'");
+    hg("bookmark C_BookMark");
+    hg("up branchA");
+  }
+}
diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java
index a176b9c..0123556 100644
--- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java
+++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/AbstractJavaFxPackager.java
@@ -18,6 +18,7 @@
 import com.intellij.execution.CommandLineUtil;
 import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.ArrayUtilRt;
@@ -358,4 +359,6 @@
   public abstract String getPreloaderJar();
 
   public abstract boolean convertCss2Bin();
+
+  public abstract List<JavaFxManifestAttribute> getCustomManifestAttributes();
 }
diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java
index e9f50e7..7ebe629 100644
--- a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java
+++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxAntGenerator.java
@@ -106,7 +106,18 @@
     createJarTag.add(new SimpleTag("fileset", fileset2Jar.toArray(new Pair[fileset2Jar.size()])));
 
     createJarTag.add(createResourcesTag(preloaderFiles, false, allButPreloader, allButSelf, all));
-    
+
+    List<JavaFxManifestAttribute> manifestAttributes = packager.getCustomManifestAttributes();
+    if (manifestAttributes != null) {
+      final SimpleTag manifestTag = new SimpleTag("manifest");
+      for (JavaFxManifestAttribute pair : manifestAttributes) {
+        manifestTag.add(new SimpleTag("attribute", 
+                                      new Pair<String, String>("name", pair.getName()), 
+                                      new Pair<String, String>("value", pair.getValue())));
+      }
+      createJarTag.add(manifestTag);
+    }
+
     topLevelTagsCollector.add(createJarTag);
 
     //deploy task
diff --git a/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxManifestAttribute.java b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxManifestAttribute.java
new file mode 100644
index 0000000..52706a2
--- /dev/null
+++ b/plugins/javaFX/common-javaFX-plugin/src/org/jetbrains/plugins/javaFX/packaging/JavaFxManifestAttribute.java
@@ -0,0 +1,50 @@
+package org.jetbrains.plugins.javaFX.packaging;
+
+public class JavaFxManifestAttribute {
+  private String myName;
+  private String myValue;
+
+  public JavaFxManifestAttribute() {
+  }
+
+  public JavaFxManifestAttribute(String name, String value) {
+    myName = name;
+    myValue = value;
+  }
+
+  public String getName() {
+    return myName;
+  }
+
+  public void setName(String name) {
+    myName = name;
+  }
+
+  public String getValue() {
+    return myValue;
+  }
+
+  public void setValue(String value) {
+    myValue = value;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    if (this == o) return true;
+    if (o == null || getClass() != o.getClass()) return false;
+
+    JavaFxManifestAttribute attribute = (JavaFxManifestAttribute)o;
+
+    if (!myName.equals(attribute.myName)) return false;
+    if (!myValue.equals(attribute.myValue)) return false;
+
+    return true;
+  }
+
+  @Override
+  public int hashCode() {
+    int result = myName.hashCode();
+    result = 31 * result + myValue.hashCode();
+    return result;
+  }
+}
diff --git a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java
index ac4dc59..1003d26 100644
--- a/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java
+++ b/plugins/javaFX/javaFX-CE/testSrc/org/jetbrains/plugins/javaFX/packaging/JavaFxAntTaskTest.java
@@ -15,6 +15,7 @@
  */
 package org.jetbrains.plugins.javaFX.packaging;
 
+import com.intellij.openapi.util.Pair;
 import com.intellij.testFramework.UsefulTestCase;
 
 import java.io.File;
@@ -215,6 +216,7 @@
     private String myPreloaderJar;
     private boolean myConvertCss2Bin;
     private boolean mySigned;
+    private List<JavaFxManifestAttribute> myCustomManifestAttributes;
 
     private MockJavaFxPackager(String outputPath) {
       myOutputPath = outputPath;
@@ -365,5 +367,10 @@
     public boolean convertCss2Bin() {
       return myConvertCss2Bin;
     }
+
+    @Override
+    public List<JavaFxManifestAttribute> getCustomManifestAttributes() {
+      return myCustomManifestAttributes;
+    }
   }
 }
diff --git a/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java b/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java
index 06148e7..2acbf76 100644
--- a/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java
+++ b/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactBuildTaskProvider.java
@@ -31,6 +31,7 @@
 import org.jetbrains.jps.model.library.sdk.JpsSdk;
 import org.jetbrains.jps.model.library.sdk.JpsSdkType;
 import org.jetbrains.plugins.javaFX.packaging.AbstractJavaFxPackager;
+import org.jetbrains.plugins.javaFX.packaging.JavaFxManifestAttribute;
 import org.jetbrains.plugins.javaFX.packaging.JavaFxPackagerConstants;
 import org.jetbrains.plugins.javaFX.preloader.JpsJavaFxPreloaderArtifactProperties;
 import org.jetbrains.plugins.javaFX.preloader.JpsJavaFxPreloaderArtifactType;
@@ -237,6 +238,11 @@
       return myProperties.myState.isConvertCss2Bin();
     }
 
+    @Override
+    public List<JavaFxManifestAttribute> getCustomManifestAttributes() {
+      return myProperties.myState.getCustomManifestAttributes();
+    }
+
     private JpsArtifact getPreloaderArtifact() {
       for (JpsPackagingElement element : myArtifact.getRootElement().getChildren()) {
         if (element instanceof JpsArtifactOutputPackagingElement) {
diff --git a/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactProperties.java b/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactProperties.java
index 14c9e25..34e3855 100644
--- a/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactProperties.java
+++ b/plugins/javaFX/javaFX-jps-plugin/src/org/jetbrains/plugins/javaFX/JpsJavaFxArtifactProperties.java
@@ -2,8 +2,12 @@
 
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.jps.model.ex.JpsElementBase;
+import org.jetbrains.plugins.javaFX.packaging.JavaFxManifestAttribute;
 import org.jetbrains.plugins.javaFX.packaging.JavaFxPackagerConstants;
 
+import java.util.ArrayList;
+import java.util.List;
+
 /**
  * User: anna
  * Date: 3/13/13
@@ -36,6 +40,7 @@
     myState.setAlias(state.myAlias);
     myState.setConvertCss2Bin(state.myConvertCss2Bin);
     myState.setNativeBundle(state.myNativeBundle);
+    myState.setCustomManifestAttributes(state.myCustomManifestAttributes);
   }
 
   @NotNull
@@ -67,6 +72,7 @@
     private String myKeypass;
     private boolean myConvertCss2Bin;
     public JavaFxPackagerConstants.NativeBundles myNativeBundle = JavaFxPackagerConstants.NativeBundles.none;
+    private List<JavaFxManifestAttribute> myCustomManifestAttributes = new ArrayList<JavaFxManifestAttribute>();
 
     public String getTitle() {
       return myTitle;
@@ -203,5 +209,13 @@
     public void setNativeBundle(JavaFxPackagerConstants.NativeBundles nativeBundle) {
       myNativeBundle = nativeBundle;
     }
+
+    public List<JavaFxManifestAttribute> getCustomManifestAttributes() {
+      return myCustomManifestAttributes;
+    }
+
+    public void setCustomManifestAttributes(List<JavaFxManifestAttribute> customManifestAttributes) {
+      myCustomManifestAttributes = customManifestAttributes;
+    }
   }
 }
diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java
index d3227b9..33f41a1 100644
--- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java
+++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactProperties.java
@@ -25,6 +25,7 @@
 import com.intellij.openapi.projectRoots.Sdk;
 import com.intellij.openapi.roots.ModuleRootManager;
 import com.intellij.openapi.util.Computable;
+import com.intellij.openapi.util.Pair;
 import com.intellij.packaging.artifacts.Artifact;
 import com.intellij.packaging.artifacts.ArtifactManager;
 import com.intellij.packaging.artifacts.ArtifactProperties;
@@ -35,6 +36,7 @@
 import com.intellij.packaging.ui.ArtifactEditorContext;
 import com.intellij.packaging.ui.ArtifactPropertiesEditor;
 import com.intellij.util.xmlb.XmlSerializerUtil;
+import com.intellij.util.xmlb.annotations.Tag;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.plugins.javaFX.packaging.preloader.JavaFxPreloaderArtifactProperties;
@@ -42,7 +44,9 @@
 import org.jetbrains.plugins.javaFX.packaging.preloader.JavaFxPreloaderArtifactType;
 
 import java.io.File;
+import java.util.ArrayList;
 import java.util.Collections;
+import java.util.List;
 import java.util.Set;
 
 /**
@@ -69,6 +73,7 @@
   private String myKeypass;
   private boolean myConvertCss2Bin;
   private String myNativeBundle = JavaFxPackagerConstants.NativeBundles.none.name();
+  private List<JavaFxManifestAttribute> myCustomManifestAttributes = new ArrayList<JavaFxManifestAttribute>();
 
   @Override
   public void onBuildFinished(@NotNull final Artifact artifact, @NotNull final CompileContext compileContext) {
@@ -298,6 +303,14 @@
     myNativeBundle = nativeBundle;
   }
 
+  public List<JavaFxManifestAttribute> getCustomManifestAttributes() {
+    return myCustomManifestAttributes;
+  }
+
+  public void setCustomManifestAttributes(List<JavaFxManifestAttribute> customManifestAttributes) {
+    myCustomManifestAttributes = customManifestAttributes;
+  }
+
   public static abstract class JavaFxPackager extends AbstractJavaFxPackager {
     private final Artifact myArtifact;
     private final JavaFxArtifactProperties myProperties;
@@ -423,5 +436,10 @@
     public boolean isEnabledSigning() {
       return myProperties.isEnabledSigning();
     }
+
+    @Override
+    public List<JavaFxManifestAttribute> getCustomManifestAttributes() {
+      return myProperties.getCustomManifestAttributes();
+    }
   }
 }
diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.form b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.form
index f32f1a7..be0f538 100644
--- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.form
+++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.form
@@ -3,12 +3,12 @@
   <grid id="27dc6" binding="myWholePanel" 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>
-      <xy x="20" y="20" width="500" height="400"/>
+      <xy x="20" y="20" width="500" height="422"/>
     </constraints>
     <properties/>
     <border type="none"/>
     <children>
-      <grid id="ca833" layout-manager="GridLayoutManager" row-count="12" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+      <grid id="ca833" layout-manager="GridLayoutManager" row-count="13" 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="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"/>
@@ -215,6 +215,37 @@
             </constraints>
             <properties/>
           </component>
+          <component id="7d6a7" class="javax.swing.JLabel">
+            <constraints>
+              <grid row="12" 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>
+            <properties>
+              <text value="Custom manifest attributes"/>
+            </properties>
+          </component>
+          <grid id="cd6c2" 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="12" column="1" 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"/>
+            <children>
+              <component id="bacf3" class="javax.swing.JButton" binding="myEditAttributesButton" default-binding="true">
+                <constraints>
+                  <grid row="0" column="0" row-span="1" col-span="1" vsize-policy="0" hsize-policy="0" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+                </constraints>
+                <properties>
+                  <text value="Edit  Attributes"/>
+                </properties>
+              </component>
+              <hspacer id="20f71">
+                <constraints>
+                  <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="1" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+                </constraints>
+              </hspacer>
+            </children>
+          </grid>
         </children>
       </grid>
       <vspacer id="1a12e">
diff --git a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.java b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.java
index f802e6d..0006db9 100644
--- a/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.java
+++ b/plugins/javaFX/src/org/jetbrains/plugins/javaFX/packaging/JavaFxArtifactPropertiesEditor.java
@@ -15,21 +15,27 @@
  */
 package org.jetbrains.plugins.javaFX.packaging;
 
+import com.intellij.execution.util.ListTableWithButtons;
 import com.intellij.openapi.fileChooser.FileChooserDescriptor;
 import com.intellij.openapi.fileChooser.FileChooserDescriptorFactory;
 import com.intellij.openapi.fileTypes.StdFileTypes;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.ui.DialogWrapper;
 import com.intellij.openapi.ui.TextFieldWithBrowseButton;
 import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.packaging.artifacts.Artifact;
 import com.intellij.packaging.ui.ArtifactPropertiesEditor;
 import com.intellij.util.ArrayUtil;
 import com.intellij.util.Base64Converter;
+import com.intellij.util.ui.ColumnInfo;
+import com.intellij.util.ui.ListTableModel;
 import org.jetbrains.annotations.Nullable;
 
 import javax.swing.*;
 import javax.swing.text.JTextComponent;
+import java.awt.*;
 import java.awt.event.ActionEvent;
 import java.awt.event.ActionListener;
 import java.util.ArrayList;
@@ -56,7 +62,10 @@
   private JButton myEditSignCertificateButton;
   private JCheckBox myConvertCssToBinCheckBox;
   private JComboBox myNativeBundleCB;
+  private JButton myEditAttributesButton;
   private JavaFxEditCertificatesDialog myDialog;
+  private CustomManifestAttributesDialog myManifestAttributesDialog;
+  private List<JavaFxManifestAttribute> myCustomManifestAttributes;
 
   public JavaFxArtifactPropertiesEditor(JavaFxArtifactProperties properties, final Project project, Artifact artifact) {
     super();
@@ -79,6 +88,17 @@
       }
     });
 
+    myEditAttributesButton.addActionListener(new ActionListener() {
+      @Override
+      public void actionPerformed(ActionEvent e) {
+        myManifestAttributesDialog = new CustomManifestAttributesDialog(myWholePanel, myCustomManifestAttributes);
+        myManifestAttributesDialog.show();
+        if (myManifestAttributesDialog.isOK()) {
+          myCustomManifestAttributes = myManifestAttributesDialog.getAttrs();
+        }
+      }
+    });
+
     final List<String> bundleNames = new ArrayList<String>();
     for (JavaFxPackagerConstants.NativeBundles bundle : JavaFxPackagerConstants.NativeBundles.values()) {
       bundleNames.add(bundle.name());
@@ -121,13 +141,17 @@
       if (isModified(storepass != null ? Base64Converter.decode(storepass) : "", myDialog.myPanel.myStorePassTF)) return true;
       if (myProperties.isSelfSigning() != myDialog.myPanel.mySelfSignedRadioButton.isSelected()) return true;
     }
+
+    if (myManifestAttributesDialog != null) {
+      if (!Comparing.equal(myManifestAttributesDialog.getAttrs(), myProperties.getCustomManifestAttributes())) return true;
+    }
     return false;
   }
 
   private static boolean isModified(final String title, JTextComponent tf) {
     return !Comparing.strEqual(title, tf.getText().trim());
   }
-  
+
   private static boolean isModified(final String title, TextFieldWithBrowseButton tf) {
     return !Comparing.strEqual(title, tf.getText().trim());
   }
@@ -142,7 +166,7 @@
     myProperties.setHeight(myHeightTF.getText());
     myProperties.setHtmlParamFile(myHtmlParams.getText());
     myProperties.setParamFile(myParams.getText());
-    myProperties.setUpdateMode(myUpdateInBackgroundCB.isSelected() ? JavaFxPackagerConstants.UPDATE_MODE_BACKGROUND 
+    myProperties.setUpdateMode(myUpdateInBackgroundCB.isSelected() ? JavaFxPackagerConstants.UPDATE_MODE_BACKGROUND
                                                                    : JavaFxPackagerConstants.UPDATE_MODE_ALWAYS);
     myProperties.setEnabledSigning(myEnableSigningCB.isSelected());
     myProperties.setConvertCss2Bin(myConvertCssToBinCheckBox.isSelected());
@@ -156,6 +180,10 @@
       final String storePass = String.valueOf(myDialog.myPanel.myStorePassTF.getPassword());
       myProperties.setStorepass(!StringUtil.isEmptyOrSpaces(storePass) ? Base64Converter.encode(storePass) : null);
     }
+
+    if (myManifestAttributesDialog != null) {
+      myProperties.setCustomManifestAttributes(myManifestAttributesDialog.getAttrs());
+    }
   }
 
   @Nullable
@@ -179,6 +207,7 @@
     myEnableSigningCB.setSelected(myProperties.isEnabledSigning());
     myConvertCssToBinCheckBox.setSelected(myProperties.isConvertCss2Bin());
     myEditSignCertificateButton.setEnabled(myProperties.isEnabledSigning());
+    myCustomManifestAttributes = myProperties.getCustomManifestAttributes();
   }
 
   private static void setText(TextFieldWithBrowseButton tf, final String title) {
@@ -199,4 +228,107 @@
       myDialog.myPanel = null;
     }
   }
-}
+
+  private static class CustomManifestAttributesDialog extends DialogWrapper {
+    private final JPanel myWholePanel = new JPanel(new BorderLayout());
+    private final AttributesTable myTable;
+
+    protected CustomManifestAttributesDialog(JPanel panel, List<JavaFxManifestAttribute> attrs) {
+      super(panel, true);
+      myTable = new AttributesTable();
+      myTable.setValues(attrs);
+      myWholePanel.add(myTable.getComponent(), BorderLayout.CENTER);
+      setTitle("Edit Custom Manifest Attributes");
+      init();
+    }
+
+    @Override
+    @Nullable
+    protected JComponent createCenterPanel() {
+      return myWholePanel;
+    }
+
+    @Override
+    protected void doOKAction() {
+      myTable.stopEditing();
+      super.doOKAction();
+    }
+
+    List<JavaFxManifestAttribute> getAttrs() {
+      return myTable.getAttrs();
+    }
+
+    private static class AttributesTable extends ListTableWithButtons<JavaFxManifestAttribute> {
+      @Override
+      protected ListTableModel createListModel() {
+        final ColumnInfo name = new ElementsColumnInfoBase<JavaFxManifestAttribute>("Name") {
+          @Nullable
+          @Override
+          public String valueOf(JavaFxManifestAttribute attribute) {
+            return attribute.getName();
+          }
+
+          @Override
+          public boolean isCellEditable(JavaFxManifestAttribute attr) {
+            return true;
+          }
+
+          @Override
+          public void setValue(JavaFxManifestAttribute attr, String value) {
+            attr.setName(value);
+          }
+
+          @Nullable
+          @Override
+          protected String getDescription(JavaFxManifestAttribute element) {
+            return element.getName();
+          }
+        };
+
+        final ColumnInfo value = new ElementsColumnInfoBase<JavaFxManifestAttribute>("Value") {
+          @Override
+          public String valueOf(JavaFxManifestAttribute attr) {
+            return attr.getValue();
+          }
+
+          @Override
+          public boolean isCellEditable(JavaFxManifestAttribute attr) {
+            return true;
+          }
+
+          @Override
+          public void setValue(JavaFxManifestAttribute attr, String s) {
+            attr.setValue(s);
+          }
+
+          @Nullable
+          @Override
+          protected String getDescription(JavaFxManifestAttribute attr) {
+            return attr.getValue();
+          }
+        };
+
+        return new ListTableModel((new ColumnInfo[]{name, value}));
+      }
+
+      @Override
+      protected JavaFxManifestAttribute createElement() {
+        return new JavaFxManifestAttribute("", "");
+      }
+
+      @Override
+      protected JavaFxManifestAttribute cloneElement(JavaFxManifestAttribute attribute) {
+        return new JavaFxManifestAttribute(attribute.getName(), attribute.getValue());
+      }
+
+      @Override
+      protected boolean canDeleteElement(JavaFxManifestAttribute selection) {
+        return true;
+      }
+
+      public List<JavaFxManifestAttribute> getAttrs() {
+        return getElements();
+      }
+    }
+  }
+}
\ No newline at end of file
diff --git a/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java b/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java
index 298f9d2..35ff780 100644
--- a/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java
+++ b/plugins/junit/src/com/intellij/execution/junit/AllInDirectoryConfigurationProducer.java
@@ -43,6 +43,7 @@
     final VirtualFile virtualFile = ((PsiDirectory)element).getVirtualFile();
     final Module module = ModuleUtilCore.findModuleForFile(virtualFile, project);
     if (module == null) return false;
+    if (!ModuleRootManager.getInstance(module).getFileIndex().isInTestSourceContent(virtualFile)) return false;
     int testRootCount = ModuleRootManager.getInstance(module).getSourceRoots(JavaSourceRootType.TEST_SOURCE).size();
     if (testRootCount < 2) return false;
     if (!LocationUtil.isJarAttached(context.getLocation(), aPackage, JUnitUtil.TESTCASE_CLASS)) return false;
diff --git a/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java b/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java
index 4220c5a..d70a97f 100644
--- a/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java
+++ b/plugins/junit/src/com/intellij/execution/junit/JUnitConfigurationProducer.java
@@ -56,6 +56,7 @@
     } else {
       testPackage = null;
     }
+    PsiDirectory testDir = element instanceof PsiDirectory ? (PsiDirectory)element : null;
     RunnerAndConfigurationSettings template = RunManager.getInstance(location.getProject())
       .getConfigurationTemplate(getConfigurationFactory());
     final Module predefinedModule =
@@ -66,7 +67,7 @@
     if (vmParameters != null && !Comparing.strEqual(vmParameters, unitConfiguration.getVMParameters())) return false;
     final TestObject testobject = unitConfiguration.getTestObject();
     if (testobject != null) {
-      if (testobject.isConfiguredByElement(unitConfiguration, testClass, testMethod, testPackage)) {
+      if (testobject.isConfiguredByElement(unitConfiguration, testClass, testMethod, testPackage, testDir)) {
         final Module configurationModule = unitConfiguration.getConfigurationModule().getModule();
         if (Comparing.equal(location.getModule(), configurationModule)) return true;
         if (Comparing.equal(predefinedModule, configurationModule)) {
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestClass.java b/plugins/junit/src/com/intellij/execution/junit/TestClass.java
index db91769..d1b687d 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestClass.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestClass.java
@@ -26,10 +26,7 @@
 import com.intellij.execution.runners.ExecutionEnvironment;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiPackage;
+import com.intellij.psi.*;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
 
 class TestClass extends TestObject {
@@ -62,7 +59,8 @@
   public boolean isConfiguredByElement(final JUnitConfiguration configuration,
                                        PsiClass testClass,
                                        PsiMethod testMethod,
-                                       PsiPackage testPackage) {
+                                       PsiPackage testPackage,
+                                       PsiDirectory testDir) {
 
     if (testClass == null) {
       return false;
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java b/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java
index 77403df..b99c2f0 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestDirectory.java
@@ -25,6 +25,7 @@
 import com.intellij.execution.util.ProgramParametersUtil;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.Comparing;
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -120,14 +121,12 @@
   public boolean isConfiguredByElement(JUnitConfiguration configuration,
                                        PsiClass testClass,
                                        PsiMethod testMethod,
-                                       PsiPackage testPackage) {
-    if (JUnitConfiguration.TEST_DIRECTORY.equals(configuration.getPersistentData().TEST_OBJECT) && testPackage != null) {
-      final PsiDirectory[] directories = testPackage.getDirectories(configuration.getConfigurationModule().getSearchScope());
-      final String dirName = configuration.getPersistentData().getDirName();
-      if (dirName != null) {
-        for (PsiDirectory directory : directories) {
-          if (dirName.equals(directory.getVirtualFile().getPath())) return true;
-        }
+                                       PsiPackage testPackage, 
+                                       PsiDirectory testDir) {
+    if (JUnitConfiguration.TEST_DIRECTORY.equals(configuration.getPersistentData().TEST_OBJECT) && testDir != null) {
+      if (Comparing.strEqual(FileUtil.toSystemIndependentName(configuration.getPersistentData().getDirName()), 
+                             testDir.getVirtualFile().getPath())) {
+        return true;
       }
     }
     return false;
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestMethod.java b/plugins/junit/src/com/intellij/execution/junit/TestMethod.java
index 3d03c02..23d7983 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestMethod.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestMethod.java
@@ -22,10 +22,7 @@
 import com.intellij.execution.runners.ExecutionEnvironment;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Comparing;
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiPackage;
+import com.intellij.psi.*;
 import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.refactoring.listeners.RefactoringElementAdapter;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
@@ -105,7 +102,8 @@
   public boolean isConfiguredByElement(final JUnitConfiguration configuration,
                                        PsiClass testClass,
                                        PsiMethod testMethod,
-                                       PsiPackage testPackage) {
+                                       PsiPackage testPackage,
+                                       PsiDirectory testDir) {
     if (testMethod == null) return false;
     if (testClass == null) return false;
     final JUnitConfiguration.Data data = configuration.getPersistentData();
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestObject.java b/plugins/junit/src/com/intellij/execution/junit/TestObject.java
index ac1c523..39a280c 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestObject.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestObject.java
@@ -62,10 +62,7 @@
 import com.intellij.openapi.util.io.FileUtil;
 import com.intellij.openapi.util.registry.Registry;
 import com.intellij.openapi.vfs.CharsetToolkit;
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiPackage;
+import com.intellij.psi.*;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
 import com.intellij.rt.execution.junit.IDEAJUnitListener;
 import com.intellij.rt.execution.junit.JUnitStarter;
@@ -138,7 +135,8 @@
   public abstract boolean isConfiguredByElement(JUnitConfiguration configuration,
                                                 PsiClass testClass,
                                                 PsiMethod testMethod,
-                                                PsiPackage testPackage);
+                                                PsiPackage testPackage, 
+                                                PsiDirectory testDir);
 
   protected void configureModule(final JavaParameters parameters, final RunConfigurationModule configurationModule, final String mainClassName)
     throws CantRunException {
@@ -162,7 +160,8 @@
     public boolean isConfiguredByElement(final JUnitConfiguration configuration,
                                          PsiClass testClass,
                                          PsiMethod testMethod,
-                                         PsiPackage testPackage) {
+                                         PsiPackage testPackage,
+                                         PsiDirectory testDir) {
       return false;
     }
 
@@ -468,9 +467,7 @@
                                                 boolean junit4) {
     try {
       if (createTempFile) {
-        myTempFile = FileUtil.createTempFile("idea_junit", ".tmp");
-        myTempFile.deleteOnExit();
-        myJavaParameters.getProgramParametersList().add("@" + myTempFile.getAbsolutePath());
+        createTempFiles();
       }
 
       final Map<String, List<String>> perModule = forkPerModule() ? new TreeMap<String, List<String>>() : null;
@@ -538,6 +535,15 @@
     }
   }
 
+  protected void createTempFiles() throws IOException {
+    myTempFile = FileUtil.createTempFile("idea_junit", ".tmp");
+    myTempFile.deleteOnExit();
+    myJavaParameters.getProgramParametersList().add("@" + myTempFile.getAbsolutePath());
+    myWorkingDirsFile = FileUtil.createTempFile("idea_working_dirs_junit", ".tmp");
+    myWorkingDirsFile.deleteOnExit();
+    myJavaParameters.getProgramParametersList().add("@w@" + myWorkingDirsFile.getAbsolutePath());
+  }
+
   public void clear() {
     myJavaParameters = null;
   }
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestPackage.java b/plugins/junit/src/com/intellij/execution/junit/TestPackage.java
index 7e6cf5c..558b2e88 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestPackage.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestPackage.java
@@ -160,18 +160,7 @@
     configureClasspath();
 
     try {
-      myTempFile = FileUtil.createTempFile("idea_junit", ".tmp");
-      myTempFile.deleteOnExit();
-      myJavaParameters.getProgramParametersList().add("@" + myTempFile.getAbsolutePath());
-    }
-    catch (IOException e) {
-      LOG.error(e);
-    }
-
-    try {
-      myWorkingDirsFile = FileUtil.createTempFile("idea_working_dirs_junit", ".tmp");
-      myWorkingDirsFile.deleteOnExit();
-      myJavaParameters.getProgramParametersList().add("@w@" + myWorkingDirsFile.getAbsolutePath());
+      createTempFiles();
     }
     catch (IOException e) {
       LOG.error(e);
@@ -246,7 +235,8 @@
   public boolean isConfiguredByElement(final JUnitConfiguration configuration,
                                        PsiClass testClass,
                                        PsiMethod testMethod,
-                                       PsiPackage testPackage) {
+                                       PsiPackage testPackage,
+                                       PsiDirectory testDir) {
     return testPackage != null
            && Comparing.equal(testPackage.getQualifiedName(), configuration.getPersistentData().getPackageName());
   }
diff --git a/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java b/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java
index b0cc87b..c4954f0 100644
--- a/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java
+++ b/plugins/junit/src/com/intellij/execution/junit/TestsPattern.java
@@ -34,10 +34,7 @@
 import com.intellij.openapi.progress.impl.BackgroundableProcessIndicator;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.psi.PsiClass;
-import com.intellij.psi.PsiElement;
-import com.intellij.psi.PsiMethod;
-import com.intellij.psi.PsiPackage;
+import com.intellij.psi.*;
 import com.intellij.psi.search.GlobalSearchScope;
 import com.intellij.refactoring.listeners.RefactoringElementListener;
 import com.intellij.refactoring.listeners.RefactoringElementListenerComposite;
@@ -194,7 +191,8 @@
   public boolean isConfiguredByElement(JUnitConfiguration configuration,
                                        PsiClass testClass,
                                        PsiMethod testMethod,
-                                       PsiPackage testPackage) {
+                                       PsiPackage testPackage,
+                                       PsiDirectory testDir) {
     /*if (testMethod != null && Comparing.strEqual(testMethod.getName(), configuration.getPersistentData().METHOD_NAME)) {
       return true;
     }*/
diff --git a/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java b/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java
index d0a3a0e..1ed5c0c 100644
--- a/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java
+++ b/plugins/junit_rt/src/com/intellij/rt/execution/junit/JUnitStarter.java
@@ -193,7 +193,7 @@
       System.setOut(new PrintStream(out));
       System.setErr(new PrintStream(err));
       if (ourCommandFileName != null) {
-        if (!"none".equals(ourForkMode) || new File(ourWorkingDirs).length() > 0) {
+        if (!"none".equals(ourForkMode) || ourWorkingDirs != null && new File(ourWorkingDirs).length() > 0) {
           return JUnitForkedStarter.startForkedVMs(ourWorkingDirs, args, isJUnit4, listeners, out, err, ourForkMode, ourCommandFileName);
         }
       }
diff --git a/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java b/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java
index f924632..bf3fff9 100644
--- a/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java
+++ b/plugins/maven/artifact-resolver-m2/src/org/jetbrains/idea/maven/artifactResolver/common/MavenModuleMap.java
@@ -56,6 +56,10 @@
 
   public boolean resolveToModule(Artifact artifact) {
     String extension = artifact.getArtifactHandler().getExtension();
+    if ("jar".equals(extension) && "test-jar".equals(artifact.getType())) {
+      extension = "test-jar";
+    }
+
     File file = findArtifact(artifact.getGroupId(), artifact.getArtifactId(), extension, artifact.getBaseVersion());
 
     if(file == null) {
diff --git a/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java b/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java
index d67fcc9..612d24b 100644
--- a/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java
+++ b/plugins/maven/artifact-resolver-m3/src/org/jetbrains/idea/maven/artifactResolver/MyWorkspaceReader.java
@@ -52,7 +52,12 @@
   }
 
   public File findArtifact(Artifact artifact) {
-    return MavenModuleMap.getInstance().findArtifact(artifact.getGroupId(), artifact.getArtifactId(), artifact.getExtension(),
+    String type = artifact.getExtension();
+    if ("jar".equals(type) && "tests".equals(artifact.getClassifier())) {
+      type = "test-jar";
+    }
+
+    return MavenModuleMap.getInstance().findArtifact(artifact.getGroupId(), artifact.getArtifactId(), type,
                                                      artifact.getBaseVersion());
   }
 
diff --git a/plugins/maven/artifact-resolver-m31/lib/eclipse-aether/aether-api-0.9.0.M2.jar b/plugins/maven/artifact-resolver-m31/lib/eclipse-aether/aether-api-0.9.0.M2.jar
new file mode 100644
index 0000000..e5b122c
--- /dev/null
+++ b/plugins/maven/artifact-resolver-m31/lib/eclipse-aether/aether-api-0.9.0.M2.jar
Binary files differ
diff --git a/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml b/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml
new file mode 100644
index 0000000..3d45f6b
--- /dev/null
+++ b/plugins/maven/artifact-resolver-m31/maven-artifact-resolver-m31.iml
@@ -0,0 +1,40 @@
+<?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-library">
+      <library>
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/../maven3-server-impl/lib/maven3/lib/maven-core-3.0.3.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES />
+      </library>
+    </orderEntry>
+    <orderEntry type="module-library">
+      <library>
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/../maven3-server-impl/lib/maven3/lib/plexus-component-annotations-1.5.5.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES />
+      </library>
+    </orderEntry>
+    <orderEntry type="module-library">
+      <library>
+        <CLASSES>
+          <root url="jar://$MODULE_DIR$/lib/eclipse-aether/aether-api-0.9.0.M2.jar!/" />
+        </CLASSES>
+        <JAVADOC />
+        <SOURCES />
+      </library>
+    </orderEntry>
+    <orderEntry type="module" module-name="maven-artifact-resolver-m2" />
+  </component>
+</module>
+
diff --git a/plugins/maven/artifact-resolver-m31/src/META-INF/plexus/components.xml b/plugins/maven/artifact-resolver-m31/src/META-INF/plexus/components.xml
new file mode 100644
index 0000000..d4d29b1
--- /dev/null
+++ b/plugins/maven/artifact-resolver-m31/src/META-INF/plexus/components.xml
@@ -0,0 +1,12 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<component-set>
+  <components>
+    <component>
+      <role>org.eclipse.aether.repository.WorkspaceReader</role>
+      <role-hint>ide</role-hint>
+      <implementation>org.jetbrains.idea.maven.artifactResolver.IntelliJWorkspaceReaderM31</implementation>
+      <description />
+      <isolated-realm>false</isolated-realm>
+    </component>
+  </components>
+</component-set>
diff --git a/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/IntelliJWorkspaceReaderM31.java b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/IntelliJWorkspaceReaderM31.java
new file mode 100644
index 0000000..3041e83
--- /dev/null
+++ b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/IntelliJWorkspaceReaderM31.java
@@ -0,0 +1,67 @@
+/*
+ * 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.idea.maven.artifactResolver;
+
+import org.codehaus.plexus.component.annotations.Component;
+import org.eclipse.aether.artifact.Artifact;
+import org.eclipse.aether.repository.WorkspaceReader;
+import org.eclipse.aether.repository.WorkspaceRepository;
+import org.jetbrains.idea.maven.artifactResolver.common.MavenModuleMap;
+
+import java.io.File;
+import java.util.Collections;
+import java.util.List;
+
+/**
+ * @author Sergey Evdokimov
+ */
+@Component(role = WorkspaceReader.class, hint = "ide")
+public class IntelliJWorkspaceReaderM31 implements WorkspaceReader {
+
+  private final WorkspaceRepository myWorkspaceRepository;
+
+  public IntelliJWorkspaceReaderM31() {
+    myWorkspaceRepository = new WorkspaceRepository("ide", getClass());
+  }
+
+  @Override
+  public int hashCode() {
+    return 311;
+  }
+
+  @Override
+  public boolean equals(Object o) {
+    return o instanceof IntelliJWorkspaceReaderM31;
+  }
+
+  public WorkspaceRepository getRepository() {
+    return myWorkspaceRepository;
+  }
+
+  public File findArtifact(Artifact artifact) {
+    String type = artifact.getExtension();
+    if ("jar".equals(type) && "tests".equals(artifact.getClassifier())) {
+      type = "test-jar";
+    }
+
+    return MavenModuleMap.getInstance().findArtifact(artifact.getGroupId(), artifact.getArtifactId(), type,
+                                                     artifact.getBaseVersion());
+  }
+
+  public List<String> findVersions(Artifact artifact) {
+    return Collections.emptyList();
+  }
+}
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/MavenArtifactResolvedM31RtMarker.java
similarity index 61%
copy from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
copy to plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/MavenArtifactResolvedM31RtMarker.java
index fec7c97..ad15baf 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
+++ b/plugins/maven/artifact-resolver-m31/src/org/jetbrains/idea/maven/artifactResolver/MavenArtifactResolvedM31RtMarker.java
@@ -13,22 +13,10 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model.impl;
-
-import org.gradle.tooling.model.Dependency;
-
-import java.io.Serializable;
+package org.jetbrains.idea.maven.artifactResolver;
 
 /**
- * @author Vladislav.Soroka
- * @since 11/8/13
+ * @author Sergey Evdokimov
  */
-public interface GradleDependency extends Dependency, Serializable {
-  String getConfigurationName();
-
-  String getDependencyName();
-
-  String getDependencyGroup();
-
-  String getDependencyVersion();
+public class MavenArtifactResolvedM31RtMarker {
 }
diff --git a/plugins/maven/maven.iml b/plugins/maven/maven.iml
index 8c58bb7..c15aa89 100644
--- a/plugins/maven/maven.iml
+++ b/plugins/maven/maven.iml
@@ -59,6 +59,7 @@
     <orderEntry type="module" module-name="jps-model-impl" />
     <orderEntry type="module" module-name="maven-jps-plugin" />
     <orderEntry type="module" module-name="maven-artifact-resolver-m3" />
+    <orderEntry type="module" module-name="maven-artifact-resolver-m31" />
     <orderEntry type="module" module-name="spellchecker" />
     <orderEntry type="module" module-name="vcs-api" />
   </component>
diff --git a/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java b/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java
index bffa040..77f9950 100644
--- a/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java
+++ b/plugins/maven/maven3-server-impl/src/org/jetbrains/idea/maven/server/Maven3ServerEmbedderImpl.java
@@ -95,6 +95,8 @@
 
   private MavenWorkspaceMap myWorkspaceMap;
 
+  private Date myBuildStartTime;
+
   public Maven3ServerEmbedderImpl(MavenServerSettings settings) throws RemoteException {
     File mavenHome = settings.getMavenHome();
     if (mavenHome != null) {
@@ -263,6 +265,8 @@
 
       myWorkspaceMap = workspaceMap;
 
+      myBuildStartTime = new Date();
+
       setConsoleAndIndicator(console, new MavenServerProgressIndicatorWrapper(indicator));
     }
     catch (Exception e) {
@@ -406,6 +410,8 @@
       result.setActiveProfiles(activeProfiles);
       result.setInactiveProfiles(inactiveProfiles);
 
+      result.setStartTime(myBuildStartTime);
+
       return result;
     }
     catch (MavenExecutionRequestPopulationException e) {
@@ -414,7 +420,6 @@
   }
 
   private static MavenExecutionResult handleException(Throwable e) {
-      if (e instanceof RuntimeException) throw (RuntimeException) e;
       if (e instanceof Error) throw (Error) e;
 
       return new MavenExecutionResult(null, Collections.singletonList((Exception) e));
@@ -822,6 +827,8 @@
 
       Properties props = MavenServerUtil.collectSystemProperties();
       ProjectBuilderConfiguration config = new DefaultProjectBuilderConfiguration().setExecutionProperties(props);
+      config.setBuildStartTime(new Date());
+
       result = interpolator.interpolate(result, basedir, config, false);
     }
     catch (ModelInterpolationException e) {
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/MavenDomDependency.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/MavenDomDependency.java
index 5d8ea17..38af66e 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/MavenDomDependency.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/model/MavenDomDependency.java
@@ -67,7 +67,6 @@
    * @return the value of the classifier child.
    */
   @NotNull
-  @Required(value = false, nonEmpty = true)
   GenericDomValue<String> getClassifier();
 
   /**
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenContextlessPropertyReference.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenContextlessPropertyReference.java
new file mode 100644
index 0000000..58f3a05
--- /dev/null
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenContextlessPropertyReference.java
@@ -0,0 +1,81 @@
+/*
+ * 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.idea.maven.dom.references;
+
+import com.intellij.openapi.util.TextRange;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiReferenceBase;
+import com.intellij.psi.util.PsiTreeUtil;
+import com.intellij.psi.xml.XmlTag;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * @author Sergey Evdokimov
+ */
+public class MavenContextlessPropertyReference extends PsiReferenceBase<PsiElement> {
+
+  private final XmlTag myProperties;
+
+  public MavenContextlessPropertyReference(@NotNull XmlTag properties,
+                                           @NotNull PsiElement element,
+                                           @NotNull TextRange range,
+                                           boolean isSoft) {
+    super(element, range, isSoft);
+
+    myProperties = properties;
+  }
+
+  @Nullable
+  @Override
+  public PsiElement resolve() {
+    String value = getValue();
+
+    for (XmlTag subTag : myProperties.getSubTags()) {
+      if (value.equals(subTag.getName())) {
+        return subTag;
+      }
+    }
+
+    return null;
+  }
+
+  @NotNull
+  @Override
+  public Object[] getVariants() {
+    String skippedPropertyName = null;
+
+    XmlTag xmlTag = PsiTreeUtil.getParentOfType(getElement(), XmlTag.class, false);
+
+    if (xmlTag != null && myProperties == xmlTag.getParentTag()) {
+      skippedPropertyName = xmlTag.getName();
+    }
+
+    List<String> res = new ArrayList<String>();
+
+    for (XmlTag subTag : myProperties.getSubTags()) {
+      String name = subTag.getName();
+      if (!name.equals(skippedPropertyName)) {
+        res.add(name);
+      }
+    }
+
+    return res.toArray();
+  }
+}
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java
index 1108d8b..f839a43 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/dom/references/MavenPropertyPsiReferenceProvider.java
@@ -24,10 +24,13 @@
 import com.intellij.psi.PsiReferenceProvider;
 import com.intellij.psi.xml.XmlTag;
 import com.intellij.util.ProcessingContext;
+import com.intellij.util.xml.DomElement;
+import com.intellij.util.xml.DomUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.idea.maven.dom.MavenDomUtil;
 import org.jetbrains.idea.maven.dom.MavenPropertyResolver;
+import org.jetbrains.idea.maven.dom.model.MavenDomProperties;
 import org.jetbrains.idea.maven.plugins.api.MavenPluginParamInfo;
 import org.jetbrains.idea.maven.project.MavenProject;
 import org.jetbrains.idea.maven.project.MavenProjectsManager;
@@ -77,6 +80,7 @@
     if (!isElementCanContainReference(element)) return PsiReference.EMPTY_ARRAY;
 
     MavenProject mavenProject = null;
+    XmlTag propertiesTag = null;
     List<PsiReference> result = null;
 
     Matcher matcher = MavenPropertyResolver.PATTERN.matcher(textRange.substring(text));
@@ -98,13 +102,29 @@
 
         mavenProject = findMavenProject(element);
         if (mavenProject == null) {
-          return PsiReference.EMPTY_ARRAY;
+          propertiesTag = findPropertiesParentTag(element);
+          if (propertiesTag == null) {
+            return PsiReference.EMPTY_ARRAY;
+          }
         }
       }
 
-      result.add(new MavenPropertyPsiReference(mavenProject, element, propertyName, range, isSoft));
+      PsiReference ref;
+      if (mavenProject != null) {
+        ref = new MavenPropertyPsiReference(mavenProject, element, propertyName, range, isSoft);
+      }
+      else {
+        ref = new MavenContextlessPropertyReference(propertiesTag, element, range, isSoft);
+      }
+
+      result.add(ref);
     }
 
     return result == null ? PsiReference.EMPTY_ARRAY : result.toArray(new PsiReference[result.size()]);
   }
+
+  private static XmlTag findPropertiesParentTag(@NotNull PsiElement element) {
+    DomElement domElement = DomUtil.getDomElement(element);
+    return domElement instanceof MavenDomProperties ? domElement.getXmlTag() : null;
+  }
 }
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java
index 635e1da..4f0b999 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenEditGoalDialog.java
@@ -138,9 +138,8 @@
     if (goalsComboBox != null) {
       goalsComboBox.setSelectedItem(goals);
     }
-    else {
-      goalsEditor.setText(goals);
-    }
+
+    goalsEditor.setText(goals);
   }
 
   @NotNull
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java
index a8f4606..4ba837b 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenExternalParameters.java
@@ -47,6 +47,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM2RtMarker;
+import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM31RtMarker;
 import org.jetbrains.idea.maven.artifactResolver.MavenArtifactResolvedM3RtMarker;
 import org.jetbrains.idea.maven.artifactResolver.common.MavenModuleMap;
 import org.jetbrains.idea.maven.project.MavenGeneralSettings;
@@ -126,7 +127,7 @@
 
     if (project != null && parameters.isResolveToWorkspace()) {
       try {
-        String resolverJar = getArtifactResolverJar(MavenUtil.isMaven3(mavenHome));
+        String resolverJar = getArtifactResolverJar(MavenUtil.getMavenVersion(mavenHome));
         confFile = patchConfFile(confFile, resolverJar);
 
         File modulesPathsFile = dumpModulesPaths(project);
@@ -196,11 +197,24 @@
     finally {
       sc.close();
     }
-
   }
 
-  private static String getArtifactResolverJar(boolean isMaven3) throws IOException {
-    Class marker = isMaven3 ? MavenArtifactResolvedM3RtMarker.class : MavenArtifactResolvedM2RtMarker.class;
+  private static String getArtifactResolverJar(@Nullable String mavenVersion) throws IOException {
+    boolean isMaven3;
+    Class marker;
+
+    if (mavenVersion != null && mavenVersion.compareTo("3.1.0") >= 0) {
+      isMaven3 = true;
+      marker = MavenArtifactResolvedM31RtMarker.class;
+    }
+    else if (mavenVersion != null && mavenVersion.compareTo("3.0.0") >= 0) {
+      isMaven3 = true;
+      marker = MavenArtifactResolvedM3RtMarker.class;
+    }
+    else {
+      isMaven3 = false;
+      marker = MavenArtifactResolvedM2RtMarker.class;
+    }
 
     File classDirOrJar = new File(PathUtil.getJarPathForClass(marker));
 
@@ -248,6 +262,12 @@
 
           res.setProperty(mavenProject.getMavenId().getGroupId()
                           + ':' + mavenProject.getMavenId().getArtifactId()
+                          + ":test-jar"
+                          + ':' + mavenProject.getMavenId().getVersion(),
+                          mavenProject.getTestOutputDirectory());
+
+          res.setProperty(mavenProject.getMavenId().getGroupId()
+                          + ':' + mavenProject.getMavenId().getArtifactId()
                           + ':' + mavenProject.getPackaging()
                           + ':' + mavenProject.getMavenId().getVersion(),
                            mavenProject.getOutputDirectory());
@@ -483,6 +503,10 @@
       cmdList.add("--update-snapshots");
     }
 
+    if (StringUtil.isNotEmpty(coreSettings.getThreads())) {
+      cmdList.add("-T", coreSettings.getThreads());
+    }
+
     addIfNotEmpty(cmdList, coreSettings.getFailureBehavior().getCommandLineOption());
     addIfNotEmpty(cmdList, coreSettings.getChecksumPolicy().getCommandLineOption());
 
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java
index 25f1012..c9718cd 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/execution/MavenResumeAction.java
@@ -297,7 +297,9 @@
         goals.add(myResumeModuleId);
       }
 
-      myRunner.execute(new ExecutionEnvironmentBuilder(myEnvironment).setContentToReuse(null).build());
+      runConfiguration.getRunnerParameters().setGoals(goals);
+
+      myRunner.execute(new ExecutionEnvironmentBuilder(myEnvironment).setContentToReuse(null).setRunProfile(runConfiguration).build());
     }
     catch (RunCanceledByUserException ignore) {
     }
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/actions/MavenExecuteGoalAction.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/actions/MavenExecuteGoalAction.java
index 99289a1..8190fce 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/actions/MavenExecuteGoalAction.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/navigator/actions/MavenExecuteGoalAction.java
@@ -22,10 +22,10 @@
 import com.intellij.notification.Notifications;
 import com.intellij.openapi.actionSystem.AnActionEvent;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
-import com.intellij.openapi.actionSystem.PlatformDataKeys;
 import com.intellij.openapi.options.ShowSettingsUtil;
 import com.intellij.openapi.project.DumbAwareAction;
 import com.intellij.openapi.project.Project;
+import com.intellij.openapi.util.text.StringUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.idea.maven.execution.*;
 import org.jetbrains.idea.maven.project.MavenGeneralSettings;
@@ -59,7 +59,12 @@
 
     dialog.setWorkDirectory(lastWorkingDirectory);
 
-    if (historyService.getCanceledCommand() != null) {
+    if (StringUtil.isEmptyOrSpaces(historyService.getCanceledCommand())) {
+      if (historyService.getHistory().size() > 0) {
+        dialog.setGoals(historyService.getHistory().get(0));
+      }
+    }
+    else {
       dialog.setGoals(historyService.getCanceledCommand());
     }
 
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.form b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.form
index 5bfdc81..ad75695 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.form
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.form
@@ -1,9 +1,9 @@
 <?xml version="1.0" encoding="UTF-8"?>
 <form xmlns="http://www.intellij.com/uidesigner/form/" version="1" bind-to-class="org.jetbrains.idea.maven.project.MavenGeneralPanel">
-  <grid id="27dc6" binding="panel" layout-manager="GridLayoutManager" row-count="11" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+  <grid id="27dc6" binding="panel" layout-manager="GridLayoutManager" row-count="12" column-count="3" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
     <margin top="0" left="0" bottom="0" right="0"/>
     <constraints>
-      <xy x="20" y="20" width="684" height="451"/>
+      <xy x="20" y="20" width="684" height="454"/>
     </constraints>
     <properties/>
     <border type="none"/>
@@ -115,12 +115,12 @@
       </component>
       <nested-form id="3edfe" form-file="org/jetbrains/idea/maven/project/MavenEnvironmentForm.form" binding="mavenPathsForm">
         <constraints>
-          <grid row="9" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+          <grid row="10" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
         </constraints>
       </nested-form>
       <vspacer id="9cb69">
         <constraints>
-          <grid row="10" column="0" row-span="1" col-span="2" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
+          <grid row="11" column="0" row-span="1" col-span="2" vsize-policy="6" hsize-policy="1" anchor="0" fill="2" indent="0" use-parent-layout="false"/>
         </constraints>
       </vspacer>
       <hspacer id="38d7a">
@@ -147,6 +147,26 @@
           <toolTipText value="Forces a check for updated releases and snapshots on remote repositories"/>
         </properties>
       </component>
+      <component id="71ae2" class="com.intellij.ui.components.JBLabel">
+        <constraints>
+          <grid row="9" 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>
+        <properties>
+          <horizontalAlignment value="10"/>
+          <horizontalTextPosition value="11"/>
+          <labelFor value="79cd1"/>
+          <text value="&lt;html&gt;Threads &lt;small&gt;&lt;i&gt;(-T option):&lt;i&gt;&lt;/small&gt;&lt;/html&gt;"/>
+          <toolTipText value="Thread count, for instance 2.0C where C is core multiplied (option -T)"/>
+        </properties>
+      </component>
+      <component id="79cd1" class="javax.swing.JTextField" binding="threadsEditor">
+        <constraints>
+          <grid row="9" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="2" anchor="8" fill="0" indent="0" use-parent-layout="false">
+            <preferred-size width="150" height="-1"/>
+          </grid>
+        </constraints>
+        <properties/>
+      </component>
     </children>
   </grid>
 </form>
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.java
index fbd6848..312f0f2 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralPanel.java
@@ -18,6 +18,7 @@
 package org.jetbrains.idea.maven.project;
 
 import com.intellij.openapi.util.Pair;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.ui.PanelWithAnchor;
 import com.intellij.ui.components.JBLabel;
 import com.intellij.util.Function;
@@ -44,6 +45,7 @@
   private MavenEnvironmentForm mavenPathsForm;
   private JBLabel myMultiprojectBuildFailPolicyLabel;
   private JCheckBox alwaysUpdateSnapshotsCheckBox;
+  private JTextField threadsEditor;
   private final DefaultComboBoxModel outputLevelComboModel = new DefaultComboBoxModel();
   private final DefaultComboBoxModel checksumPolicyComboModel = new DefaultComboBoxModel();
   private final DefaultComboBoxModel failPolicyComboModel = new DefaultComboBoxModel();
@@ -122,6 +124,7 @@
     data.setFailureBehavior((MavenExecutionOptions.FailureMode)ComboBoxUtil.getSelectedValue(failPolicyComboModel));
     data.setPluginUpdatePolicy((MavenExecutionOptions.PluginUpdatePolicy)ComboBoxUtil.getSelectedValue(pluginUpdatePolicyComboModel));
     data.setAlwaysUpdateSnapshots(alwaysUpdateSnapshotsCheckBox.isSelected());
+    data.setThreads(threadsEditor.getText());
 
     data.endUpdate();
   }
@@ -135,6 +138,7 @@
     checkboxUsePluginRegistry.setSelected(data.isUsePluginRegistry());
     checkboxRecursive.setSelected(!data.isNonRecursive());
     alwaysUpdateSnapshotsCheckBox.setSelected(data.isAlwaysUpdateSnapshots());
+    threadsEditor.setText(StringUtil.notNullize(data.getThreads()));
 
     ComboBoxUtil.select(outputLevelComboModel, data.getOutputLevel());
     ComboBoxUtil.select(checksumPolicyComboModel, data.getChecksumPolicy());
diff --git a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java
index 02e00a3..44b7dc0 100644
--- a/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java
+++ b/plugins/maven/src/main/java/org/jetbrains/idea/maven/project/MavenGeneralSettings.java
@@ -16,6 +16,7 @@
 package org.jetbrains.idea.maven.project;
 
 import com.intellij.openapi.util.Comparing;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.LocalFileSystem;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.util.containers.ContainerUtil;
@@ -45,6 +46,8 @@
 
   private boolean alwaysUpdateSnapshots = false;
 
+  private String threads;
+
   private MavenExecutionOptions.LoggingLevel outputLevel = MavenExecutionOptions.LoggingLevel.INFO;
   private MavenExecutionOptions.ChecksumPolicy checksumPolicy = MavenExecutionOptions.ChecksumPolicy.NOT_SET;
   private MavenExecutionOptions.FailureMode failureBehavior = MavenExecutionOptions.FailureMode.NOT_SET;
@@ -287,6 +290,16 @@
     changed();
   }
 
+  @Nullable
+  public String getThreads() {
+    return threads;
+  }
+
+  public void setThreads(@Nullable String threads) {
+    this.threads = StringUtil.nullize(threads);
+    changed();
+  }
+
   public boolean equals(final Object o) {
     if (this == o) return true;
     if (o == null || getClass() != o.getClass()) return false;
@@ -305,6 +318,7 @@
     if (!overriddenLocalRepository.equals(that.overriddenLocalRepository)) return false;
     if (!mavenHome.equals(that.mavenHome)) return false;
     if (!mavenSettingsFile.equals(that.mavenSettingsFile)) return false;
+    if (!Comparing.equal(threads, that.threads)) return false;
 
     return true;
   }
diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPropertyCompletionAndResolutionTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPropertyCompletionAndResolutionTest.java
index bc4867b..dc3fb09 100644
--- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPropertyCompletionAndResolutionTest.java
+++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/dom/MavenPropertyCompletionAndResolutionTest.java
@@ -15,6 +15,7 @@
  */
 package org.jetbrains.idea.maven.dom;
 
+import com.intellij.codeInsight.completion.CompletionType;
 import com.intellij.lang.properties.IProperty;
 import com.intellij.openapi.util.SystemInfo;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -22,6 +23,7 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiManager;
 import com.intellij.psi.PsiReference;
+import com.intellij.psi.xml.XmlTag;
 import org.jetbrains.idea.maven.dom.model.MavenDomProfiles;
 import org.jetbrains.idea.maven.dom.model.MavenDomProfilesModel;
 import org.jetbrains.idea.maven.dom.model.MavenDomSettingsModel;
@@ -577,6 +579,44 @@
     assertResolved(myProjectPom, findTag(profiles, "settings.localRepository", MavenDomSettingsModel.class));
   }
 
+  public void testCompletionPropertyInsideSettingsXml() throws Exception {
+    VirtualFile profiles = updateSettingsXml("<profiles>" +
+                                                 "  <profile>" +
+                                                 "    <id>one</id>" +
+                                                 "    <properties>" +
+                                                 "      <foo>value</foo>" +
+                                                 "      <bar>value</bar>" +
+                                                 "      <xxx>${<caret>}</xxx>" +
+                                                 "    </properties>" +
+                                                 "  </profile>" +
+                                                 "</profiles>");
+
+    myFixture.configureFromExistingVirtualFile(profiles);
+    myFixture.complete(CompletionType.BASIC);
+    List<String> strings = myFixture.getLookupElementStrings();
+
+    assert strings != null;
+    assert strings.containsAll(Arrays.asList("foo", "bar"));
+    assert !strings.contains("xxx");
+  }
+
+  public void testResolvePropertyInsideSettingsXml() throws Exception {
+    VirtualFile profiles = updateSettingsXml("<profiles>" +
+                                                 "  <profile>" +
+                                                 "    <id>one</id>" +
+                                                 "    <properties>" +
+                                                 "      <foo>value</foo>" +
+                                                 "      <bar>${<caret>foo}</bar>" +
+                                                 "    </properties>" +
+                                                 "  </profile>" +
+                                                 "</profiles>");
+
+    myFixture.configureFromExistingVirtualFile(profiles);
+    PsiElement elementAtCaret = myFixture.getElementAtCaret();
+    assert elementAtCaret instanceof XmlTag;
+    assertEquals("foo", ((XmlTag)elementAtCaret).getName());
+  }
+
   public void testResolvingAbsentSettingsModelProperties() throws Exception {
     createProjectPom("<groupId>test</groupId>" +
                      "<artifactId>project</artifactId>" +
diff --git a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java
index e30c306..5f32a74 100644
--- a/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java
+++ b/plugins/maven/src/test/java/org/jetbrains/idea/maven/execution/MavenRunConfigurationTest.java
@@ -41,6 +41,7 @@
     s.myGeneralSettings.setChecksumPolicy(MavenExecutionOptions.ChecksumPolicy.WARN);
     s.myGeneralSettings.setFailureBehavior(MavenExecutionOptions.FailureMode.AT_END);
     s.myGeneralSettings.setOutputLevel(MavenExecutionOptions.LoggingLevel.FATAL);
+    s.myGeneralSettings.setThreads("1.5C");
 
     s.myRunnerSettings = new MavenRunnerSettings();
     s.myRunnerSettings.setMavenProperties(ImmutableMap.of("a", "1", "b", "2", "c", "3"));
diff --git a/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java b/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java
index 6320a308..b7d8a7f 100644
--- a/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java
+++ b/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesFile.java
@@ -15,6 +15,7 @@
  */
 package com.intellij.lang.properties.xml;
 
+import com.intellij.ide.highlighter.XmlFileType;
 import com.intellij.lang.properties.IProperty;
 import com.intellij.lang.properties.PropertiesUtil;
 import com.intellij.lang.properties.ResourceBundle;
@@ -71,7 +72,7 @@
 
   @Nullable
   public static PropertiesFile getPropertiesFile(final PsiFile file) {
-    return file instanceof XmlFile ? getPropertiesFile((XmlFile)file) : null;
+    return file instanceof XmlFile && file.getFileType() == XmlFileType.INSTANCE ? getPropertiesFile((XmlFile)file) : null;
   }
 
   public static PropertiesFile getPropertiesFile(final XmlFile file) {
diff --git a/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesIconProvider.java b/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesIconProvider.java
index ca8bd0c..713b511 100644
--- a/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesIconProvider.java
+++ b/plugins/properties/src/com/intellij/lang/properties/xml/XmlPropertiesIconProvider.java
@@ -1,6 +1,7 @@
 package com.intellij.lang.properties.xml;
 
 import com.intellij.ide.IconProvider;
+import com.intellij.ide.highlighter.XmlFileType;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.xml.XmlFile;
 import icons.PropertiesIcons;
@@ -16,6 +17,8 @@
 
   @Override
   public Icon getIcon(@NotNull PsiElement element, int flags) {
-    return element instanceof XmlFile && XmlPropertiesFile.getPropertiesFile((XmlFile)element) != null ? PropertiesIcons.XmlProperties : null;
+    return element instanceof XmlFile &&
+           ((XmlFile)element).getFileType() == XmlFileType.INSTANCE &&
+           XmlPropertiesFile.getPropertiesFile((XmlFile)element) != null ? PropertiesIcons.XmlProperties : null;
   }
 }
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/RootUrlInfo.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/RootUrlInfo.java
index d16e4c9..73ec70b 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/RootUrlInfo.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/RootUrlInfo.java
@@ -15,8 +15,8 @@
  */
 package org.jetbrains.idea.svn;
 
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VirtualFile;
+import com.intellij.util.UriUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.tmatesoft.svn.core.SVNURL;
@@ -43,7 +43,7 @@
     myNode = node;
     myFormat = format;
     myRoot = root;
-    myRepositoryUrl = StringUtil.trimEnd(node.getRepositoryRootUrl().toString(), "/");
+    myRepositoryUrl = UriUtil.trimLastSlash(node.getRepositoryRootUrl().toString());
     myType = type;
   }
 
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/CreateExternalAction.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/CreateExternalAction.java
index 490c093..b65332a 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/CreateExternalAction.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/actions/CreateExternalAction.java
@@ -167,8 +167,12 @@
   private void checkState(AnActionEvent e, final ActionStateConsumer sc) {
     final DataContext dc = e.getDataContext();
     final Project project = CommonDataKeys.PROJECT.getData(dc);
+    if (project == null) {
+      sc.hide();
+      return;
+    }
     final ProjectLevelVcsManager manager = ProjectLevelVcsManager.getInstance(project);
-    if (project == null || ! manager.checkVcsIsActive(SvnVcs.getKey().getName())) {
+    if (!manager.checkVcsIsActive(SvnVcs.getKey().getName())) {
       sc.hide();
       return;
     }
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java
index d060ea2..92d964e 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/checkout/SvnCheckoutProvider.java
@@ -38,7 +38,6 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.openapi.wm.StatusBar;
 import com.intellij.util.containers.ContainerUtil;
-import com.intellij.util.ui.UIUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.jetbrains.idea.svn.*;
@@ -58,7 +57,6 @@
 
 import javax.swing.*;
 import java.io.File;
-import java.util.Collections;
 import java.util.List;
 import java.util.concurrent.atomic.AtomicReference;
 
@@ -88,7 +86,7 @@
     ClientFactory settingsFactory = vcs.getFactoryFromSettings();
     ClientFactory otherFactory = vcs.getOtherFactory();
     List<WorkingCopyFormat> settingsFactoryFormats = settingsFactory.createCheckoutClient().getSupportedFormats();
-    List<WorkingCopyFormat> otherFactoryFormats = otherFactory.createCheckoutClient().getSupportedFormats();
+    List<WorkingCopyFormat> otherFactoryFormats = CheckoutFormatFromUserProvider.getOtherFactoryFormats(otherFactory);
 
     return settingsFactoryFormats.contains(format) || !otherFactoryFormats.contains(format) ? settingsFactory : otherFactory;
   }
@@ -361,17 +359,25 @@
 
       try {
         result.addAll(myVcs.getFactoryFromSettings().createCheckoutClient().getSupportedFormats());
+        result.addAll(getOtherFactoryFormats(myVcs.getOtherFactory()));
       }
       catch (VcsException e) {
         error.set(e.getMessage());
       }
 
+      return result;
+    }
+
+    private static List<WorkingCopyFormat> getOtherFactoryFormats(@NotNull ClientFactory otherFactory) {
+      List<WorkingCopyFormat> result;
+
       try {
-        result.addAll(myVcs.getOtherFactory().createCheckoutClient().getSupportedFormats());
+        result = otherFactory.createCheckoutClient().getSupportedFormats();
       }
       catch (VcsException e) {
         // do not add error as it is just usability fix and "other factory" could be incorrectly configured (for instance, invalid
         // executable path)
+        result = ContainerUtil.newArrayList();
         LOG.info("Failed to get checkout formats from other factory", e);
       }
 
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandExecutor.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandExecutor.java
index 556691a..a7580ae 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandExecutor.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/commandLine/CommandExecutor.java
@@ -22,13 +22,18 @@
 import com.intellij.openapi.util.Key;
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.util.EventDispatcher;
+import com.intellij.util.io.BaseDataReader;
+import com.intellij.util.io.BinaryOutputReader;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 import org.tmatesoft.svn.core.SVNCancelException;
 
+import java.io.ByteArrayOutputStream;
 import java.io.IOException;
+import java.io.InputStream;
 import java.io.OutputStreamWriter;
+import java.util.concurrent.Future;
 import java.util.concurrent.atomic.AtomicBoolean;
 import java.util.concurrent.atomic.AtomicReference;
 
@@ -117,7 +122,13 @@
 
   @NotNull
   protected OSProcessHandler createProcessHandler() {
-    return new OSProcessHandler(myProcess, myCommandLine.getCommandLineString());
+    return needsBinaryOutput()
+           ? new BinaryOSProcessHandler(myProcess, myCommandLine.getCommandLineString())
+           : new OSProcessHandler(myProcess, myCommandLine.getCommandLineString());
+  }
+
+  private boolean needsBinaryOutput() {
+    return SvnCommandName.cat.equals(myCommand.getName());
   }
 
   @NotNull
@@ -142,6 +153,11 @@
     return outputAdapter.getOutput().getStderr();
   }
 
+  @Nullable
+  public ByteArrayOutputStream getBinaryOutput() {
+    return myHandler instanceof BinaryOSProcessHandler ? ((BinaryOSProcessHandler)myHandler).myBinaryOutput : null;
+  }
+
   // TODO: Carefully here - do not modify command from threads other than the one started command execution
   @NotNull
   public Command getCommand() {
@@ -344,4 +360,38 @@
       }
     }
   }
+
+  private static class BinaryOSProcessHandler extends OSProcessHandler {
+
+    @NotNull private final ByteArrayOutputStream myBinaryOutput;
+
+    public BinaryOSProcessHandler(@NotNull final Process process, @Nullable final String commandLine) {
+      super(process, commandLine);
+      myBinaryOutput = new ByteArrayOutputStream();
+    }
+
+    @NotNull
+    @Override
+    protected BaseDataReader createOutputDataReader(BaseDataReader.SleepingPolicy sleepingPolicy) {
+      return new SimpleBinaryOutputReader(myProcess.getInputStream(), sleepingPolicy);
+    }
+
+    private class SimpleBinaryOutputReader extends BinaryOutputReader {
+
+      public SimpleBinaryOutputReader(@NotNull InputStream stream, SleepingPolicy sleepingPolicy) {
+        super(stream, sleepingPolicy);
+        start();
+      }
+
+      @Override
+      protected void onBinaryAvailable(@NotNull byte[] data, int size) {
+        myBinaryOutput.write(data, 0, size);
+      }
+
+      @Override
+      protected Future<?> executeOnPooledThread(Runnable runnable) {
+        return BinaryOSProcessHandler.this.executeOnPooledThread(runnable);
+      }
+    }
+  }
 }
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/content/CmdContentClient.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/content/CmdContentClient.java
index 2b1c22e..d654253 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/content/CmdContentClient.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/content/CmdContentClient.java
@@ -10,6 +10,7 @@
 import org.tmatesoft.svn.core.wc.SVNRevision;
 import org.tmatesoft.svn.core.wc2.SvnTarget;
 
+import java.io.ByteArrayOutputStream;
 import java.util.ArrayList;
 import java.util.List;
 
@@ -22,17 +23,17 @@
   public byte[] getContent(@NotNull SvnTarget target, @Nullable SVNRevision revision, @Nullable SVNRevision pegRevision)
     throws VcsException, FileTooBigRuntimeException {
     // TODO: rewrite this to provide output as Stream
-    // TODO: rewrite without conversion from String to byte[]
     // TODO: Also implement max size constraint like in SvnKitContentClient
-    // TODO: Could not use export to get content of scheduled for deletion file - use cat command, but write special binary handler
+    // NOTE: Export could not be used to get content of scheduled for deletion file
 
     List<String> parameters = new ArrayList<String>();
     CommandUtil.put(parameters, target.getPathOrUrlString(), pegRevision);
     CommandUtil.put(parameters, revision);
 
     CommandExecutor command = CommandUtil.execute(myVcs, target, SvnCommandName.cat, parameters, null);
-
-    byte[] bytes = CharsetToolkit.getUtf8Bytes(command.getOutput());
+    // TODO: currently binary output will be null for terminal mode - use text output in this case
+    ByteArrayOutputStream output = command.getBinaryOutput();
+    byte[] bytes = output != null ? output.toByteArray() : CharsetToolkit.getUtf8Bytes(command.getOutput());
 
     ContentRevisionCache.checkContentsSize(target.getPathOrUrlString(), bytes.length);
 
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java
index 143d8f6..046a134 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/CopiesPanel.java
@@ -331,7 +331,7 @@
 
     try {
       result.addAll(factory.createUpgradeClient().getSupportedFormats());
-      result.addAll(otherFactory.createUpgradeClient().getSupportedFormats());
+      result.addAll(SvnFormatWorker.getOtherFactoryFormats(otherFactory));
     }
     catch (VcsException e) {
       LOG.info(e);
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SvnFormatWorker.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SvnFormatWorker.java
index dc67e89..dd22ac5 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SvnFormatWorker.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/dialogs/SvnFormatWorker.java
@@ -16,6 +16,7 @@
 package org.jetbrains.idea.svn.dialogs;
 
 import com.intellij.openapi.application.ApplicationManager;
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.progress.ProgressIndicator;
 import com.intellij.openapi.progress.Task;
 import com.intellij.openapi.project.Project;
@@ -26,6 +27,7 @@
 import com.intellij.openapi.vcs.VcsException;
 import com.intellij.openapi.vcs.changes.ChangeListManager;
 import com.intellij.openapi.vcs.changes.LocalChangeList;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.vcsUtil.VcsUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.idea.svn.SvnBundle;
@@ -46,6 +48,9 @@
 import java.util.List;
 
 public class SvnFormatWorker extends Task.Backgroundable {
+
+  private static final Logger LOG = Logger.getInstance(SvnFormatWorker.class);
+
   private List<Throwable> myExceptions;
   private final Project myProject;
   private final WorkingCopyFormat myNewFormat;
@@ -159,11 +164,25 @@
     ClientFactory factory = myVcs.getFactory(path);
     ClientFactory otherFactory = myVcs.getOtherFactory(factory);
     List<WorkingCopyFormat> factoryFormats = factory.createUpgradeClient().getSupportedFormats();
-    List<WorkingCopyFormat> otherFactoryFormats = otherFactory.createUpgradeClient().getSupportedFormats();
+    List<WorkingCopyFormat> otherFactoryFormats = getOtherFactoryFormats(otherFactory);
 
     return factoryFormats.contains(format) || !otherFactoryFormats.contains(format) ? factory : otherFactory;
   }
 
+  public static List<WorkingCopyFormat> getOtherFactoryFormats(@NotNull ClientFactory otherFactory) {
+    List<WorkingCopyFormat> result;
+
+    try {
+      result = otherFactory.createUpgradeClient().getSupportedFormats();
+    }
+    catch (VcsException e) {
+      result = ContainerUtil.newArrayList();
+      LOG.info("Failed to get upgrade formats from other factory", e);
+    }
+
+    return result;
+  }
+
   private static ISVNEventHandler createUpgradeHandler(@NotNull final ProgressIndicator indicator,
                                                        @NotNull final String cleanupMessage,
                                                        @NotNull final String upgradeMessage) {
diff --git a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java
index 1122088..cfafc65 100644
--- a/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java
+++ b/plugins/svn4idea/src/org/jetbrains/idea/svn/treeConflict/MergeFromTheirsResolver.java
@@ -23,7 +23,7 @@
 import com.intellij.openapi.fileEditor.FileDocumentManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.DialogWrapper;
-import com.intellij.openapi.ui.MessageBuilder;
+import com.intellij.openapi.ui.MessageDialogBuilder;
 import com.intellij.openapi.ui.MessageType;
 import com.intellij.openapi.ui.Messages;
 import com.intellij.openapi.util.Comparing;
@@ -594,7 +594,7 @@
     if (!containAdditions(myTheirsChanges) && !containAdditions(myTheirsBinaryChanges)) {
       return false;
     }
-    return Messages.YES == MessageBuilder.yesNo(TreeConflictRefreshablePanel.TITLE, "Keep newly created file(s) in their original place?").yesText("Keep").noText("Move").doNotAsk(
+    return Messages.YES == MessageDialogBuilder.yesNo(TreeConflictRefreshablePanel.TITLE, "Keep newly created file(s) in their original place?").yesText("Keep").noText("Move").doNotAsk(
       new DialogWrapper.DoNotAskOption() {
         @Override
         public boolean isToBeShown() {
diff --git a/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/BaseRepositoryImpl.java b/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/BaseRepositoryImpl.java
index 20f96a3..0d6c2ec 100644
--- a/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/BaseRepositoryImpl.java
+++ b/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/BaseRepositoryImpl.java
@@ -1,5 +1,6 @@
 package com.intellij.tasks.impl;
 
+import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.tasks.TaskRepositoryType;
 import com.intellij.tasks.config.TaskSettings;
 import com.intellij.tasks.impl.ssl.CertificatesManager;
@@ -12,6 +13,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import javax.net.ssl.SSLContext;
 import java.io.UnsupportedEncodingException;
 import java.net.URLEncoder;
 
@@ -23,8 +25,18 @@
 public abstract class BaseRepositoryImpl extends BaseRepository {
   public static final String EASY_HTTPS = "easyhttps";
 
+  private static final Logger LOG = Logger.getInstance(BaseRepositoryImpl.class);
+
   static {
-    Protocol.registerProtocol("https", CertificatesManager.createDefault().createProtocol());
+    try {
+      SSLContext context = CertificatesManager.createDefault().createSslContext();
+      SSLContext.setDefault(context);
+    }
+    catch (Exception e) {
+      LOG.error(e);
+    }
+    // Don't do this: protocol created this way will ignore SSL tunnels. See IDEA-115708.
+    // Protocol.registerProtocol("https", CertificatesManager.createDefault().createProtocol());
     Protocol.registerProtocol(EASY_HTTPS, new Protocol(EASY_HTTPS, (ProtocolSocketFactory)new EasySSLProtocolSocketFactory(), 443));
   }
 
diff --git a/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/ssl/CertificatesManager.java b/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/ssl/CertificatesManager.java
index d3c6a8f..9ade70c 100644
--- a/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/ssl/CertificatesManager.java
+++ b/plugins/tasks/tasks-api/src/com/intellij/tasks/impl/ssl/CertificatesManager.java
@@ -152,7 +152,7 @@
         X509Certificate certificate = certificates[0];
         // looks like self-signed certificate
         if (certificates.length == 1 && certificateIsSelfSigned(certificate)) {
-          // check-the-act sequence
+          // check-then-act sequence
           synchronized (myCustomManager) {
             try {
               myCustomManager.checkServerTrusted(certificates, s);
diff --git a/plugins/tasks/tasks-core/src/META-INF/plugin.xml b/plugins/tasks/tasks-core/src/META-INF/plugin.xml
index 1ff3f1b..b558f4e 100644
--- a/plugins/tasks/tasks-core/src/META-INF/plugin.xml
+++ b/plugins/tasks/tasks-core/src/META-INF/plugin.xml
@@ -72,7 +72,7 @@
         <keyboard-shortcut keymap="$default" first-keystroke="alt shift T"/>
       </action>
       <add-to-group group-id="MainToolBar" anchor="last"/>
-      <add-to-group group-id="NavBarToolBar" anchor="last"/>
+      <add-to-group group-id="NavBarToolBarOthers" anchor="last"/>
     </group>
 
     <!--
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/JiraRestApi.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/JiraRestApi.java
index f9b9a78..c056128 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/JiraRestApi.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/JiraRestApi.java
@@ -91,26 +91,23 @@
   public abstract String getVersionName();
 
   public void setTaskState(Task task, TaskState state) throws Exception {
-    String requestBody;
-    switch (state) {
-      case IN_PROGRESS:
-        requestBody = "{\"transition\": \"4\"}";
-        break;
-      case RESOLVED:
-        // 5 for "Resolved", 2 for "Close"
-        requestBody = "{\"transition\": \"5\", \"resolution\": \"Fixed\"}";
-        break;
-      case REOPENED:
-        requestBody = "{\"transition\": \"3\"}";
-        break;
-      default:
-        return;
+    String requestBody = getRequestForStateTransition(state);
+    if (requestBody == null) {
+      return;
     }
-    // REST API 2.0 require double quotes both around field names and values (even numbers)
-    // REST API 2.0alpha1 permits to omit them, but handles both variants
     final String transitionsUrl = myRepository.getUrl() + REST_API_PATH_SUFFIX + "/issue/" + task.getId() + "/transitions";
+    LOG.debug(String.format("Transition destination: %s, request: %s", state, requestBody));
     final PostMethod method = new PostMethod(transitionsUrl);
     method.setRequestEntity(new StringRequestEntity(requestBody, "application/json", "utf-8"));
-    myRepository.executeMethod(method);
+    try {
+      myRepository.executeMethod(method);
+    }
+    catch (Exception e) {
+      LOG.warn(String.format("Transition destination: %s, server URL: %s", state, myRepository.getUrl()), e);
+      throw e;
+    }
   }
+
+  @Nullable
+  protected abstract String getRequestForStateTransition(@NotNull TaskState state);
 }
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api2/JiraRestApi2.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api2/JiraRestApi2.java
index 677902e..a8a88ea 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api2/JiraRestApi2.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api2/JiraRestApi2.java
@@ -2,6 +2,7 @@
 
 import com.google.gson.reflect.TypeToken;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.tasks.TaskState;
 import com.intellij.tasks.jira.JiraRepository;
 import com.intellij.tasks.jira.JiraRestApi;
 import com.intellij.tasks.jira.JiraUtil;
@@ -59,6 +60,23 @@
     return JiraUtil.GSON.fromJson(response, JiraIssueApi2.class);
   }
 
+  @Nullable
+  @Override
+  protected String getRequestForStateTransition(@NotNull TaskState state) {
+    // REST API 2.0 require double quotes both around field names and values (even numbers)
+    switch (state) {
+      case IN_PROGRESS:
+        return  "{\"transition\": {\"id\": \"4\"}}";
+      case RESOLVED:
+        // 5 for "Resolved", 2 for "Closed"
+        return  "{\"transition\": {\"id\": \"5\"}, \"fields\": {\"resolution\": {\"name\": \"Fixed\"}}}";
+      case REOPENED:
+        return  "{\"transition\": {\"id\": \"3\"}}";
+      default:
+        return null;
+    }
+  }
+
   @NotNull
   @Override
   public String getVersionName() {
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api20alpha1/JiraRestApi20Alpha1.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api20alpha1/JiraRestApi20Alpha1.java
index 21cc343..df0ff53f 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api20alpha1/JiraRestApi20Alpha1.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/jira/model/api20alpha1/JiraRestApi20Alpha1.java
@@ -2,12 +2,14 @@
 
 import com.google.gson.reflect.TypeToken;
 import com.intellij.openapi.diagnostic.Logger;
+import com.intellij.tasks.TaskState;
 import com.intellij.tasks.jira.JiraRepository;
 import com.intellij.tasks.jira.JiraRestApi;
 import com.intellij.tasks.jira.JiraUtil;
 import com.intellij.tasks.jira.model.JiraIssue;
 import com.intellij.tasks.jira.model.JiraResponseWrapper;
 import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.lang.reflect.Type;
 import java.util.ArrayList;
@@ -47,6 +49,22 @@
     return updatedIssues;
   }
 
+  @Nullable
+  @Override
+  protected String getRequestForStateTransition(@NotNull TaskState state) {
+    switch (state) {
+      case IN_PROGRESS:
+        return  "{\"transition\": \"4\"}";
+      case RESOLVED:
+        // 5 for "Resolved", 2 for "Closed"
+        return  "{\"transition\": \"5\", \"resolution\": \"Fixed\"}";
+      case REOPENED:
+        return  "{\"transition\": \"3\"}";
+      default:
+        return null;
+    }
+  }
+
   @NotNull
   @Override
   public String getVersionName() {
diff --git a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java
index b69f648..7af64fa 100644
--- a/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java
+++ b/plugins/tasks/tasks-core/src/com/intellij/tasks/mantis/MantisRepositoryEditor.java
@@ -1,12 +1,11 @@
 package com.intellij.tasks.mantis;
 
-import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.ui.ComboBox;
-import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.tasks.config.BaseRepositoryEditor;
 import com.intellij.ui.components.JBLabel;
 import com.intellij.util.Consumer;
+import com.intellij.util.UriUtil;
 import com.intellij.util.ui.FormBuilder;
 import org.jetbrains.annotations.Nullable;
 
@@ -19,8 +18,6 @@
  * Date: 9/21/12
  */
 public class MantisRepositoryEditor extends BaseRepositoryEditor<MantisRepository> {
-  private static final Logger LOG = Logger.getInstance("#com.intellij.tasks.mantis.MantisRepositoryEditor");
-
   private ComboBox myProjectCombobox;
   private ComboBox myFilterCombobox;
   private JBLabel myProjectLabel;
@@ -35,7 +32,7 @@
 
   @Override
   public void apply() {
-    if (!myRepository.getUrl().equals(StringUtil.trimEnd(myURLText.getText(), "/")) ||
+    if (!myRepository.getUrl().equals(UriUtil.trimLastSlash(myURLText.getText())) ||
         !myRepository.getUsername().equals(myUserNameText.getText()) ||
         !myRepository.getPassword().equals(myPasswordText.getText())) {
       resetComboBoxes();
diff --git a/plugins/tasks/tasks-core/tasks-core.iml b/plugins/tasks/tasks-core/tasks-core.iml
index 460f43f..7094b91 100644
--- a/plugins/tasks/tasks-core/tasks-core.iml
+++ b/plugins/tasks/tasks-core/tasks-core.iml
@@ -27,15 +27,6 @@
     </orderEntry>
     <orderEntry type="library" exported="" name="http-client-3.1" level="project" />
     <orderEntry type="library" name="XmlRPC" level="project" />
-    <orderEntry type="module-library" exported="">
-      <library name="markdownj">
-        <CLASSES>
-          <root url="jar://$MODULE_DIR$/lib/markdownj-core-0.4.2-SNAPSHOT.jar!/" />
-        </CLASSES>
-        <JAVADOC />
-        <SOURCES />
-      </library>
-    </orderEntry>
     <orderEntry type="library" name="gson" level="project" />
     <orderEntry type="module" module-name="xml" />
     <orderEntry type="module" module-name="core-api" />
diff --git a/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java b/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java
index 3780bd8..fc5ed55 100644
--- a/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java
+++ b/plugins/tasks/tasks-tests/test/com/intellij/tasks/integration/JiraIntegrationTest.java
@@ -52,6 +52,7 @@
   public void testLogin() throws Exception {
     myRepository.setUsername("german");
     myRepository.setUsername("wrong password");
+    //noinspection ConstantConditions
     Exception exception = myRepository.createCancellableConnection().call();
     assertNotNull(exception);
     assertEquals(JiraRepository.LOGIN_FAILED_CHECK_YOUR_PERMISSIONS, exception.getMessage());
@@ -88,6 +89,7 @@
     changeStateAndCheck(JIRA_5_TEST_SERVER_URL, "UT-8");
   }
 
+  @SuppressWarnings("ConstantConditions")
   private void changeStateAndCheck(String url, String key) throws Exception {
     myRepository.setUrl(url);
     Task task = myRepository.findTask(key);
diff --git a/plugins/terminal/lib/jediterm-pty-1.0.jar b/plugins/terminal/lib/jediterm-pty-1.0.jar
index bb04f22..ae4c9c5 100644
--- a/plugins/terminal/lib/jediterm-pty-1.0.jar
+++ b/plugins/terminal/lib/jediterm-pty-1.0.jar
Binary files differ
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java
index 767df1e..259d93c 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalPanel.java
@@ -114,6 +114,7 @@
 
   @Override
   protected void setupAntialiasing(Graphics graphics) {
+    UIUtil.setupComposite((Graphics2D)graphics);
     UISettings.setupAntialiasing(graphics);
   }
 
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSystemSettingsProvider.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSystemSettingsProvider.java
index 4adeb3c..94479c9 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSystemSettingsProvider.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/JBTerminalSystemSettingsProvider.java
@@ -35,7 +35,7 @@
  */
 class JBTerminalSystemSettingsProvider extends DefaultTabbedSettingsProvider implements Disposable {
   private Set<TerminalSettingsListener> myListeners = Sets.newHashSet();
-  
+
   private final MyColorSchemeDelegate myColorScheme;
 
   JBTerminalSystemSettingsProvider() {
@@ -151,19 +151,11 @@
   public String getFontName() {
     List<String> fonts = myColorScheme.getConsoleFontPreferences().getEffectiveFontFamilies();
 
-    for (String font : fonts) {
-      if (isApplicable(font)) {
-        return font;
-      }
+    if (fonts.size() > 0) {
+      return fonts.get(0);
     }
-    return "Monospaced-14";
-  }
 
-  private static boolean isApplicable(String font) {
-    if ("Source Code Pro".equals(font)) {
-      return false;
-    }
-    return true;
+    return "Monospaced-14";
   }
 
   @Override
@@ -174,7 +166,7 @@
 
   @Override
   public boolean useAntialiasing() {
-    return UISettings.getInstance().ANTIALIASING_IN_EDITOR;
+    return true; // we return true here because all the settings are checked again in UiSettings.setupAntialiasing
   }
 
   @Override
@@ -215,6 +207,11 @@
   }
 
   @Override
+  public boolean allowSelectionOnMouseReporting() {
+    return true;
+  }
+
+  @Override
   public void dispose() {
 
   }
@@ -314,7 +311,7 @@
 
     @Override
     public void setFontPreferences(@NotNull FontPreferences preferences) {
-      throw new IllegalStateException();      
+      throw new IllegalStateException();
     }
 
     @Override
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java
index 064dad9..3d0ec61 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/LocalTerminalDirectRunner.java
@@ -33,32 +33,10 @@
   private static final Logger LOG = Logger.getInstance(LocalTerminalDirectRunner.class);
 
   private final Charset myDefaultCharset;
-  private final String[] myCommand;
 
   public LocalTerminalDirectRunner(Project project) {
     super(project);
     myDefaultCharset = Charset.forName("UTF-8");
-
-    String shellPath = TerminalOptionsProvider.getInstance().getShellPath();
-
-    if (SystemInfo.isUnix) {
-      File rcFile = findRCFile();
-
-      String shellName = getShellName(shellPath);
-
-      if (rcFile != null && (shellName.equals("bash") || shellName.equals("sh"))) {
-        myCommand = new String[]{shellPath, "--rcfile", rcFile.getAbsolutePath(), "-i"};
-      }
-      else if (hasLoginArgument(shellName)) {
-        myCommand = new String[]{shellPath, "--login"};
-      }
-      else {
-        myCommand = shellPath.split(" ");
-      }
-    }
-    else {
-      myCommand = new String[]{shellPath};
-    }
   }
 
   private static boolean hasLoginArgument(String name) {
@@ -71,7 +49,7 @@
 
   private static File findRCFile() {
     try {
-      final String folder = PtyUtil.getJarFolder();
+      final String folder = PtyUtil.getPtyLibFolderPath();
       if (folder != null) {
         File rcFile = new File(folder, "jediterm.in");
         if (rcFile.exists()) {
@@ -90,7 +68,7 @@
     Map<String, String> envs = new HashMap<String, String>(System.getenv());
     envs.put("TERM", "xterm");
     try {
-      return PtyProcess.exec(myCommand, envs, currentProjectFolder());
+      return PtyProcess.exec(getCommand(), envs, currentProjectFolder());
     }
     catch (IOException e) {
       throw new ExecutionException(e);
@@ -116,7 +94,33 @@
 
   @Override
   protected String getTerminalConnectionName(PtyProcess process) {
-    return StringUtil.join(myCommand);
+    return "Local Terminal";
+  }
+
+  public String[] getCommand() {
+    String[] command;
+    String shellPath = TerminalOptionsProvider.getInstance().getShellPath();
+
+    if (SystemInfo.isUnix) {
+      File rcFile = findRCFile();
+
+      String shellName = getShellName(shellPath);
+
+      if (rcFile != null && (shellName.equals("bash") || shellName.equals("sh"))) {
+        command = new String[]{shellPath, "--rcfile", rcFile.getAbsolutePath(), "-i"};
+      }
+      else if (hasLoginArgument(shellName)) {
+        command = new String[]{shellPath, "--login"};
+      }
+      else {
+        command = shellPath.split(" ");
+      }
+    }
+    else {
+      command = new String[]{shellPath};
+    }
+
+    return command;
   }
 
   private static class PtyProcessHandler extends ProcessHandler implements TaskExecutor {
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalOptionsProvider.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalOptionsProvider.java
index dd59065..840bf05 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalOptionsProvider.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalOptionsProvider.java
@@ -18,10 +18,7 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.components.*;
-import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.SystemInfo;
-import com.intellij.openapi.util.text.StringUtil;
-import com.jediterm.terminal.emulator.ColorPalette;
 import org.jetbrains.annotations.NotNull;
 
 import java.io.File;
@@ -90,6 +87,12 @@
   }
 
   private static String getDefaultShellPath() {
+    String shell = System.getenv("SHELL");
+    
+    if (shell != null && new File(shell).canExecute()) {
+      return shell;
+    }
+    
     if (SystemInfo.isUnix) {
       return "/bin/bash";
     }
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.form b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.form
index 45678d4..c4dd803 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.form
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.form
@@ -19,7 +19,7 @@
         </clientProperties>
         <border type="none"/>
         <children>
-          <grid id="57ec0" layout-manager="GridLayoutManager" row-count="2" column-count="2" same-size-horizontally="false" same-size-vertically="false" hgap="-1" vgap="-1">
+          <grid id="57ec0" 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="0" column="0" row-span="1" col-span="3" vsize-policy="3" hsize-policy="3" anchor="0" fill="3" indent="0" use-parent-layout="false"/>
@@ -33,17 +33,9 @@
                 </constraints>
                 <properties>
                   <horizontalTextPosition value="2"/>
-                  <text value="Default shell"/>
+                  <text value="Shell path"/>
                 </properties>
               </component>
-              <component id="8b4db" class="javax.swing.JTextField" binding="myShellTextField">
-                <constraints>
-                  <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
-                    <preferred-size width="150" height="-1"/>
-                  </grid>
-                </constraints>
-                <properties/>
-              </component>
               <component id="f633a" 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"/>
@@ -55,12 +47,18 @@
               </component>
               <component id="5495b" class="javax.swing.JTextField" binding="myTabNameTextField">
                 <constraints>
-                  <grid row="1" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
+                  <grid row="1" column="1" row-span="1" col-span="2" vsize-policy="0" hsize-policy="6" anchor="8" fill="1" indent="0" use-parent-layout="false">
                     <preferred-size width="150" height="-1"/>
                   </grid>
                 </constraints>
                 <properties/>
               </component>
+              <component id="aad87" class="com.intellij.openapi.ui.TextFieldWithBrowseButton" binding="myShellPathField">
+                <constraints>
+                  <grid row="0" column="1" row-span="1" col-span="1" vsize-policy="0" hsize-policy="6" anchor="0" fill="1" indent="0" use-parent-layout="false"/>
+                </constraints>
+                <properties/>
+              </component>
             </children>
           </grid>
           <vspacer id="d777c">
diff --git a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java
index 0400bb3..ff0a771 100644
--- a/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java
+++ b/plugins/terminal/src/org/jetbrains/plugins/terminal/TerminalSettingsPanel.java
@@ -15,9 +15,12 @@
  */
 package org.jetbrains.plugins.terminal;
 
-import com.intellij.openapi.Disposable;
+import com.intellij.openapi.fileChooser.FileChooserDescriptor;
+import com.intellij.openapi.ui.TextComponentAccessor;
+import com.intellij.openapi.ui.TextFieldWithBrowseButton;
 import com.intellij.openapi.util.Comparing;
 import com.intellij.ui.components.JBCheckBox;
+import org.jetbrains.annotations.NotNull;
 
 import javax.swing.*;
 
@@ -26,7 +29,7 @@
  */
 public class TerminalSettingsPanel {
   private JPanel myWholePanel;
-  private JTextField myShellTextField;
+  private TextFieldWithBrowseButton myShellPathField;
   private JBCheckBox mySoundBellCheckBox;
   private JBCheckBox myCloseSessionCheckBox;
   private JBCheckBox myMouseReportCheckBox;
@@ -35,14 +38,25 @@
   private JBCheckBox myCopyOnSelectionCheckBox;
   private TerminalOptionsProvider myOptionsProvider;
 
-  public JComponent createPanel(TerminalOptionsProvider provider) {
+  public JComponent createPanel(@NotNull TerminalOptionsProvider provider) {
     myOptionsProvider = provider;
 
+    FileChooserDescriptor fileChooserDescriptor = new FileChooserDescriptor(true, false, false, false, false, false);
+
+    myShellPathField.addBrowseFolderListener(
+      "",
+      "Shell Executable Path",
+      null,
+      fileChooserDescriptor,
+      TextComponentAccessor.TEXT_FIELD_WHOLE_TEXT,
+      false
+    );
+
     return myWholePanel;
   }
 
   public boolean isModified() {
-    return !Comparing.equal(myShellTextField.getText(), myOptionsProvider.getShellPath())
+    return !Comparing.equal(myShellPathField.getText(), myOptionsProvider.getShellPath())
            || !Comparing.equal(myTabNameTextField.getText(), myOptionsProvider.getTabName())
            || (myCloseSessionCheckBox.isSelected() != myOptionsProvider.closeSessionOnLogout())
            || (myMouseReportCheckBox.isSelected() != myOptionsProvider.enableMouseReporting())
@@ -53,7 +67,7 @@
   }
 
   public void apply() {
-    myOptionsProvider.setShellPath(myShellTextField.getText());
+    myOptionsProvider.setShellPath(myShellPathField.getText());
     myOptionsProvider.setTabName(myTabNameTextField.getText());
     myOptionsProvider.setCloseSessionOnLogout(myCloseSessionCheckBox.isSelected());
     myOptionsProvider.setReportMouse(myMouseReportCheckBox.isSelected());
@@ -63,7 +77,7 @@
   }
 
   public void reset() {
-    myShellTextField.setText(myOptionsProvider.getShellPath());
+    myShellPathField.setText(myOptionsProvider.getShellPath());
     myTabNameTextField.setText(myOptionsProvider.getTabName());
     myCloseSessionCheckBox.setSelected(myOptionsProvider.closeSessionOnLogout());
     myMouseReportCheckBox.setSelected(myOptionsProvider.enableMouseReporting());
diff --git a/plugins/testng/src/com/theoryinpractice/testng/DataProviderSearcher.java b/plugins/testng/src/com/theoryinpractice/testng/DataProviderSearcher.java
index 9e454a4..8a42056 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/DataProviderSearcher.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/DataProviderSearcher.java
@@ -36,7 +36,7 @@
 
     final PsiAnnotation annotation = AnnotationUtil.findAnnotation(method, DataProvider.class.getName());
     if (annotation == null) return;
-    final PsiAnnotationMemberValue dataProviderMethodName = annotation.findAttributeValue("name");
+    final PsiAnnotationMemberValue dataProviderMethodName = annotation.findDeclaredAttributeValue("name");
     if (dataProviderMethodName != null) {
       final String providerName = StringUtil.unquoteString(dataProviderMethodName.getText());
       queryParameters.getOptimizer().searchWord(providerName, queryParameters.getScope(), UsageSearchContext.IN_STRINGS, true, method);
diff --git a/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java b/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java
index 09a08f7..e848397 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/TestNGReferenceContributor.java
@@ -98,7 +98,7 @@
         for (PsiMethod method : methods) {
           PsiAnnotation dataProviderAnnotation = AnnotationUtil.findAnnotation(method, DataProvider.class.getName());
           if (dataProviderAnnotation != null) {
-            final PsiAnnotationMemberValue dataProviderMethodName = dataProviderAnnotation.findAttributeValue("name");
+            final PsiAnnotationMemberValue dataProviderMethodName = dataProviderAnnotation.findDeclaredAttributeValue("name");
             if (dataProviderMethodName != null && val.equals(StringUtil.unquoteString(dataProviderMethodName.getText()))) {
               return method;
             }
@@ -129,8 +129,7 @@
           }
           final PsiAnnotation dataProviderAnnotation = AnnotationUtil.findAnnotation(method, DataProvider.class.getName());
           if (dataProviderAnnotation != null) {
-            boolean nameFoundInAttributes = false;
-            final PsiAnnotationMemberValue memberValue = dataProviderAnnotation.findAttributeValue("name");
+            final PsiAnnotationMemberValue memberValue = dataProviderAnnotation.findDeclaredAttributeValue("name");
             if (memberValue != null) {
               list.add(LookupValueFactory.createLookupValue(StringUtil.unquoteString(memberValue.getText()), null));
               list.add(LookupValueFactory.createLookupValue(method.getName(), null));
@@ -144,7 +143,7 @@
     private PsiClass getProviderClass(final PsiClass topLevelClass) {
       final PsiAnnotation annotation = PsiTreeUtil.getParentOfType(getElement(), PsiAnnotation.class);
       if (annotation != null) {
-        final PsiAnnotationMemberValue value = annotation.findAttributeValue("dataProviderClass");
+        final PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue("dataProviderClass");
         if (value instanceof PsiClassObjectAccessExpression) {
           final PsiTypeElement operand = ((PsiClassObjectAccessExpression)value).getOperand();
           final PsiClass psiClass = PsiUtil.resolveClassInType(operand.getType());
diff --git a/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnMethodInspection.java b/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnMethodInspection.java
index f60b1d3..b8cf78a 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnMethodInspection.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/inspection/DependsOnMethodInspection.java
@@ -72,7 +72,7 @@
         List<ProblemDescriptor> problemDescriptors = new ArrayList<ProblemDescriptor>();
 
         for (PsiAnnotation annotation : annotations) {
-          final PsiAnnotationMemberValue value = annotation.findAttributeValue("dependsOnMethods");
+          final PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue("dependsOnMethods");
           if (value != null) {
             String text = value.getText();
             if (value instanceof PsiReferenceExpression) {
diff --git a/plugins/testng/src/com/theoryinpractice/testng/inspection/ExpectedExceptionNeverThrownTestNGInspection.java b/plugins/testng/src/com/theoryinpractice/testng/inspection/ExpectedExceptionNeverThrownTestNGInspection.java
index f3a808e..a8abfe8 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/inspection/ExpectedExceptionNeverThrownTestNGInspection.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/inspection/ExpectedExceptionNeverThrownTestNGInspection.java
@@ -55,7 +55,7 @@
       if (annotation == null) {
         return;
       }
-      final PsiAnnotationMemberValue value = annotation.findAttributeValue("expectedExceptions");
+      final PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue("expectedExceptions");
       if (!(value instanceof PsiClassObjectAccessExpression)) {
         return;
       }
diff --git a/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java b/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java
index e635c2a..7958cc3 100644
--- a/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java
+++ b/plugins/testng/src/com/theoryinpractice/testng/util/TestNGUtil.java
@@ -315,7 +315,7 @@
   }
 
   public static boolean isAnnotatedWithParameter(PsiAnnotation annotation, String parameter, Set<String> values) {
-    final PsiAnnotationMemberValue attributeValue = annotation.findAttributeValue(parameter);
+    final PsiAnnotationMemberValue attributeValue = annotation.findDeclaredAttributeValue(parameter);
     if (attributeValue != null) {
       Collection<String> matches = extractValuesFromParameter(attributeValue);
       for (String s : matches) {
@@ -375,7 +375,7 @@
                                                       final PsiAnnotation annotation,
                                                       final PsiDocCommentOwner commentOwner) {
     if (annotation != null) {
-      final PsiAnnotationMemberValue value = annotation.findAttributeValue(parameter);
+      final PsiAnnotationMemberValue value = annotation.findDeclaredAttributeValue(parameter);
       if (value != null) {
         results.addAll(extractValuesFromParameter(value));
       }
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/editor/MyEditorState.java b/plugins/ui-designer/src/com/intellij/uiDesigner/editor/MyEditorState.java
index fef1e13..4ecd1e4 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/editor/MyEditorState.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/editor/MyEditorState.java
@@ -50,6 +50,7 @@
     return (int)(myDocumentModificationStamp ^ (myDocumentModificationStamp >>> 32));
   }
 
+  @Override
   public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
     return otherState instanceof MyEditorState;
   }
diff --git a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java
index 624e321..a4b0f84 100644
--- a/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java
+++ b/plugins/ui-designer/src/com/intellij/uiDesigner/snapShooter/SnapShooterConfigurationExtension.java
@@ -45,7 +45,6 @@
 import org.jdom.Element;
 import org.jetbrains.annotations.NotNull;
 
-import java.io.IOException;
 import java.util.Set;
 import java.util.TreeSet;
 
@@ -65,12 +64,7 @@
       appConfiguration.putUserData(SnapShooterConfigurationSettings.SNAP_SHOOTER_KEY, settings);
     }
     if (appConfiguration.ENABLE_SWING_INSPECTOR) {
-      try {
-        settings.setLastPort(NetUtils.findAvailableSocketPort());
-      }
-      catch(IOException ex) {
-        settings.setLastPort(-1);
-      }
+      settings.setLastPort(NetUtils.tryToFindAvailableSocketPort());
     }
 
     if (appConfiguration.ENABLE_SWING_INSPECTOR && settings.getLastPort() != -1) {
diff --git a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java
index c1d45c2..e2886b3 100644
--- a/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java
+++ b/plugins/xpath/xpath-lang/src/org/intellij/lang/xpath/xslt/run/XsltCommandLineState.java
@@ -27,6 +27,7 @@
 import com.intellij.ide.BrowserUtil;
 import com.intellij.ide.plugins.IdeaPluginDescriptor;
 import com.intellij.ide.plugins.PluginManager;
+import com.intellij.ide.plugins.PluginManagerCore;
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.application.ex.ApplicationManagerEx;
 import com.intellij.openapi.components.PathMacroManager;
@@ -50,7 +51,6 @@
 
 import javax.swing.*;
 import java.io.File;
-import java.io.IOException;
 import java.util.List;
 
 import static org.intellij.lang.xpath.xslt.run.XsltRunConfiguration.isEmpty;
@@ -86,105 +86,104 @@
     }
 
     protected SimpleJavaParameters createJavaParameters() throws ExecutionException {
-        final Sdk jdk = myXsltRunConfiguration.getEffectiveJDK();
-        if (jdk == null) {
-            throw CantRunException.noJdkConfigured();
+      final Sdk jdk = myXsltRunConfiguration.getEffectiveJDK();
+      if (jdk == null) {
+        throw CantRunException.noJdkConfigured();
+      }
+
+      final SimpleJavaParameters parameters = new SimpleJavaParameters();
+      parameters.setJdk(jdk);
+
+      if (myXsltRunConfiguration.getJdkChoice() == XsltRunConfiguration.JdkChoice.FROM_MODULE) {
+        final Module module = myXsltRunConfiguration.getEffectiveModule();
+        // relaxed check for valid module: when running XSLTs that don't belong to any module, let's assume it is
+        // OK to run as if just a JDK has been selected (a missing JDK would already have been complained about above)
+        if (module != null) {
+          OrderEnumerator.orderEntries(module).productionOnly().recursively().classes().collectPaths(parameters.getClassPath());
         }
+      }
 
-        final SimpleJavaParameters parameters = new SimpleJavaParameters();
-        parameters.setJdk(jdk);
+      final ParametersList vmParameters = parameters.getVMParametersList();
+      vmParameters.addParametersString(myXsltRunConfiguration.myVmArguments);
+      if (isEmpty(myXsltRunConfiguration.getXsltFile())) {
+        throw new CantRunException("No XSLT file selected");
+      }
+      vmParameters.defineProperty("xslt.file", myXsltRunConfiguration.getXsltFile());
+      if (isEmpty(myXsltRunConfiguration.getXmlInputFile())) {
+        throw new CantRunException("No XML input file selected");
+      }
+      vmParameters.defineProperty("xslt.input", myXsltRunConfiguration.getXmlInputFile());
 
-        if (myXsltRunConfiguration.getJdkChoice() == XsltRunConfiguration.JdkChoice.FROM_MODULE) {
-            final Module module = myXsltRunConfiguration.getEffectiveModule();
-            // relaxed check for valid module: when running XSLTs that don't belong to any module, let's assume it is
-            // OK to run as if just a JDK has been selected (a missing JDK would already have been complained about above) 
-            if (module != null) {
-              OrderEnumerator.orderEntries(module).productionOnly().recursively().classes().collectPaths(parameters.getClassPath());
-            }
+      final XsltRunConfiguration.OutputType outputType = myXsltRunConfiguration.getOutputType();
+      if (outputType == XsltRunConfiguration.OutputType.CONSOLE) {
+        //noinspection deprecation
+        myPort = NetUtils.tryToFindAvailableSocketPort(myXsltRunConfiguration.myRunnerPort);
+        vmParameters.defineProperty("xslt.listen-port", String.valueOf(myPort));
+      }
+      if (myXsltRunConfiguration.isSaveToFile()) {
+        vmParameters.defineProperty("xslt.output", myXsltRunConfiguration.myOutputFile);
+      }
+
+      for (Pair<String, String> pair : myXsltRunConfiguration.getParameters()) {
+        final String name = pair.getFirst();
+        final String value = pair.getSecond();
+        if (isEmpty(name) || value == null) continue;
+        vmParameters.defineProperty("xslt.param." + name, value);
+      }
+      vmParameters.defineProperty("xslt.smart-error-handling", String.valueOf(myXsltRunConfiguration.mySmartErrorHandling));
+
+      final PluginId pluginId = PluginManagerCore.getPluginByClassName(getClass().getName());
+      assert pluginId != null || System.getProperty("xslt.plugin.path") != null : "PluginId not found - development builds need to specify -Dxslt.plugin.path=../out/classes/production/xslt-rt";
+
+      final File pluginPath;
+      if (pluginId != null) {
+        final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(pluginId);
+        assert descriptor != null;
+        pluginPath = descriptor.getPath();
+      }
+      else {
+        // -Dxslt.plugin.path=C:\work\java\intellij/ultimate\out\classes\production\xslt-rt
+        pluginPath = new File(System.getProperty("xslt.plugin.path"));
+      }
+
+      LOG.debug("Plugin Path = " + pluginPath.getAbsolutePath());
+
+      final char c = File.separatorChar;
+      File rtClasspath = new File(pluginPath, "lib" + c + "rt" + c + "xslt-rt.jar");
+      //        File rtClasspath = new File("C:/Demetra/plugins/xpath/lib/rt/xslt-rt.jar");
+      if (!rtClasspath.exists()) {
+        LOG.warn("Plugin's Runtime classes not found in " + rtClasspath.getAbsolutePath());
+        if (!(rtClasspath = new File(pluginPath, "classes")).exists()) {
+          if (ApplicationManagerEx.getApplicationEx().isInternal() && new File(pluginPath, "org").exists()) {
+            rtClasspath = pluginPath;
+          }
+          else {
+            throw new CantRunException("Runtime classes not found");
+          }
         }
+        parameters.getVMParametersList().prepend("-ea");
+      }
+      parameters.getClassPath().addTail(rtClasspath.getAbsolutePath());
 
-        final ParametersList vmParameters = parameters.getVMParametersList();
-        vmParameters.addParametersString(myXsltRunConfiguration.myVmArguments);
-        if (isEmpty(myXsltRunConfiguration.getXsltFile())) {
-            throw new CantRunException("No XSLT file selected");
-        }
-        vmParameters.defineProperty("xslt.file", myXsltRunConfiguration.getXsltFile());
-        if (isEmpty(myXsltRunConfiguration.getXmlInputFile())) {
-            throw new CantRunException("No XML input file selected");
-        }
-        vmParameters.defineProperty("xslt.input", myXsltRunConfiguration.getXmlInputFile());
-
-        final XsltRunConfiguration.OutputType outputType = myXsltRunConfiguration.getOutputType();
-        if (outputType == XsltRunConfiguration.OutputType.CONSOLE) {
-            try {
-                myPort = NetUtils.findAvailableSocketPort();
-            } catch (IOException e) {
-                //noinspection deprecation
-                myPort = myXsltRunConfiguration.myRunnerPort;
-            }
-            vmParameters.defineProperty("xslt.listen-port", String.valueOf(myPort));
-        } 
-        if (myXsltRunConfiguration.isSaveToFile()) {
-            vmParameters.defineProperty("xslt.output", myXsltRunConfiguration.myOutputFile);
-        }
-
-        for (Pair<String, String> pair : myXsltRunConfiguration.getParameters()) {
-            final String name = pair.getFirst();
-            final String value = pair.getSecond();
-            if (isEmpty(name) || value == null) continue;
-            vmParameters.defineProperty("xslt.param." + name, value);
-        }
-        vmParameters.defineProperty("xslt.smart-error-handling", String.valueOf(myXsltRunConfiguration.mySmartErrorHandling));
-
-        final PluginId pluginId = PluginManager.getPluginByClassName(getClass().getName());
-        assert pluginId != null || System.getProperty("xslt.plugin.path") != null : "PluginId not found - development builds need to specify -Dxslt.plugin.path=../out/classes/production/xslt-rt";
-
-        final File pluginPath;
-        if (pluginId != null) {
-            final IdeaPluginDescriptor descriptor = PluginManager.getPlugin(pluginId);
-            assert descriptor != null;
-            pluginPath = descriptor.getPath();
-        } else {
-          // -Dxslt.plugin.path=C:\work\java\intellij/ultimate\out\classes\production\xslt-rt
-          pluginPath = new File(System.getProperty("xslt.plugin.path"));
-        }
-
-        LOG.debug("Plugin Path = " + pluginPath.getAbsolutePath());
-
-        final char c = File.separatorChar;
-        File rtClasspath = new File(pluginPath, "lib" + c + "rt" + c + "xslt-rt.jar");
-//        File rtClasspath = new File("C:/Demetra/plugins/xpath/lib/rt/xslt-rt.jar");
-        if (!rtClasspath.exists()) {
-            LOG.warn("Plugin's Runtime classes not found in " + rtClasspath.getAbsolutePath());
-            if (!(rtClasspath = new File(pluginPath, "classes")).exists()) {
-              if (ApplicationManagerEx.getApplicationEx().isInternal() && new File(pluginPath, "org").exists()) {
-                rtClasspath = pluginPath;
-              } else {
-                throw new CantRunException("Runtime classes not found");
-              }
-            }
-            parameters.getVMParametersList().prepend("-ea");
-        }
-        parameters.getClassPath().addTail(rtClasspath.getAbsolutePath());
-
-        parameters.setMainClass("org.intellij.plugins.xslt.run.rt.XSLTRunner");
+      parameters.setMainClass("org.intellij.plugins.xslt.run.rt.XSLTRunner");
 
       if (isEmpty(myXsltRunConfiguration.myWorkingDirectory)) {
         parameters.setWorkingDirectory(new File(myXsltRunConfiguration.getXsltFile()).getParentFile().getAbsolutePath());
-      } else {
+      }
+      else {
         parameters.setWorkingDirectory(expandPath(myXsltRunConfiguration.myWorkingDirectory, myXsltRunConfiguration.getEffectiveModule(),
                                                   myXsltRunConfiguration.getProject()));
       }
 
-        myExtensionData = new UserDataHolderBase();
-        final List<XsltRunnerExtension> extensions = XsltRunnerExtension.getExtensions(myXsltRunConfiguration, myIsDebugger);
-        for (XsltRunnerExtension extension : extensions) {
-            extension.patchParameters(parameters, myXsltRunConfiguration, myExtensionData);
-        }
+      myExtensionData = new UserDataHolderBase();
+      final List<XsltRunnerExtension> extensions = XsltRunnerExtension.getExtensions(myXsltRunConfiguration, myIsDebugger);
+      for (XsltRunnerExtension extension : extensions) {
+        extension.patchParameters(parameters, myXsltRunConfiguration, myExtensionData);
+      }
 
-        parameters.setUseDynamicClasspath(JdkUtil.useDynamicClasspath(myXsltRunConfiguration.getProject()));
+      parameters.setUseDynamicClasspath(JdkUtil.useDynamicClasspath(myXsltRunConfiguration.getProject()));
 
-        return parameters;
+      return parameters;
     }
 
   protected static String expandPath(String path, Module module, Project project) {
diff --git a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java
index f48a5ea..038d5be 100644
--- a/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java
+++ b/plugins/xslt-debugger/src/org/intellij/plugins/xsltDebugger/XsltDebuggerExtension.java
@@ -25,6 +25,7 @@
 import com.intellij.icons.AllIcons;
 import com.intellij.ide.plugins.IdeaPluginDescriptor;
 import com.intellij.ide.plugins.PluginManager;
+import com.intellij.ide.plugins.PluginManagerCore;
 import com.intellij.openapi.application.PathManager;
 import com.intellij.openapi.application.ex.ApplicationManagerEx;
 import com.intellij.openapi.diagnostic.Logger;
@@ -125,7 +126,7 @@
 
     final char c = File.separatorChar;
 
-    final PluginId pluginId = PluginManager.getPluginByClassName(getClass().getName());
+    final PluginId pluginId = PluginManagerCore.getPluginByClassName(getClass().getName());
     assert pluginId != null || System.getProperty("xslt-debugger.plugin.path") != null;
 
     final File pluginPath;
diff --git a/python/IntelliLang-python/src/META-INF/intellilang-python-support.xml b/python/IntelliLang-python/src/META-INF/intellilang-python-support.xml
index 2ffa9f7..ce37b6b 100644
--- a/python/IntelliLang-python/src/META-INF/intellilang-python-support.xml
+++ b/python/IntelliLang-python/src/META-INF/intellilang-python-support.xml
@@ -7,5 +7,8 @@
   </extensions>
   <extensions defaultExtensionNs="com.intellij">
     <patterns.patternClass className="com.jetbrains.python.patterns.PythonPatterns" alias="py"/>
+    <multiHostInjector implementation="com.jetbrains.python.intelliLang.PyCommentInjector"/>
+    <multiHostInjector implementation="com.jetbrains.python.intelliLang.PyConfigurationInjector"/>
+    <multiHostInjector implementation="com.jetbrains.python.intelliLang.PyTemporaryInjector"/>
   </extensions>
 </idea-plugin>
\ No newline at end of file
diff --git a/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyCommentInjector.java b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyCommentInjector.java
new file mode 100644
index 0000000..45eb96b
--- /dev/null
+++ b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyCommentInjector.java
@@ -0,0 +1,25 @@
+package com.jetbrains.python.intelliLang;
+
+import com.intellij.lang.Language;
+import com.intellij.psi.PsiElement;
+import com.jetbrains.python.codeInsight.PyInjectorBase;
+import org.intellij.plugins.intelliLang.inject.InjectedLanguage;
+import org.intellij.plugins.intelliLang.inject.InjectorUtils;
+import org.intellij.plugins.intelliLang.inject.config.BaseInjection;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author vlan
+ */
+public class PyCommentInjector extends PyInjectorBase {
+  @Nullable
+  @Override
+  public Language getInjectedLanguage(@NotNull PsiElement context) {
+    final BaseInjection injection = InjectorUtils.findCommentInjection(context, "comment", null);
+    if (injection != null) {
+      return InjectedLanguage.findLanguageById(injection.getInjectedLanguageId());
+    }
+    return null;
+  }
+}
diff --git a/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyConfigurationInjector.java b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyConfigurationInjector.java
new file mode 100644
index 0000000..f672f5d
--- /dev/null
+++ b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyConfigurationInjector.java
@@ -0,0 +1,33 @@
+package com.jetbrains.python.intelliLang;
+
+import com.intellij.lang.Language;
+import com.intellij.psi.PsiElement;
+import com.jetbrains.python.codeInsight.PyInjectorBase;
+import org.intellij.plugins.intelliLang.Configuration;
+import org.intellij.plugins.intelliLang.inject.InjectedLanguage;
+import org.intellij.plugins.intelliLang.inject.InjectorUtils;
+import org.intellij.plugins.intelliLang.inject.LanguageInjectionSupport;
+import org.intellij.plugins.intelliLang.inject.config.BaseInjection;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author vlan
+ */
+public class PyConfigurationInjector extends PyInjectorBase {
+  @Nullable
+  @Override
+  public Language getInjectedLanguage(@NotNull PsiElement context) {
+    for (LanguageInjectionSupport support : InjectorUtils.getActiveInjectionSupports()) {
+      if (support instanceof PyLanguageInjectionSupport) {
+        final Configuration configuration = Configuration.getInstance();
+        for (BaseInjection injection : configuration.getInjections(support.getId())) {
+          if (injection.acceptsPsiElement(context)) {
+            return InjectedLanguage.findLanguageById(injection.getInjectedLanguageId());
+          }
+        }
+      }
+    }
+    return null;
+  }
+}
diff --git a/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyLanguageInjectionSupport.java b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyLanguageInjectionSupport.java
index 5a91db5..dee16d2 100644
--- a/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyLanguageInjectionSupport.java
+++ b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyLanguageInjectionSupport.java
@@ -15,22 +15,17 @@
  */
 package com.jetbrains.python.intelliLang;
 
-import com.intellij.lang.Language;
-import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.util.Ref;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiLanguageInjectionHost;
 import com.jetbrains.python.patterns.PythonPatterns;
 import com.jetbrains.python.psi.PyElement;
-import com.jetbrains.python.psi.PyStringLiteralExpression;
 import org.intellij.plugins.intelliLang.inject.AbstractLanguageInjectionSupport;
 import org.intellij.plugins.intelliLang.inject.config.BaseInjection;
-import org.jdom.Element;
 import org.jetbrains.annotations.NonNls;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.List;
-
 /**
  * @author yole
  */
@@ -54,36 +49,15 @@
     return host instanceof PyElement;
   }
 
-  @Override
-  public boolean useDefaultInjector(PsiLanguageInjectionHost host) {
-    return true;
-  }
-
-  @Override
-  public BaseInjection createInjection(Element element) {
-    // This is how DefaultLanguageInjector gets its injection ranges
-    return new BaseInjection(getId()) {
-      @NotNull
-      @Override
-      public List<TextRange> getInjectedArea(PsiElement element) {
-        if (element instanceof PyStringLiteralExpression) {
-          return ((PyStringLiteralExpression)element).getStringValueTextRanges();
-        }
-        return super.getInjectedArea(element);
-      }
-    };
-  }
-
-  @Override
-  public boolean addInjectionInPlace(Language language, PsiLanguageInjectionHost psiElement) {
-    // XXX: Disable temporary injections via intention actions for Python elements, since TemporaryPlacesInjector cannot handle elements
-    // with multiple injection text ranges (PY-10691)
-    return true;
-  }
-
   @Nullable
   @Override
   public String getHelpId() {
     return "reference.settings.language.injection.generic.python";
   }
+
+  @Nullable
+  @Override
+  public BaseInjection findCommentInjection(@NotNull PsiElement host, @Nullable Ref<PsiElement> commentRef) {
+    return null;
+  }
 }
diff --git a/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyTemporaryInjector.java b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyTemporaryInjector.java
new file mode 100644
index 0000000..0bbcdef
--- /dev/null
+++ b/python/IntelliLang-python/src/com/jetbrains/python/intelliLang/PyTemporaryInjector.java
@@ -0,0 +1,40 @@
+package com.jetbrains.python.intelliLang;
+
+import com.intellij.lang.Language;
+import com.intellij.lang.injection.MultiHostRegistrar;
+import com.intellij.psi.PsiElement;
+import com.intellij.psi.PsiFile;
+import com.intellij.psi.PsiLanguageInjectionHost;
+import com.jetbrains.python.codeInsight.PyInjectorBase;
+import org.intellij.plugins.intelliLang.inject.InjectedLanguage;
+import org.intellij.plugins.intelliLang.inject.InjectorUtils;
+import org.intellij.plugins.intelliLang.inject.TemporaryPlacesRegistry;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+/**
+ * @author vlan
+ */
+public class PyTemporaryInjector extends PyInjectorBase {
+  @Override
+  public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
+    if (registerInjection(registrar, context)) {
+      final TemporaryPlacesRegistry registry = TemporaryPlacesRegistry.getInstance(context.getProject());
+      InjectorUtils.registerSupport(registry.getLanguageInjectionSupport(), false, registrar);
+    }
+  }
+
+  @Nullable
+  @Override
+  public Language getInjectedLanguage(@NotNull PsiElement context) {
+    final TemporaryPlacesRegistry registry = TemporaryPlacesRegistry.getInstance(context.getProject());
+    if (context instanceof PsiLanguageInjectionHost) {
+      final PsiFile file = context.getContainingFile();
+      final InjectedLanguage injectedLanguage = registry.getLanguageFor((PsiLanguageInjectionHost)context, file);
+      if (injectedLanguage != null) {
+        return injectedLanguage.getLanguage();
+      }
+    }
+    return null;
+  }
+}
diff --git a/python/IntelliLang-python/src/pyInjections.xml b/python/IntelliLang-python/src/pyInjections.xml
index e9ae34e..f561c1d 100644
--- a/python/IntelliLang-python/src/pyInjections.xml
+++ b/python/IntelliLang-python/src/pyInjections.xml
@@ -9,6 +9,6 @@
   </injection>
   <injection language="SQL" injector-id="python">
     <display-name>"SQL select/delete/insert/update/create"</display-name>
-    <place><![CDATA[pyLiteralExpression().withText(string().matchesBrics(" *(((SELECT|DELETE) .*FROM)|((INSERT|REPLACE) .*INTO)|(UPDATE .* SET)|((CREATE|DROP|ALTER) +(TABLE|INDEX))) .*"))]]></place>
+    <place><![CDATA[pyLiteralExpression().withText(string().matchesBrics("[UuRrBb\\\"\\' \t]*(((SELECT|DELETE) .*FROM)|((INSERT|REPLACE) .*INTO)|(UPDATE .* SET)|((CREATE|DROP|ALTER) +(TABLE|INDEX))) .*"))]]></place>
   </injection>
 </component>
diff --git a/python/helpers/generator3.py b/python/helpers/generator3.py
index 5fced92..fe24620 100644
--- a/python/helpers/generator3.py
+++ b/python/helpers/generator3.py
@@ -38,12 +38,12 @@
     return fname
 
 
-def redo_module(mod_name, outfile, module_file_name, doing_builtins):
+def redo_module(module_name, outfile, module_file_name, doing_builtins):
     # gobject does 'del _gobject' in its __init__.py, so the chained attribute lookup code
     # fails to find 'gobject._gobject'. thus we need to pull the module directly out of
     # sys.modules
-    mod = sys.modules.get(mod_name)
-    mod_path = mod_name.split('.')
+    mod = sys.modules.get(module_name)
+    mod_path = module_name.split('.')
     if not mod and sys.platform == 'cli':
         # "import System.Collections" in IronPython 2.7 doesn't actually put System.Collections in sys.modules
         # instead, sys.modules['System'] get set to a Microsoft.Scripting.Actions.NamespaceTracker and Collections can be
@@ -54,16 +54,16 @@
                 mod = getattr(mod, component)
             except AttributeError:
                 mod = None
-                report("Failed to find CLR module " + mod_name)
+                report("Failed to find CLR module " + module_name)
                 break
     if mod:
         action("restoring")
         r = ModuleRedeclarator(mod, outfile, module_file_name, doing_builtins=doing_builtins)
-        r.redo(mod_name, ".".join(mod_path[:-1]) in MODULES_INSPECT_DIR)
+        r.redo(module_name, ".".join(mod_path[:-1]) in MODULES_INSPECT_DIR)
         action("flushing")
         r.flush()
     else:
-        report("Failed to find imported module in sys.modules " + mod_name)
+        report("Failed to find imported module in sys.modules " + module_name)
 
 # find_binaries functionality
 def cut_binary_lib_suffix(path, f):
@@ -122,6 +122,18 @@
             os.path.exists(os.path.join(root, d, "__init__.pyo")))
 
 
+def walk_python_path(path):
+    for root, dirs, files in os.walk(path):
+        if root.endswith('__pycache__'):
+            continue
+        dirs_copy = list(dirs)
+        for d in dirs_copy:
+            if d.endswith('__pycache__') or not is_module(d, root):
+                dirs.remove(d)
+        # some files show up but are actually non-existent symlinks
+        yield root, [f for f in files if os.path.exists(os.path.join(root, f))]
+
+
 def list_binaries(paths):
     """
     Finds binaries in the given list of paths.
@@ -139,13 +151,7 @@
     paths = sorted_no_case(paths)
     for path in paths:
         if path == os.path.dirname(sys.argv[0]): continue
-        for root, dirs, files in os.walk(path):
-            if root.endswith('__pycache__'): continue
-            dirs_copy = list(dirs)
-            for d in dirs_copy:
-                if d.endswith("__pycache__") or not is_module(d, root):
-                    dirs.remove(d)
-
+        for root, files in walk_python_path(path):
             cutpoint = path.rfind(SEP)
             if cutpoint > 0:
                 preprefix = path[(cutpoint + len(SEP)):] + '.'
@@ -180,17 +186,10 @@
 
             path = os.path.normpath(path)
 
-            for root, dirs, files in os.walk(path):
-                if root.endswith('__pycache__'): continue
-                dirs_copy = list(dirs)
-                for d in dirs_copy:
-                    if d.endswith("__pycache__") or not is_module(d, root):
-                        dirs.remove(d)
+            for root, files in walk_python_path(path):
                 for name in files:
                     if name.endswith('.py'):
                         file_path = os.path.join(root, name)
-                        # some files show up but are actually non-existent symlinks
-                        if not os.path.exists(file_path): continue
                         say("%s\t%s\t%d", os.path.normpath(file_path), path, os.path.getsize(file_path))
         say('END')
         sys.stdout.flush()
diff --git a/python/helpers/pycharm/tcunittest.py b/python/helpers/pycharm/tcunittest.py
index 07da02d..b6950c9 100644
--- a/python/helpers/pycharm/tcunittest.py
+++ b/python/helpers/pycharm/tcunittest.py
@@ -47,7 +47,7 @@
     quot = val[0]
     count = 1
     quote_ind = val[count:].find(quot)
-    while val[count+quote_ind-1] == "\\" and quote_ind != -1:
+    while quote_ind != -1 and val[count+quote_ind-1] == "\\":
       count = count + quote_ind + 1
       quote_ind = val[count:].find(quot)
 
@@ -60,16 +60,15 @@
       val = val[val_index+2:].strip()
       quot = val[0]
       quote_ind = val[count:].find(quot)
-      while val[count+quote_ind-1] == "\\" and quote_ind != -1:
+      while quote_ind != -1 and val[count+quote_ind-1] == "\\":
         count = count + quote_ind + 1
         quote_ind = val[count:].find(quot)
       return val[0:quote_ind+count+1]
 
     else:
       quot = val[-1]
-      count = 0
-      quote_ind = val[:len(val)-count-1].rfind(quot)
-      while val[quote_ind-1] == "\\":
+      quote_ind = val[:len(val)-1].rfind(quot)
+      while quote_ind != -1 and val[quote_ind-1] == "\\":
         quote_ind = val[:quote_ind-1].rfind(quot)
       return val[quote_ind:]
 
diff --git a/python/helpers/pydev/pydev_console_utils.py b/python/helpers/pydev/pydev_console_utils.py
index ee62910..54a8585 100644
--- a/python/helpers/pydev/pydev_console_utils.py
+++ b/python/helpers/pydev/pydev_console_utils.py
@@ -4,6 +4,7 @@
 import traceback
 
 from pydevd_constants import USE_LIB_COPY
+from pydevd_constants import IS_JYTHON
 
 try:
     if USE_LIB_COPY:
@@ -132,6 +133,16 @@
             return '\n'
 
 
+class CodeFragment:
+    def __init__(self, text, is_single_line=True):
+        self.text = text
+        self.is_single_line = is_single_line
+        
+    def append(self, code_fragment):
+        self.text = self.text + "\n" + code_fragment.text
+        if not code_fragment.is_single_line:
+            self.is_single_line = False
+
 #=======================================================================================================================
 # BaseInterpreterInterface
 #=======================================================================================================================
@@ -140,22 +151,16 @@
         self.mainThread = mainThread
         self.interruptable = False
         self.exec_queue = _queue.Queue(0)
-        self.buffer = []
+        self.buffer = None
 
-    def needMore(self, buffer, line):
-        if not buffer:
-            buffer = []
-        buffer.append(line)
-        source = "\n".join(buffer)
+    def needMoreForCode(self, source):
         if hasattr(self.interpreter, 'is_complete'):
             return not self.interpreter.is_complete(source)
-
         try:
-            code = self.interpreter.compile(source, "<input>", "single")
+            code = self.interpreter.compile(source, '<input>', 'exec')
         except (OverflowError, SyntaxError, ValueError):
             # Case 1
             return False
-
         if code is None:
             # Case 2
             return True
@@ -163,10 +168,15 @@
         # Case 3
         return False
 
+    def needMore(self, code_fragment):
+        if self.buffer is None:
+            self.buffer = code_fragment
+        else:
+            self.buffer.append(code_fragment)
+        
+        return self.needMoreForCode(self.buffer.text)
 
-    def addExec(self, line):
-        #f_opened = open('c:/temp/a.txt', 'a')
-        #f_opened.write(line+'\n')
+    def addExec(self, code_fragment):
         original_in = sys.stdin
         try:
             help = None
@@ -199,14 +209,14 @@
                             self._input_error_printed = True
                             sys.stderr.write('\nError when trying to update pydoc.help.input\n')
                             sys.stderr.write('(help() may not work -- please report this as a bug in the pydev bugtracker).\n\n')
-                            import traceback;
+                            import traceback
 
                             traceback.print_exc()
 
                 try:
                     self.startExec()
-                    more = self.doAddExec(line)
-                    self.finishExec()
+                    more = self.doAddExec(code_fragment)
+                    self.finishExec(more)
                 finally:
                     if help is not None:
                         try:
@@ -226,12 +236,10 @@
 
             traceback.print_exc()
 
-        #it's always false at this point
-        need_input = False
-        return more, need_input
+        return more
 
 
-    def doAddExec(self, line):
+    def doAddExec(self, codeFragment):
         '''
         Subclasses should override.
         
@@ -309,15 +317,31 @@
             return ''
 
 
-    def execLine(self, line):
+    def doExecCode(self, code, is_single_line):
         try:
-            #buffer = self.interpreter.buffer[:]
-            self.exec_queue.put(line)
-            return self.needMore(self.buffer, line)
+            code_fragment = CodeFragment(code, is_single_line)
+            more = self.needMore(code_fragment)
+            if not more:
+                code_fragment = self.buffer
+                self.buffer = None
+                self.exec_queue.put(code_fragment)
+
+            return more
         except:
             traceback.print_exc()
             return False
 
+    def execLine(self, line):
+        return self.doExecCode(line, True)
+
+
+    def execMultipleLines(self, lines):
+        if IS_JYTHON:
+            for line in lines.split('\n'):
+                self.doExecCode(line, True)
+        else:
+            return self.doExecCode(lines, False)
+
 
     def interrupt(self):
         try:
@@ -343,13 +367,13 @@
         else:
             return None
 
-    def finishExec(self):
+    def finishExec(self, more):
         self.interruptable = False
 
         server = self.get_server()
 
         if server is not None:
-            return server.NotifyFinished()
+            return server.NotifyFinished(more)
         else:
             return True
 
diff --git a/python/helpers/pydev/pydev_ipython_console.py b/python/helpers/pydev/pydev_ipython_console.py
index d3d4ae8..6a8e056 100644
--- a/python/helpers/pydev/pydev_ipython_console.py
+++ b/python/helpers/pydev/pydev_ipython_console.py
@@ -39,14 +39,14 @@
     def get_greeting_msg(self):
         return self.interpreter.get_greeting_msg()
 
-    def doAddExec(self, line):
+    def doAddExec(self, codeFragment):
         self.notify_about_magic()
-        if (line.rstrip().endswith('??')):
+        if (codeFragment.text.rstrip().endswith('??')):
             print('IPython-->')
         try:
-            res = bool(self.interpreter.addExec(line))
+            res = bool(self.interpreter.addExec(codeFragment.text))
         finally:
-            if (line.rstrip().endswith('??')):
+            if (codeFragment.text.rstrip().endswith('??')):
                 print('<--IPython')
 
         return res
diff --git a/python/helpers/pydev/pydev_monkey.py b/python/helpers/pydev/pydev_monkey.py
index 07c7e2b..8dd94ab 100644
--- a/python/helpers/pydev/pydev_monkey.py
+++ b/python/helpers/pydev/pydev_monkey.py
@@ -37,8 +37,9 @@
                 host, port = pydevd.dispatch()
 
                 if port is not None:
-                    args[indC + 1] = "import sys; sys.path.append('%s'); import pydevd; pydevd.settrace(host='%s', port=%s, suspend=False); %s"%(helpers, host, port, args[indC + 1])
-                    return args
+                    new_args.extend(args)
+                    new_args[indC + 1] = "import sys; sys.path.append('%s'); import pydevd; pydevd.settrace(host='%s', port=%s, suspend=False); %s"%(helpers, host, port, args[indC + 1])
+                    return new_args
             else:
                 new_args.append(args[0])
         else:
@@ -99,8 +100,9 @@
     args = str_to_args(new_arg_str)
     if not is_python(args[0]):
         return arg_str
-    art = args_to_str(patch_args(args))
-    return art
+    arg_str = args_to_str(patch_args(args))
+    pydev_log.debug("New args: %s"% arg_str)
+    return arg_str
 
 def monkey_patch_module(module, funcname, create_func):
     if hasattr(module, funcname):
diff --git a/python/helpers/pydev/pydevconsole.py b/python/helpers/pydev/pydevconsole.py
index 026fb7f..e8b8d29 100644
--- a/python/helpers/pydev/pydevconsole.py
+++ b/python/helpers/pydev/pydevconsole.py
@@ -10,7 +10,7 @@
 import sys
 
 from pydevd_constants import USE_LIB_COPY
-from pydevd_utils import *
+from pydevd_constants import IS_JYTHON
 
 if USE_LIB_COPY:
     import _pydev_threading as threading
@@ -51,6 +51,7 @@
     setattr(__builtin__, 'False', 0)
 
 from pydev_console_utils import BaseInterpreterInterface
+from pydev_console_utils import CodeFragment
 
 IS_PYTHON_3K = False
 
@@ -72,56 +73,30 @@
 except ImportError:
     import _pydev_xmlrpclib as xmlrpclib
 
-try:
-    class ExecState:
-        FIRST_CALL = True
-        PYDEV_CONSOLE_RUN_IN_UI = False #Defines if we should run commands in the UI thread.
 
-    from org.python.pydev.core.uiutils import RunInUiThread #@UnresolvedImport
-    from java.lang import Runnable #@UnresolvedImport
+class Command:
+    def __init__(self, interpreter, code_fragment):
+        """
+        :type code_fragment: CodeFragment
+        :type interpreter: InteractiveConsole
+        """
+        self.interpreter = interpreter
+        self.code_fragment = code_fragment
+        self.more = None
 
-    class Command(Runnable):
-        def __init__(self, interpreter, line):
-            self.interpreter = interpreter
-            self.line = line
-
-        def run(self):
-            if ExecState.FIRST_CALL:
-                ExecState.FIRST_CALL = False
-                sys.stdout.write('\nYou are now in a console within Eclipse.\nUse it with care as it can halt the VM.\n')
-                sys.stdout.write(
-                    'Typing a line with "PYDEV_CONSOLE_TOGGLE_RUN_IN_UI"\nwill start executing all the commands in the UI thread.\n\n')
-
-            if self.line == 'PYDEV_CONSOLE_TOGGLE_RUN_IN_UI':
-                ExecState.PYDEV_CONSOLE_RUN_IN_UI = not ExecState.PYDEV_CONSOLE_RUN_IN_UI
-                if ExecState.PYDEV_CONSOLE_RUN_IN_UI:
-                    sys.stdout.write(
-                        'Running commands in UI mode. WARNING: using sys.stdin (i.e.: calling raw_input()) WILL HALT ECLIPSE.\n')
-                else:
-                    sys.stdout.write('No longer running commands in UI mode.\n')
-                self.more = False
-            else:
-                self.more = self.interpreter.push(self.line)
-
-
-    def Sync(runnable):
-        if ExecState.PYDEV_CONSOLE_RUN_IN_UI:
-            return RunInUiThread.sync(runnable)
+    @staticmethod
+    def symbol_for_fragment(code_fragment):
+        if code_fragment.is_single_line:
+            symbol = 'single'
         else:
-            return runnable.run()
+            symbol = 'exec' # Jython doesn't support this
+        return symbol
 
-except:
-    #If things are not there, define a way in which there's no 'real' sync, only the default execution.
-    class Command:
-        def __init__(self, interpreter, line):
-            self.interpreter = interpreter
-            self.line = line
+    def run(self):
+        text = self.code_fragment.text
+        symbol = self.symbol_for_fragment(self.code_fragment)
 
-        def run(self):
-            self.more = self.interpreter.push(self.line)
-
-    def Sync(runnable):
-        runnable.run()
+        self.more = self.interpreter.runsource(text, '<input>', symbol)
 
 try:
     try:
@@ -152,9 +127,9 @@
         self._input_error_printed = False
 
 
-    def doAddExec(self, line):
-        command = Command(self.interpreter, line)
-        Sync(command)
+    def doAddExec(self, codeFragment):
+        command = Command(self.interpreter, codeFragment)
+        command.run()
         return command.more
 
 
@@ -185,14 +160,13 @@
     while 1:
         try:
             try:
-                line = interpreter.exec_queue.get(block=True, timeout=0.05)
+                codeFragment = interpreter.exec_queue.get(block=True, timeout=0.05)
             except _queue.Empty:
                 continue
 
-            if not interpreter.addExec(line):     #TODO: think about locks here
-                interpreter.buffer = []
+            more = interpreter.addExec(codeFragment)
         except KeyboardInterrupt:
-            interpreter.buffer = []
+            interpreter.buffer = None
             continue
         except SystemExit:
             raise
@@ -274,6 +248,7 @@
         raise
 
     server.register_function(interpreter.execLine)
+    server.register_function(interpreter.execMultipleLines)
     server.register_function(interpreter.getCompletions)
     server.register_function(interpreter.getFrame)
     server.register_function(interpreter.getVariable)
@@ -339,17 +314,17 @@
 def get_frame():
     return interpreterInterface.getFrame()
 
-def exec_expression(expression, globals, locals):
+def exec_code(code, globals, locals):
     interpreterInterface = get_interpreter()
 
     interpreterInterface.interpreter.update(globals, locals)
 
-    res = interpreterInterface.needMore(None, expression)
+    res = interpreterInterface.needMore(code)
 
     if res:
         return True
 
-    interpreterInterface.addExec(expression)
+    interpreterInterface.addExec(code)
 
     return False
 
@@ -399,7 +374,7 @@
     updated_globals.update(frame.f_locals) #locals later because it has precedence over the actual globals
 
     if IPYTHON:
-        return exec_expression(expression, updated_globals, frame.f_locals)
+        return exec_code(CodeFragment(expression), updated_globals, frame.f_locals)
 
     interpreter = ConsoleWriter()
 
diff --git a/python/helpers/pydev/pydevd_constants.py b/python/helpers/pydev/pydevd_constants.py
index 34759f7..5e78e15 100644
--- a/python/helpers/pydev/pydevd_constants.py
+++ b/python/helpers/pydev/pydevd_constants.py
@@ -41,6 +41,10 @@
 
 import os
 
+import pydevd_vm_type
+
+IS_JYTHON = pydevd_vm_type.GetVmType() == pydevd_vm_type.PydevdVmType.JYTHON
+
 #=======================================================================================================================
 # Python 3?
 #=======================================================================================================================
diff --git a/python/helpers/pydev/test_debug.py b/python/helpers/pydev/test_debug.py
index 89051c8..bc55de1 100644
--- a/python/helpers/pydev/test_debug.py
+++ b/python/helpers/pydev/test_debug.py
@@ -1,16 +1,20 @@
 __author__ = 'Dmitry.Trofimov'
 
 import unittest
+import os
+
+test_data_path = os.path.abspath(os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', '..', '..', '..', 'python', 'testData', 'debug'))
 
 class PyDevTestCase(unittest.TestCase):
     def testZipFileExits(self):
         from pydevd_file_utils import exists
-        self.assertTrue(exists('../../../testData/debug/zipped_lib.zip/zipped_module.py'))
-        self.assertFalse(exists('../../../testData/debug/zipped_lib.zip/zipped_module2.py'))
-        self.assertFalse(exists('../../../testData/debug/zipped_lib2.zip/zipped_module.py'))
+
+        self.assertTrue(exists(test_data_path +'/zipped_lib.zip/zipped_module.py'))
+        self.assertFalse(exists(test_data_path + '/zipped_lib.zip/zipped_module2.py'))
+        self.assertFalse(exists(test_data_path + '/zipped_lib2.zip/zipped_module.py'))
 
 
     def testEggFileExits(self):
         from pydevd_file_utils import exists
-        self.assertTrue(exists('../../../testData/debug/pycharm-debug.egg/pydev/pydevd.py'))
-        self.assertFalse(exists('../../../testData/debug/pycharm-debug.egg/pydev/pydevd2.py'))
+        self.assertTrue(exists(test_data_path + '/pycharm-debug.egg/pydev/pydevd.py'))
+        self.assertFalse(exists(test_data_path + '/pycharm-debug.egg/pydev/pydevd2.py'))
diff --git a/python/openapi/src/com/jetbrains/python/psi/PyStringLiteralFileReferenceSet.java b/python/openapi/src/com/jetbrains/python/psi/PyStringLiteralFileReferenceSet.java
index e74cd80..6c470c7 100644
--- a/python/openapi/src/com/jetbrains/python/psi/PyStringLiteralFileReferenceSet.java
+++ b/python/openapi/src/com/jetbrains/python/psi/PyStringLiteralFileReferenceSet.java
@@ -20,17 +20,19 @@
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiReferenceProvider;
 import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReference;
-import com.intellij.psi.impl.source.resolve.reference.impl.providers.FileReferenceSet;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
 import java.util.ArrayList;
 import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 
 /**
  * @author traff
  */
 public class PyStringLiteralFileReferenceSet extends RootFileReferenceSet {
+  public static final Pattern DELIMITERS = Pattern.compile("\\\\|/");
   private final PyStringLiteralExpression myStringLiteralExpression;
 
 
@@ -57,61 +59,33 @@
   protected void reparse() {
     //noinspection ConstantConditions
     if (myStringLiteralExpression != null) {
-      MyTextRangeConsumer textRangeConsumer = new MyTextRangeConsumer(this);
-
-      myStringLiteralExpression.iterateCharacterRanges(textRangeConsumer);
-      textRangeConsumer.finish();
-
-      List<FileReference> referencesList = textRangeConsumer.myReferenceList;
-
-      myReferences = referencesList.toArray(new FileReference[referencesList.size()]);
+      final List<FileReference> references = getFileReferences(myStringLiteralExpression);
+      myReferences = references.toArray(new FileReference[references.size()]);
     }
   }
 
-  private static class MyTextRangeConsumer implements PyStringLiteralExpression.TextRangeConsumer {
-    private final StringBuilder myItem = new StringBuilder();
-    private int myStartOffset = -1;
-    private int myIndex = 0;
-    private int myEndOffset = -1;
-    private final FileReferenceSet myFileReferenceSet;
-
-
-    private final List<FileReference> myReferenceList = new ArrayList<FileReference>();
-
-    private MyTextRangeConsumer(FileReferenceSet set) {
-      myFileReferenceSet = set;
-    }
-
-    @Override
-    public boolean process(int startOffset, int endOffset, String value) {
-      if ("\\".equals(value) || "/".equals(value)) {
-        addReference(startOffset);
+  @NotNull
+  private List<FileReference> getFileReferences(@NotNull PyStringLiteralExpression expression) {
+    final String value = expression.getStringValue();
+    final Matcher matcher = DELIMITERS.matcher(value);
+    int start = 0;
+    int index = 0;
+    final List<FileReference> results = new ArrayList<FileReference>();
+    while (matcher.find()) {
+      final String s = value.substring(start, matcher.start());
+      if (!s.isEmpty()) {
+        final TextRange range = TextRange.create(expression.valueOffsetToTextOffset(start),
+                                                 expression.valueOffsetToTextOffset(matcher.start()));
+        results.add(createFileReference(range, index++, s));
       }
-      else {
-        if (myStartOffset == -1) {
-          myStartOffset = startOffset;
-        }
-        myEndOffset = endOffset;
-        myItem.append(value);
-      }
-      return true;
+      start = matcher.end();
     }
-
-    private void addReference(int startOffset) {
-      if (myStartOffset != -1) {
-        final FileReference ref = myFileReferenceSet.createFileReference(
-          new TextRange(myStartOffset, startOffset),
-          myIndex++,
-          myItem.toString());
-        myReferenceList.add(ref);
-        myStartOffset = -1;
-        myItem.setLength(0);
-      }
+    final String s = value.substring(start);
+    if (!s.isEmpty()) {
+      final TextRange range = TextRange.create(expression.valueOffsetToTextOffset(start),
+                                               expression.valueOffsetToTextOffset(value.length()));
+      results.add(createFileReference(range, index, s));
     }
-
-
-    public void finish() {
-      addReference(myEndOffset);
-    }
+    return results;
   }
 }
diff --git a/python/pluginResources/META-INF/plugin.xml b/python/pluginResources/META-INF/plugin.xml
index 0d0d760..f263de7 100644
--- a/python/pluginResources/META-INF/plugin.xml
+++ b/python/pluginResources/META-INF/plugin.xml
@@ -4,9 +4,9 @@
 
   <id>PythonCore</id>
   <name>Python Community Edition</name>
-  <idea-version since-build="130.0" until-build="133.*"/>
+  <idea-version since-build="133.286" until-build="133.*"/>
   <description>Smart editing for Python scripts</description>
-  <version>3.1 Beta</version>
+  <version>3.1 Beta 2</version>
   <depends>com.intellij.modules.java</depends>
 
 
diff --git a/python/psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java b/python/psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java
index 8c3182d..f7dd122 100644
--- a/python/psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java
+++ b/python/psi-api/src/com/jetbrains/python/psi/PyStringLiteralExpression.java
@@ -16,8 +16,10 @@
 package com.jetbrains.python.psi;
 
 import com.intellij.lang.ASTNode;
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiLanguageInjectionHost;
+import org.jetbrains.annotations.NotNull;
 
 import java.util.List;
 
@@ -28,20 +30,6 @@
 
   int valueOffsetToTextOffset(int valueOffset);
 
-  void iterateCharacterRanges(TextRangeConsumer consumer);
-
-  /**
-   * Iterator over decoded string characters.
-   */
-  interface TextRangeConsumer {
-    /**
-     * Process a decoded character.
-     *
-     * @param startOffset start offset in the un-decoded string
-     * @param endOffset end offset in the un-decoded string
-     * @param value decoded character value
-     * @return false in order to stop iteration
-     */
-    boolean process(int startOffset, int endOffset, String value);
-  }
+  @NotNull
+  List<Pair<TextRange, String>> getDecodedFragments();
 }
diff --git a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java b/python/psi-api/src/com/jetbrains/python/psi/impl/PyResolveResultRater.java
similarity index 61%
copy from plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
copy to python/psi-api/src/com/jetbrains/python/psi/impl/PyResolveResultRater.java
index fec7c97..961293f 100644
--- a/plugins/gradle/src/org/jetbrains/plugins/gradle/model/impl/GradleDependency.java
+++ b/python/psi-api/src/com/jetbrains/python/psi/impl/PyResolveResultRater.java
@@ -13,22 +13,14 @@
  * See the License for the specific language governing permissions and
  * limitations under the License.
  */
-package org.jetbrains.plugins.gradle.model.impl;
+package com.jetbrains.python.psi.impl;
 
-import org.gradle.tooling.model.Dependency;
+import com.intellij.openapi.extensions.ExtensionPointName;
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
 
-import java.io.Serializable;
+public interface PyResolveResultRater {
+  ExtensionPointName<PyResolveResultRater> EP_NAME = ExtensionPointName.create("Pythonid.resolveResultRater");
 
-/**
- * @author Vladislav.Soroka
- * @since 11/8/13
- */
-public interface GradleDependency extends Dependency, Serializable {
-  String getConfigurationName();
-
-  String getDependencyName();
-
-  String getDependencyGroup();
-
-  String getDependencyVersion();
+  int getRate(@NotNull final PsiElement target);
 }
diff --git a/python/pydevSrc/com/jetbrains/python/console/pydev/AbstractConsoleCommunication.java b/python/pydevSrc/com/jetbrains/python/console/pydev/AbstractConsoleCommunication.java
index 70594f9..e8fa271 100644
--- a/python/pydevSrc/com/jetbrains/python/console/pydev/AbstractConsoleCommunication.java
+++ b/python/pydevSrc/com/jetbrains/python/console/pydev/AbstractConsoleCommunication.java
@@ -57,9 +57,9 @@
   }
 
   @Override
-  public void notifyCommandExecuted() {
+  public void notifyCommandExecuted(boolean more) {
     for (ConsoleCommunicationListener listener: communicationListeners) {
-      listener.commandExecuted();
+      listener.commandExecuted(more);
     }
   }
 
diff --git a/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunication.java b/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunication.java
index a114c2c..3017171 100644
--- a/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunication.java
+++ b/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunication.java
@@ -18,13 +18,30 @@
 
   boolean isExecuting();
 
-  void execInterpreter(String s, Function<InterpreterResponse, Object> callback);
+  void execInterpreter(ConsoleCodeFragment code, Function<InterpreterResponse, Object> callback);
 
   void interrupt();
 
   void addCommunicationListener(ConsoleCommunicationListener listener);
 
-  void notifyCommandExecuted();
+  void notifyCommandExecuted(boolean more);
   void notifyInputRequested();
 
+  class ConsoleCodeFragment {
+    private final String myText;
+    private final boolean myIsSingleLine;
+
+    public ConsoleCodeFragment(String text, boolean isSingleLine) {
+      myText = text;
+      myIsSingleLine = isSingleLine;
+    }
+
+    public String getText() {
+      return myText;
+    }
+
+    public boolean isSingleLine() {
+      return myIsSingleLine;
+    }
+  }
 }
diff --git a/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunicationListener.java b/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunicationListener.java
index 562f729..a9263b7 100644
--- a/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunicationListener.java
+++ b/python/pydevSrc/com/jetbrains/python/console/pydev/ConsoleCommunicationListener.java
@@ -4,6 +4,6 @@
  * @author traff
  */
 public interface ConsoleCommunicationListener {
-  void commandExecuted();
+  void commandExecuted(boolean more);
   void inputRequested();
 }
diff --git a/python/pydevSrc/com/jetbrains/python/console/pydev/IScriptConsoleCommunication.java b/python/pydevSrc/com/jetbrains/python/console/pydev/IScriptConsoleCommunication.java
deleted file mode 100644
index 3c998c8..0000000
--- a/python/pydevSrc/com/jetbrains/python/console/pydev/IScriptConsoleCommunication.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/*******************************************************************************
- * Copyright (c) 2005, 2007 IBM Corporation and others.
- * All rights reserved. This program and the accompanying materials
- * are made available under the terms of the Eclipse Public License v1.0
- * which accompanies this distribution, and is available at
- * http://www.eclipse.org/legal/epl-v10.html
- *
- 
- *******************************************************************************/
-package com.jetbrains.python.console.pydev;
-
-import com.intellij.util.Function;
-
-/**
- * Interface for the console communication.
- *
- * This interface is meant to be the way to communicate with the shell.
- */
-public interface IScriptConsoleCommunication {
-
-    /**
-     * Executes a given command in the interpreter (push a line)
-     *
-     * @param command the command to be executed
-     * @return the response from the interpreter (contains the stdout, stderr, etc).
-     * @throws Exception
-     */
-    void execInterpreter(String command, Function<InterpreterResponse, Object> onResponseReceived);
-
-    /**
-     * Creates the completions to be applied in the interpreter.
-     *
-     * @param text the text with what should be completed (e.g.: xxx.bar.foo)
-     * @param offset the offset where the completion was requested in the console document
-     * @return a list of proposals that can be applied for the given text.
-     * @throws Exception
-     */
-    //public ICompletionProposal[] getCompletions(String text, int offset) throws Exception;
-
-    /**
-     * Gets the description to be shown on hover to the user
-     *
-     * @param text the text representing the completion to be applied
-     * @return the description to be shown to the user
-     * @throws Exception
-     */
-    String getDescription(String text) throws Exception;
-
-    /**
-     * Stops the communication with the server. Should ask the server to terminate at this point.
-     * @throws Exception
-     */
-    void close();
-}
\ No newline at end of file
diff --git a/python/resources/idea/PyCharmCoreApplicationInfo.xml b/python/resources/idea/PyCharmCoreApplicationInfo.xml
index ef906b0..0ac5772 100644
--- a/python/resources/idea/PyCharmCoreApplicationInfo.xml
+++ b/python/resources/idea/PyCharmCoreApplicationInfo.xml
@@ -1,6 +1,6 @@
 <component>
   <company name="JetBrains s.r.o." url="http://www.jetbrains.com/?fromIDE"/>
-  <version major="3" minor="0" eap="true"/>
+  <version major="3" minor="1" eap="true"/>
   <build number="__BUILD_NUMBER__" date="__BUILD_DATE__"/>
   <logo url="/pycharm_core_logo.png" textcolor="ffffff" progressColor="ffaa16" progressY="230" progressTailIcon="/community_progress_tail.png"/>
   <about url="/pycharm_core_about.png" logoX="300" logoY="265" logoW="75" logoH="30" foreground="ffffff" linkColor="fca11a"/>
diff --git a/python/rest/resources/META-INF/plugin.xml b/python/rest/resources/META-INF/plugin.xml
index 06cd1f4..76e5727 100644
--- a/python/rest/resources/META-INF/plugin.xml
+++ b/python/rest/resources/META-INF/plugin.xml
@@ -3,12 +3,16 @@
   <id>org.jetbrains.plugins.rest</id>
   <description>This plugin enables support for reStructuredText files (*.rst)</description>
   <vendor>JetBrains</vendor>
-  <version>132.SNAPSHOT</version>
-  <idea-version since-build="130.1" until-build="133.0"/>
+  <version>134.SNAPSHOT</version>
+  <idea-version since-build="130.1"/>
   <depends>com.intellij.modules.lang</depends>
 
   <xi:include href="/META-INF/rest.xml" xpointer="xpointer(/idea-plugin/*)"/>
-
+  <change-notes><![CDATA[
+    <ul>
+    <li>Added inspection for title & underline length math (PY-10998)</li>
+    </ul>
+]]></change-notes>
   <extensions defaultExtensionNs="com.intellij">
     <errorHandler implementation="com.intellij.diagnostic.ITNReporter"/>
   </extensions>
diff --git a/python/rest/src/com/jetbrains/rest/RestBundle.properties b/python/rest/src/com/jetbrains/rest/RestBundle.properties
index 24b98c7..192f443 100644
--- a/python/rest/src/com/jetbrains/rest/RestBundle.properties
+++ b/python/rest/src/com/jetbrains/rest/RestBundle.properties
@@ -9,6 +9,7 @@
 ### Annotators ###
 ANN.unknown.target=Unknown target name ''{0}''
 ANN.duplicate.target=Duplicate explicit target name ''{0}''
+ANN.title.length=Title length must match the underline
 ANN.unusable.anonymous.target=Anonymous hyperlink target has no reference
 ANN.inline.block=Blank line is required after a literal block
 
diff --git a/python/rest/src/com/jetbrains/rest/RestLanguage.java b/python/rest/src/com/jetbrains/rest/RestLanguage.java
index c451e37..df05659 100644
--- a/python/rest/src/com/jetbrains/rest/RestLanguage.java
+++ b/python/rest/src/com/jetbrains/rest/RestLanguage.java
@@ -17,10 +17,7 @@
 
 import com.intellij.lang.Language;
 import com.intellij.psi.templateLanguages.TemplateLanguage;
-import com.jetbrains.rest.validation.RestAnnotator;
-import com.jetbrains.rest.validation.RestHyperlinksAnnotator;
-import com.jetbrains.rest.validation.RestInlineBlockAnnotator;
-import com.jetbrains.rest.validation.RestReferenceTargetAnnotator;
+import com.jetbrains.rest.validation.*;
 
 import java.util.Set;
 import java.util.concurrent.CopyOnWriteArraySet;
@@ -48,6 +45,7 @@
     _annotators.add(RestHyperlinksAnnotator.class);
     _annotators.add(RestReferenceTargetAnnotator.class);
     _annotators.add(RestInlineBlockAnnotator.class);
+    _annotators.add(RestTitleAnnotator.class);
   }
 
   public Set<Class<? extends RestAnnotator>> getAnnotators() {
diff --git a/python/rest/src/com/jetbrains/rest/psi/RestTitle.java b/python/rest/src/com/jetbrains/rest/psi/RestTitle.java
index eb93cbe..05c2e66 100644
--- a/python/rest/src/com/jetbrains/rest/psi/RestTitle.java
+++ b/python/rest/src/com/jetbrains/rest/psi/RestTitle.java
@@ -16,6 +16,7 @@
 package com.jetbrains.rest.psi;
 
 import com.intellij.lang.ASTNode;
+import com.jetbrains.rest.validation.RestElementVisitor;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -37,15 +38,13 @@
 
   @Nullable
   public String getName() {
-    final String text = getNode().getText();
-    if (text.length() == 0) return null;
+    final String text = getNode().getText().trim();
+    if (text.length() < 2) return null;
     final char adorn = text.charAt(text.length()-2);
     final CharacterIterator it = new StringCharacterIterator(text);
     int finish = 0;
     for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it.previous()) {
-      if (finish == 0)
-        finish++;
-      else if (ch != adorn) {
+      if (ch != adorn) {
         finish = it.getIndex();
         break;
       }
@@ -63,4 +62,25 @@
       return null;
     return text.substring(start, finish).trim();
   }
+
+  @Nullable
+  public String getUnderline() {
+    final String text = getNode().getText().trim();
+    if (text.length() < 2) return null;
+    final char adorn = text.charAt(text.length()-2);
+    final CharacterIterator it = new StringCharacterIterator(text);
+    int start = 0;
+    for (char ch = it.last(); ch != CharacterIterator.DONE; ch = it.previous()) {
+      if (ch != adorn) {
+        start = it.getIndex() + 1;
+        break;
+      }
+    }
+    return text.substring(start, text.length());
+  }
+
+  @Override
+  protected void acceptRestVisitor(RestElementVisitor visitor) {
+    visitor.visitTitle(this);
+  }
 }
diff --git a/python/rest/src/com/jetbrains/rest/validation/RestTitleAnnotator.java b/python/rest/src/com/jetbrains/rest/validation/RestTitleAnnotator.java
new file mode 100644
index 0000000..c906e31
--- /dev/null
+++ b/python/rest/src/com/jetbrains/rest/validation/RestTitleAnnotator.java
@@ -0,0 +1,32 @@
+/*
+ * 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.jetbrains.rest.validation;
+
+import com.jetbrains.rest.RestBundle;
+import com.jetbrains.rest.psi.RestTitle;
+
+public class RestTitleAnnotator extends RestAnnotator {
+  @Override
+  public void visitTitle(final RestTitle node) {
+    final String name = node.getName();
+    if (name == null) return;
+    int nameLen = name.length();
+    final String underline = node.getUnderline();
+    if (underline != null && nameLen != underline.length()) {
+      getHolder().createWarningAnnotation(node, RestBundle.message("ANN.title.length"));
+    }
+  }
+}
diff --git a/python/src/META-INF/python-core.xml b/python/src/META-INF/python-core.xml
index 6c02c7a..cf37b69 100644
--- a/python/src/META-INF/python-core.xml
+++ b/python/src/META-INF/python-core.xml
@@ -369,6 +369,8 @@
 
     <completion.contributor language="Python"
                             implementationClass="com.jetbrains.python.codeInsight.completion.PyClassNameCompletionContributor"/>
+    <completion.contributor language="Python"
+                            implementationClass="com.jetbrains.python.codeInsight.completion.PyBracketProtectingCompletionContributor"/>
     <weigher key="completion" implementationClass="com.jetbrains.python.codeInsight.completion.PythonCompletionWeigher" order="first"/>
     <completion.confidence language="Python" implementationClass="com.jetbrains.python.codeInsight.completion.PyCompletionConfidence"/>
     <typedHandler implementation="com.jetbrains.python.console.completion.PythonConsoleAutopopupBlockingHandler" id="pydevBlockAutoPopup"
@@ -511,6 +513,7 @@
 
   <extensionPoints>
     <extensionPoint qualifiedName="Pythonid.importResolver" interface="com.jetbrains.python.psi.impl.PyImportResolver"/>
+    <extensionPoint qualifiedName="Pythonid.resolveResultRater" interface="com.jetbrains.python.psi.impl.PyResolveResultRater"/>
     <extensionPoint qualifiedName="Pythonid.typeProvider" interface="com.jetbrains.python.psi.impl.PyTypeProvider"/>
     <extensionPoint qualifiedName="Pythonid.pySuperMethodsSearch" interface="com.intellij.util.QueryExecutor"/>
     <extensionPoint qualifiedName="Pythonid.pyClassInheritorsSearch" interface="com.intellij.util.QueryExecutor"/>
@@ -544,7 +547,6 @@
     <pySuperMethodsSearch implementation="com.jetbrains.python.psi.search.PySuperMethodsSearchExecutor"/>
     <pyClassInheritorsSearch implementation="com.jetbrains.python.psi.search.PyClassInheritorsSearchExecutor"/>
     <pyOverridingMethodsSearch implementation="com.jetbrains.python.psi.search.PyOverridingMethodsSearchExecutor"/>
-    <runnableScriptFilter implementation="com.jetbrains.python.testing.pytest.PyTestRunnableScriptFilter"/>
     <runnableScriptFilter implementation="com.jetbrains.python.testing.PythonUnitTestRunnableScriptFilter"/>
     <dumbAnnotator implementation="com.jetbrains.python.validation.DocStringAnnotator"/>
     <dumbAnnotator implementation="com.jetbrains.python.validation.PyDefinitionsAnnotator"/>
diff --git a/python/src/com/jetbrains/python/PyBundle.properties b/python/src/com/jetbrains/python/PyBundle.properties
index 5ee3ef7..28289e0 100644
--- a/python/src/com/jetbrains/python/PyBundle.properties
+++ b/python/src/com/jetbrains/python/PyBundle.properties
@@ -637,6 +637,7 @@
 PARSE.expected.colon=':' expected
 PARSE.expected.rpar=')' expected
 PARSE.expected.lpar='(' expected
+PARSE.expected.rbrace='}' expected
 PARSE.expected.tick='`' (backtick) expected
 PARSE.expected.name=name expected
 PARSE.expected.colon.or.rbracket=':' or ']' expected
diff --git a/python/src/com/jetbrains/python/codeInsight/PyInjectionUtil.java b/python/src/com/jetbrains/python/codeInsight/PyInjectionUtil.java
index d68e6c6..9a7edad 100644
--- a/python/src/com/jetbrains/python/codeInsight/PyInjectionUtil.java
+++ b/python/src/com/jetbrains/python/codeInsight/PyInjectionUtil.java
@@ -23,6 +23,7 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.Arrays;
 import java.util.List;
 
 import static com.jetbrains.python.inspections.PyStringFormatParser.*;
@@ -31,15 +32,22 @@
  * @author vlan
  */
 public class PyInjectionUtil {
+  public static final List<Class<? extends PyExpression>> ELEMENTS_TO_INJECT_IN =
+    Arrays.asList(PyStringLiteralExpression.class, PyParenthesizedExpression.class, PyBinaryExpression.class, PyCallExpression.class);
+
   private PyInjectionUtil() {}
 
   /**
-   * Returns true if the element is the largest expression that represents a string literal, possibly with concatenation, parentheses,
-   * or formatting.
+   * Returns the largest expression in the specified context that represents a string literal suitable for language injection, possibly
+   * with concatenation, parentheses, or formatting.
    */
-  public static boolean isLargestStringLiteral(@NotNull PsiElement element) {
-    final PsiElement parent = element.getParent();
-    return isStringLiteralPart(element) && (parent == null || !isStringLiteralPart(parent));
+  @Nullable
+  public static PsiElement getLargestStringLiteral(@NotNull PsiElement context) {
+    PsiElement element = null;
+    for (PsiElement current = context; current != null && isStringLiteralPart(current, element); current = current.getParent()) {
+      element = current;
+    }
+    return element;
   }
 
   /**
@@ -47,27 +55,35 @@
    * string concatenations or formatting.
    */
   public static void registerStringLiteralInjection(@NotNull PsiElement element, @NotNull MultiHostRegistrar registrar) {
-    processStringLiteral(element, registrar, "", "", Formatting.NONE);
+    processStringLiteral(element, registrar, "", "", Formatting.PERCENT);
   }
 
-  private static boolean isStringLiteralPart(@NotNull PsiElement element) {
-    if (element instanceof PyStringLiteralExpression) {
+  private static boolean isStringLiteralPart(@NotNull PsiElement element, @Nullable PsiElement context) {
+    if (element == context) {
+      return true;
+    }
+    else if (element instanceof PyStringLiteralExpression) {
       return true;
     }
     else if (element instanceof PyParenthesizedExpression) {
       final PyExpression contained = ((PyParenthesizedExpression)element).getContainedExpression();
-      return contained != null && isStringLiteralPart(contained);
+      return contained != null && isStringLiteralPart(contained, context);
     }
     else if (element instanceof PyBinaryExpression) {
       final PyBinaryExpression expr = (PyBinaryExpression)element;
       final PyExpression left = expr.getLeftExpression();
       final PyExpression right = expr.getRightExpression();
-      return (expr.isOperator("+") && (isStringLiteralPart(left) || right != null && isStringLiteralPart(right))) ||
-              expr.isOperator("%") && isStringLiteralPart(left);
+      if (expr.isOperator("+")) {
+        return isStringLiteralPart(left, context) || right != null && isStringLiteralPart(right, context);
+      }
+      else if (expr.isOperator("%")) {
+        return right != context && isStringLiteralPart(left, context);
+      }
+      return false;
     }
     else if (element instanceof PyCallExpression) {
       final PyExpression qualifier = getFormatCallQualifier((PyCallExpression)element);
-      return qualifier != null && isStringLiteralPart(qualifier);
+      return qualifier != null && isStringLiteralPart(qualifier, context);
     }
     return false;
   }
@@ -100,9 +116,25 @@
             final FormatStringChunk chunk = chunks.get(i);
             if (chunk instanceof ConstantChunk) {
               final int nextIndex = i + 1;
-              final String chunkPrefix = i == 1 && chunks.get(0) instanceof SubstitutionChunk ? missingValue : "";
-              final String chunkSuffix = nextIndex < chunks.size() &&
-                                         chunks.get(nextIndex) instanceof SubstitutionChunk ? missingValue : "";
+              final String chunkPrefix;
+              if (i == 1 && chunks.get(0) instanceof SubstitutionChunk) {
+                chunkPrefix = missingValue;
+              }
+              else if (i == 0) {
+                chunkPrefix = prefix;
+              } else {
+                chunkPrefix = "";
+              }
+              final String chunkSuffix;
+              if (nextIndex < chunks.size() && chunks.get(nextIndex) instanceof SubstitutionChunk) {
+                chunkSuffix = missingValue;
+              }
+              else if (nextIndex == chunks.size()) {
+                chunkSuffix = suffix;
+              }
+              else {
+                chunkSuffix = "";
+              }
               final TextRange chunkRange = chunk.getTextRange().shiftRight(range.getStartOffset());
               registrar.addPlace(chunkPrefix, chunkSuffix, expr, chunkRange);
             }
@@ -123,9 +155,9 @@
       final PyBinaryExpression expr = (PyBinaryExpression)element;
       final PyExpression left = expr.getLeftExpression();
       final PyExpression right = expr.getRightExpression();
-      final boolean isLeftString = isStringLiteralPart(left);
+      final boolean isLeftString = isStringLiteralPart(left, null);
       if (expr.isOperator("+")) {
-        final boolean isRightString = right != null && isStringLiteralPart(right);
+        final boolean isRightString = right != null && isStringLiteralPart(right, null);
         if (isLeftString) {
           processStringLiteral(left, registrar, prefix, isRightString ? "" : missingValue, formatting);
         }
diff --git a/python/src/com/jetbrains/python/codeInsight/PyInjectorBase.java b/python/src/com/jetbrains/python/codeInsight/PyInjectorBase.java
new file mode 100644
index 0000000..98ae8c4
--- /dev/null
+++ b/python/src/com/jetbrains/python/codeInsight/PyInjectorBase.java
@@ -0,0 +1,43 @@
+package com.jetbrains.python.codeInsight;
+
+import com.intellij.lang.Language;
+import com.intellij.lang.injection.MultiHostInjector;
+import com.intellij.lang.injection.MultiHostRegistrar;
+import com.intellij.psi.PsiElement;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
+
+import java.util.List;
+
+/**
+ * @author vlan
+ */
+public abstract class PyInjectorBase implements MultiHostInjector {
+  @Override
+  public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
+    registerInjection(registrar, context);
+  }
+
+  @NotNull
+  @Override
+  public List<? extends Class<? extends PsiElement>> elementsToInjectIn() {
+    return PyInjectionUtil.ELEMENTS_TO_INJECT_IN;
+  }
+
+  @Nullable
+  public abstract Language getInjectedLanguage(@NotNull PsiElement context);
+
+  protected boolean registerInjection(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
+    final Language language = getInjectedLanguage(context);
+    if (language != null) {
+      final PsiElement element = PyInjectionUtil.getLargestStringLiteral(context);
+      if (element != null) {
+        registrar.startInjecting(language);
+        PyInjectionUtil.registerStringLiteralInjection(element, registrar);
+        registrar.doneInjecting();
+        return true;
+      }
+    }
+    return false;
+  }
+}
diff --git a/python/src/com/jetbrains/python/codeInsight/completion/PyBracketProtectingCompletionContributor.java b/python/src/com/jetbrains/python/codeInsight/completion/PyBracketProtectingCompletionContributor.java
new file mode 100644
index 0000000..766e5be
--- /dev/null
+++ b/python/src/com/jetbrains/python/codeInsight/completion/PyBracketProtectingCompletionContributor.java
@@ -0,0 +1,35 @@
+/*
+ * 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.jetbrains.python.codeInsight.completion;
+
+import com.intellij.codeInsight.completion.CompletionContributor;
+import com.intellij.codeInsight.completion.CompletionInitializationContext;
+import com.intellij.psi.PsiReference;
+import com.jetbrains.python.psi.impl.references.PyOperatorReference;
+import org.jetbrains.annotations.NotNull;
+
+/**
+ * @author yole
+ */
+public class PyBracketProtectingCompletionContributor extends CompletionContributor {
+  @Override
+  public void beforeCompletion(@NotNull CompletionInitializationContext context) {
+    PsiReference ref = context.getFile().findReferenceAt(context.getSelectionEndOffset());
+    if (ref instanceof PyOperatorReference) {
+      context.setReplacementOffset(context.getIdentifierEndOffset());
+    }
+  }
+}
diff --git a/python/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java b/python/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java
index 84d4b88..272adfa 100644
--- a/python/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java
+++ b/python/src/com/jetbrains/python/codeInsight/completion/PyDocstringCompletionContributor.java
@@ -16,6 +16,7 @@
 package com.jetbrains.python.codeInsight.completion;
 
 import com.intellij.codeInsight.completion.*;
+import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
 import com.intellij.codeInsight.lookup.LookupElementBuilder;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleUtilCore;
@@ -23,8 +24,6 @@
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.ProcessingContext;
-import com.jetbrains.python.PyTokenTypes;
-import com.jetbrains.python.documentation.PyDocumentationSettings;
 import com.jetbrains.python.psi.PyDocStringOwner;
 import com.jetbrains.python.psi.PyStringLiteralExpression;
 import com.jetbrains.python.refactoring.PyRefactoringUtil;
@@ -32,7 +31,9 @@
 
 import java.util.Collection;
 
+import static com.intellij.patterns.PlatformPatterns.psiComment;
 import static com.intellij.patterns.PlatformPatterns.psiElement;
+import static com.intellij.patterns.StandardPatterns.or;
 
 /**
  * User : ktisha
@@ -40,7 +41,7 @@
 public class PyDocstringCompletionContributor extends CompletionContributor {
   public PyDocstringCompletionContributor() {
     extend(CompletionType.BASIC,
-           psiElement().inside(PyStringLiteralExpression.class).withElementType(PyTokenTypes.DOCSTRING),
+           or(psiElement().inside(PyStringLiteralExpression.class), psiComment()),
            new IdentifierCompletionProvider());
   }
 
@@ -54,23 +55,22 @@
                                   ProcessingContext context,
                                   @NotNull CompletionResultSet result) {
       if (parameters.isAutoPopup()) return;
-      final PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(parameters.getOriginalPosition(), PyDocStringOwner.class);
-      if (docStringOwner != null) {
-        final PsiFile file = docStringOwner.getContainingFile();
-        final Module module = ModuleUtilCore.findModuleForPsiElement(docStringOwner);
-        if (module != null) {
-          final PyDocumentationSettings settings = PyDocumentationSettings.getInstance(module);
-          if (!settings.isPlain(file)) return;
-          result = result.withPrefixMatcher(getPrefix(parameters.getOffset(), file));
-          final Collection<String> identifiers = PyRefactoringUtil.collectUsedNames(docStringOwner);
-          for (String identifier : identifiers)
-            result.addElement(LookupElementBuilder.create(identifier));
+      final PsiElement element = parameters.getOriginalPosition();
+      if (element == null) return;
+      final PsiFile file = element.getContainingFile();
+      if (file.findReferenceAt(parameters.getOffset()) != null) return;
+      final PyDocStringOwner docStringOwner = PsiTreeUtil.getParentOfType(element, PyDocStringOwner.class);
+      final Module module = ModuleUtilCore.findModuleForPsiElement(element);
+      if (module != null) {
+        result = result.withPrefixMatcher(getPrefix(parameters.getOffset(), file));
+        final Collection<String> identifiers = PyRefactoringUtil.collectUsedNames(docStringOwner);
+        for (String identifier : identifiers)
+          result.addElement(LookupElementBuilder.create(identifier).withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE));
 
 
-          final Collection<String> fileIdentifiers = PyRefactoringUtil.collectUsedNames(parameters.getOriginalFile());
-          for (String identifier : fileIdentifiers)
-            result.addElement(LookupElementBuilder.create(identifier));
-        }
+        final Collection<String> fileIdentifiers = PyRefactoringUtil.collectUsedNames(parameters.getOriginalFile());
+        for (String identifier : fileIdentifiers)
+          result.addElement(LookupElementBuilder.create(identifier).withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE));
       }
     }
   }
diff --git a/python/src/com/jetbrains/python/codeInsight/regexp/PythonRegexpInjector.java b/python/src/com/jetbrains/python/codeInsight/regexp/PythonRegexpInjector.java
index 39c9aff..bb23c47 100644
--- a/python/src/com/jetbrains/python/codeInsight/regexp/PythonRegexpInjector.java
+++ b/python/src/com/jetbrains/python/codeInsight/regexp/PythonRegexpInjector.java
@@ -67,7 +67,7 @@
   @Override
   public void getLanguagesToInject(@NotNull MultiHostRegistrar registrar, @NotNull PsiElement context) {
     final PsiElement contextParent = context.getParent();
-    if (PyInjectionUtil.isLargestStringLiteral(context) && contextParent instanceof PyArgumentList) {
+    if (PyInjectionUtil.getLargestStringLiteral(context) == context && contextParent instanceof PyArgumentList) {
       final PyExpression[] args = ((PyArgumentList)contextParent).getArguments();
       int index = ArrayUtil.indexOf(args, context);
       PyCallExpression call = PsiTreeUtil.getParentOfType(context, PyCallExpression.class);
diff --git a/python/src/com/jetbrains/python/console/PyConsoleOptions.java b/python/src/com/jetbrains/python/console/PyConsoleOptions.java
index 6816b93..d02b670 100644
--- a/python/src/com/jetbrains/python/console/PyConsoleOptions.java
+++ b/python/src/com/jetbrains/python/console/PyConsoleOptions.java
@@ -19,8 +19,12 @@
 import com.intellij.openapi.components.*;
 import com.intellij.openapi.module.ModuleManager;
 import com.intellij.openapi.project.Project;
+import com.intellij.util.PathMappingSettings;
 import com.intellij.util.containers.ComparatorUtil;
+import com.intellij.util.xmlb.annotations.*;
 import com.jetbrains.python.run.AbstractPyCommonOptionsForm;
+import org.jetbrains.annotations.NotNull;
+import org.jetbrains.annotations.Nullable;
 
 import java.util.Map;
 
@@ -80,6 +84,7 @@
     public boolean myShowSeparatorLine = true;
   }
 
+  @Tag("console-settings")
   public static class PyConsoleSettings {
     public String myCustomStartScript = "";
     public String mySdkHome = null;
@@ -90,14 +95,8 @@
     public String myWorkingDirectory = "";
     public boolean myAddContentRoots = true;
     public boolean myAddSourceRoots;
-
-    public String getCustomStartScript() {
-      return myCustomStartScript;
-    }
-
-    public String getSdkHome() {
-      return mySdkHome;
-    }
+    @NotNull
+    private PathMappingSettings myMappings = new PathMappingSettings();
 
     public void apply(AbstractPyCommonOptionsForm form) {
       mySdkHome = form.getSdkHome();
@@ -109,6 +108,7 @@
 
       myAddContentRoots = form.addContentRoots();
       myAddSourceRoots = form.addSourceRoots();
+      myMappings = form.getMappingSettings() == null ? new PathMappingSettings() : form.getMappingSettings();
     }
 
     public boolean isModified(AbstractPyCommonOptionsForm form) {
@@ -119,7 +119,8 @@
              myAddContentRoots != form.addContentRoots() ||
              myAddSourceRoots != form.addSourceRoots()
              || !ComparatorUtil.equalsNullable(myModuleName, form.getModule() == null ? null : form.getModule().getName())
-             || !myWorkingDirectory.equals(form.getWorkingDirectory());
+             || !myWorkingDirectory.equals(form.getWorkingDirectory())
+             || !myMappings.equals(form.getMappingSettings());
     }
 
     public void reset(Project project, AbstractPyCommonOptionsForm form) {
@@ -143,33 +144,103 @@
         myModuleName = form.getModule().getName();
       }
 
-      form.setWorkingDirectory(form.getWorkingDirectory());
+      form.setWorkingDirectory(myWorkingDirectory);
+
+      form.setMappingSettings(myMappings);
     }
 
+    @Attribute("custom-start-script")
+    public String getCustomStartScript() {
+      return myCustomStartScript;
+    }
+
+    @Attribute("sdk-home")
+    public String getSdkHome() {
+      return mySdkHome;
+    }
+
+    @Attribute("module-name")
     public String getModuleName() {
       return myModuleName;
     }
 
+    @Attribute("working-directory")
     public String getWorkingDirectory() {
       return myWorkingDirectory;
     }
 
+    @Attribute("is-module-sdk")
     public boolean isUseModuleSdk() {
       return myUseModuleSdk;
     }
 
+    @Tag("envs")
+    @Property(surroundWithTag = false)
+    @MapAnnotation(surroundWithTag = false, surroundKeyWithTag = false, keyAttributeName = "key",
+                   entryTagName = "env", valueAttributeName = "value", surroundValueWithTag = false)
     public Map<String, String> getEnvs() {
       return myEnvs;
     }
 
+    @Attribute("add-content-roots")
     public boolean addContentRoots() {
       return myAddContentRoots;
     }
 
+    @Attribute("add-source-roots")
     public boolean addSourceRoots() {
       return myAddSourceRoots;
     }
 
+    @Attribute("interpreter-options")
+    public String getInterpreterOptions() {
+      return myInterpreterOptions;
+    }
+
+    @AbstractCollection(surroundWithTag = false)
+    public PathMappingSettings getMappings() {
+      return myMappings;
+    }
+
+    public void setCustomStartScript(String customStartScript) {
+      myCustomStartScript = customStartScript;
+    }
+
+    public void setSdkHome(String sdkHome) {
+      mySdkHome = sdkHome;
+    }
+
+    public void setInterpreterOptions(String interpreterOptions) {
+      myInterpreterOptions = interpreterOptions;
+    }
+
+    public void setUseModuleSdk(boolean useModuleSdk) {
+      myUseModuleSdk = useModuleSdk;
+    }
+
+    public void setModuleName(String moduleName) {
+      myModuleName = moduleName;
+    }
+
+    public void setEnvs(Map<String, String> envs) {
+      myEnvs = envs;
+    }
+
+    public void setWorkingDirectory(String workingDirectory) {
+      myWorkingDirectory = workingDirectory;
+    }
+
+    public void setAddContentRoots(boolean addContentRoots) {
+      myAddContentRoots = addContentRoots;
+    }
+
+    public void setAddSourceRoots(boolean addSourceRoots) {
+      myAddSourceRoots = addSourceRoots;
+    }
+
+    public void setMappings(@Nullable PathMappingSettings mappings) {
+      myMappings = mappings != null ? mappings : new PathMappingSettings();
+    }
   }
 }
 
diff --git a/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java b/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java
index b0ef1d3..6af6c13 100644
--- a/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java
+++ b/python/src/com/jetbrains/python/console/PydevConsoleCommunication.java
@@ -53,10 +53,11 @@
  *
  * @author Fabio
  */
-public class PydevConsoleCommunication extends AbstractConsoleCommunication implements IScriptConsoleCommunication, XmlRpcHandler,
+public class PydevConsoleCommunication extends AbstractConsoleCommunication implements XmlRpcHandler,
                                                                                        PyFrameAccessor {
 
   private static final String EXEC_LINE = "execLine";
+  private static final String EXEC_MULTILINE = "execMultipleLines";
   private static final String GET_COMPLETIONS = "getCompletions";
   private static final String GET_DESCRIPTION = "getDescription";
   private static final String GET_FRAME = "getFrame";
@@ -64,6 +65,7 @@
   private static final String CHANGE_VARIABLE = "changeVariable";
   private static final String HANDSHAKE = "handshake";
   private static final String CLOSE = "close";
+
   /**
    * XML-RPC client for sending messages to the server.
    */
@@ -167,7 +169,7 @@
    */
   public Object execute(String method, Vector params) throws Exception {
     if ("NotifyFinished".equals(method)) {
-      return execNotifyFinished();
+      return execNotifyFinished((Boolean)params.get(0));
     }
     else if ("RequestInput".equals(method)) {
       return execRequestInput();
@@ -223,9 +225,9 @@
     return Boolean.FALSE;
   }
 
-  private Object execNotifyFinished() {
+  private Object execNotifyFinished(boolean more) {
     setExecuting(false);
-    notifyCommandExecuted();
+    notifyCommandExecuted(more);
     return true;
   }
 
@@ -261,12 +263,13 @@
   /**
    * Executes the needed command
    *
+   * @param command
    * @return a Pair with (null, more) or (error, false)
    * @throws XmlRpcException
    */
-  protected Pair<String, Boolean> exec(final String command) throws XmlRpcException {
+  protected Pair<String, Boolean> exec(final ConsoleCodeFragment command) throws XmlRpcException {
     setExecuting(true);
-    Object execute = myClient.execute(EXEC_LINE, new Object[]{command});
+    Object execute = myClient.execute(command.isSingleLine() ? EXEC_LINE : EXEC_MULTILINE, new Object[]{command.getText()});
 
     Object object;
     if (execute instanceof Vector) {
@@ -278,6 +281,15 @@
     else {
       object = execute;
     }
+    Pair<String, Boolean> result = parseResult(object);
+    if (result.second) {
+      setExecuting(false);
+    }
+
+    return result;
+  }
+
+  private Pair<String, Boolean> parseResult(Object object) {
     if (object instanceof Boolean) {
       return new Pair<String, Boolean>(null, (Boolean)object);
     }
@@ -314,10 +326,10 @@
    *
    * @param command the command to be executed in the client
    */
-  public void execInterpreter(final String command, final Function<InterpreterResponse, Object> onResponseReceived) {
+  public void execInterpreter(final ConsoleCodeFragment command, final Function<InterpreterResponse, Object> onResponseReceived) {
     nextResponse = null;
     if (waitingForInput) {
-      inputReceived = command;
+      inputReceived = command.getText();
       waitingForInput = false;
       //the thread that we started in the last exec is still alive if we were waiting for an input.
     }
diff --git a/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java b/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java
index 20e8655..3dd6187 100644
--- a/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java
+++ b/python/src/com/jetbrains/python/console/PydevConsoleExecuteActionHandler.java
@@ -32,6 +32,7 @@
 import com.intellij.psi.codeStyle.CodeStyleSettingsManager;
 import com.intellij.psi.impl.source.codeStyle.IndentHelperImpl;
 import com.intellij.util.Function;
+import com.intellij.util.ui.UIUtil;
 import com.jetbrains.python.PythonFileType;
 import com.jetbrains.python.PythonLanguage;
 import com.jetbrains.python.console.pydev.ConsoleCommunication;
@@ -40,13 +41,10 @@
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.Scanner;
-
 /**
  * @author traff
  */
 public class PydevConsoleExecuteActionHandler extends ConsoleExecuteActionHandler implements ConsoleCommunicationListener {
-
   private final LanguageConsoleView myConsoleView;
 
   private String myInMultilineStringState = null;
@@ -67,19 +65,20 @@
 
   @Override
   public void processLine(final String text) {
-    processLine(text, true);
+    processLine(text, false);
   }
 
-  public void processLine(final String text, boolean execAnyway) {
+  public void processLine(@NotNull final String text, boolean execAnyway) {
     int indentBefore = myCurrentIndentSize;
     if (text.isEmpty()) {
       processOneLine(text);
     }
     else {
-      Scanner s = new Scanner(text);
-      while (s.hasNextLine()) {
-        String line = s.nextLine();
-        processOneLine(line);
+      if (StringUtil.countNewLines(text.trim()) > 0) {
+        executeMultiLine(text);
+      }
+      else {
+        processOneLine(text);
       }
     }
     if (execAnyway && myCurrentIndentSize > 0 && indentBefore == 0) { //if code was indented and we need to exec anyway
@@ -87,6 +86,19 @@
     }
   }
 
+  private void executeMultiLine(@NotNull String text) {
+    if (myInputBuffer == null) {
+      myInputBuffer = new StringBuilder();
+    }
+
+    myInputBuffer.append(text);
+
+    final LanguageConsoleImpl console = myConsoleView.getConsole();
+    final Editor currentEditor = console.getConsoleEditor();
+
+    sendLineToConsole(new ConsoleCommunication.ConsoleCodeFragment(myInputBuffer.toString(), false), console, currentEditor);
+  }
+
   private void processOneLine(String line) {
     int indentSize = IndentHelperImpl.getIndent(getProject(), PythonFileType.INSTANCE, line, false);
     line = StringUtil.trimTrailing(line);
@@ -169,21 +181,27 @@
         indentEditor(currentEditor, indent);
         more(console, currentEditor);
 
+        myConsoleCommunication.notifyCommandExecuted(true);
         return;
       }
     }
 
 
+    sendLineToConsole(new ConsoleCommunication.ConsoleCodeFragment(myInputBuffer.toString(), true), console, currentEditor);
+  }
+
+  private void sendLineToConsole(@NotNull final ConsoleCommunication.ConsoleCodeFragment code,
+                                 @NotNull final LanguageConsoleImpl console,
+                                 @NotNull final Editor currentEditor) {
     if (myConsoleCommunication != null) {
       final boolean waitedForInputBefore = myConsoleCommunication.isWaitingForInput();
-      final String command = myInputBuffer.toString();
       if (myConsoleCommunication.isWaitingForInput()) {
         myInputBuffer.setLength(0);
       }
       else {
         executingPrompt(console);
       }
-      myConsoleCommunication.execInterpreter(command, new Function<InterpreterResponse, Object>() {
+      myConsoleCommunication.execInterpreter(code, new Function<InterpreterResponse, Object>() {
         public Object fun(final InterpreterResponse interpreterResponse) {
           // clear
           myInputBuffer = null;
@@ -192,9 +210,15 @@
             more(console, currentEditor);
             if (myCurrentIndentSize == 0) {
               // compute current indentation
-              setCurrentIndentSize(IndentHelperImpl.getIndent(getProject(), PythonFileType.INSTANCE, line, false) + getPythonIndent());
+              setCurrentIndentSize(
+                IndentHelperImpl.getIndent(getProject(), PythonFileType.INSTANCE, lastLine(code.getText()), false) + getPythonIndent());
               // In this case we can insert indent automatically
-              indentEditor(currentEditor, myCurrentIndentSize);
+              UIUtil.invokeLaterIfNeeded(new Runnable() {
+                @Override
+                public void run() {
+                  indentEditor(currentEditor, myCurrentIndentSize);
+                }
+              });
             }
           }
           else {
@@ -215,6 +239,11 @@
     }
   }
 
+  private static String lastLine(@NotNull String text) {
+    String[] lines = StringUtil.splitByLinesDontTrim(text);
+    return lines[lines.length - 1];
+  }
+
   private void ordinaryPrompt(LanguageConsoleImpl console, Editor currentEditor) {
     if (!myConsoleCommunication.isExecuting()) {
       if (!PyConsoleUtil.ORDINARY_PROMPT.equals(console.getPrompt())) {
@@ -243,10 +272,13 @@
   }
 
   @Override
-  public void commandExecuted() {
-    final LanguageConsoleImpl console = myConsoleView.getConsole();
-    final Editor currentEditor = console.getConsoleEditor();
-    ordinaryPrompt(console, currentEditor);
+  public void commandExecuted(boolean more) {
+    if (!more) {
+      final LanguageConsoleImpl console = myConsoleView.getConsole();
+      final Editor currentEditor = console.getConsoleEditor();
+
+      ordinaryPrompt(console, currentEditor);
+    }
   }
 
   @Override
@@ -335,7 +367,7 @@
   }
 
   @Override
-  public void runExecuteAction(LanguageConsoleImpl languageConsole) {
+  public void runExecuteAction(@NotNull LanguageConsoleImpl languageConsole) {
     if (isEnabled()) {
       if (!canExecuteNow()) {
         HintManager.getInstance().showErrorHint(languageConsole.getConsoleEditor(), getPrevCommandRunningMessage());
diff --git a/python/src/com/jetbrains/python/console/PythonConsoleView.java b/python/src/com/jetbrains/python/console/PythonConsoleView.java
index ddf62ed..27d964a 100644
--- a/python/src/com/jetbrains/python/console/PythonConsoleView.java
+++ b/python/src/com/jetbrains/python/console/PythonConsoleView.java
@@ -152,7 +152,9 @@
 
 
   private void doExecute(String code) {
-    executeInConsole(PyConsoleIndentUtil.normalize(code, myExecuteActionHandler.getCurrentIndentSize()));
+    String codeFragment = PyConsoleIndentUtil.normalize(code, myExecuteActionHandler.getCurrentIndentSize());
+    codeFragment += "\n";
+    executeInConsole(codeFragment);
   }
 
   public void executeInConsole(final String code) {
@@ -383,7 +385,7 @@
     final XStandaloneVariablesView view = new XStandaloneVariablesView(myProject, new PyDebuggerEditorsProvider(), stackFrame);
     consoleCommunication.addCommunicationListener(new ConsoleCommunicationListener() {
       @Override
-      public void commandExecuted() {
+      public void commandExecuted(boolean more) {
         view.rebuildView();
       }
 
diff --git a/python/src/com/jetbrains/python/console/PythonDebugConsoleCommunication.java b/python/src/com/jetbrains/python/console/PythonDebugConsoleCommunication.java
index 8f55aed..d24a2a8a 100644
--- a/python/src/com/jetbrains/python/console/PythonDebugConsoleCommunication.java
+++ b/python/src/com/jetbrains/python/console/PythonDebugConsoleCommunication.java
@@ -63,8 +63,8 @@
     return false;
   }
 
-  protected void exec(final String command, final ProcessDebugger.DebugCallback<Pair<String, Boolean>> callback) {
-    myDebugProcess.consoleExec(command, new ProcessDebugger.DebugCallback<String>() {
+  protected void exec(final ConsoleCodeFragment command, final ProcessDebugger.DebugCallback<Pair<String, Boolean>> callback) {
+    myDebugProcess.consoleExec(command.getText(), new ProcessDebugger.DebugCallback<String>() {
       @Override
       public void ok(String value) {
         callback.ok(parseExecResponseString(value));
@@ -77,9 +77,9 @@
     });
   }
 
-  public void execInterpreter(String s, final Function<InterpreterResponse, Object> callback) {
-    myExpression.append(s);
-    exec(myExpression.toString(), new ProcessDebugger.DebugCallback<Pair<String, Boolean>>() {
+  public void execInterpreter(ConsoleCodeFragment code, final Function<InterpreterResponse, Object> callback) {
+    myExpression.append(code.getText());
+    exec(new ConsoleCodeFragment(myExpression.toString(), false), new ProcessDebugger.DebugCallback<Pair<String, Boolean>>() {
       @Override
       public void ok(Pair<String, Boolean> executed) {
         boolean more = executed.second;
diff --git a/python/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java b/python/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java
index 2bc6424..71f2772 100644
--- a/python/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java
+++ b/python/src/com/jetbrains/python/inspections/PyMethodMayBeStaticInspection.java
@@ -70,7 +70,9 @@
       if (!supers.isEmpty()) return;
       final Collection<PyFunction> overrides = PyOverridingMethodsSearch.search(node, true).findAll();
       if (!overrides.isEmpty()) return;
-      if (PyUtil.isDecoratedAsAbstract(node) || node.getModifier() != null) return;
+      final PyDecoratorList decoratorList = node.getDecoratorList();
+      if (decoratorList != null) return;
+      if (node.getModifier() != null) return;
       final Property property = containingClass.findPropertyByCallable(node);
       if (property != null) return;
 
diff --git a/python/src/com/jetbrains/python/parsing/ExpressionParsing.java b/python/src/com/jetbrains/python/parsing/ExpressionParsing.java
index 65c791a..790b155 100644
--- a/python/src/com/jetbrains/python/parsing/ExpressionParsing.java
+++ b/python/src/com/jetbrains/python/parsing/ExpressionParsing.java
@@ -236,7 +236,7 @@
           break;
         }
       }
-      myBuilder.advanceLexer();
+      checkMatches(PyTokenTypes.RBRACE, message("PARSE.expected.rbrace"));
       startMarker.done(PyElementTypes.DICT_LITERAL_EXPRESSION);
     }
   }
@@ -264,7 +264,7 @@
         break;
       }
     }
-    myBuilder.advanceLexer();
+    checkMatches(PyTokenTypes.RBRACE, message("PARSE.expected.rbrace"));
     startMarker.done(PyElementTypes.SET_LITERAL_EXPRESSION);
   }
 
diff --git a/python/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java b/python/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java
index 7f03dcd..7595fde 100644
--- a/python/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java
+++ b/python/src/com/jetbrains/python/psi/impl/PyStringLiteralExpressionImpl.java
@@ -21,7 +21,6 @@
 import com.intellij.lang.injection.InjectedLanguageManager;
 import com.intellij.navigation.ItemPresentation;
 import com.intellij.openapi.util.Pair;
-import com.intellij.openapi.util.Ref;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.*;
 import com.intellij.psi.impl.source.resolve.reference.ReferenceProvidersRegistry;
@@ -50,9 +49,21 @@
   public static final Pattern PATTERN_ESCAPE = Pattern
       .compile("\\\\(\n|\\\\|'|\"|a|b|f|n|r|t|v|([0-7]{1,3})|x([0-9a-fA-F]{1,2})" + "|N(\\{.*?\\})|u([0-9a-fA-F]{4})|U([0-9a-fA-F]{8}))");
          //        -> 1                        ->   2      <-->     3          <-     ->   4     <-->    5      <-   ->  6           <-<-
+
+  private enum EscapeRegexGroup {
+    WHOLE_MATCH,
+    ESCAPED_SUBSTRING,
+    OCTAL,
+    HEXADECIMAL,
+    UNICODE_NAMED,
+    UNICODE_16BIT,
+    UNICODE_32BIT
+  }
+
   private static final Map<String, String> escapeMap = initializeEscapeMap();
   private String stringValue;
   private List<TextRange> valueTextRanges;
+  @Nullable private List<Pair<TextRange, String>> myDecodedFragments;
   private final DefaultRegExpPropertiesProvider myPropertiesProvider;
 
   private static Map<String, String> initializeEscapeMap() {
@@ -85,6 +96,7 @@
     super.subtreeChanged();
     stringValue = null;
     valueTextRanges = null;
+    myDecodedFragments = null;
   }
 
   public List<TextRange> getStringValueTextRanges() {
@@ -143,20 +155,82 @@
     return text.length() > 0 && Character.toUpperCase(text.charAt(0)) == 'C';
   }
 
-  public void iterateCharacterRanges(TextRangeConsumer consumer) {
-    int elStart = getTextRange().getStartOffset();
-    for (ASTNode child : getStringNodes()) {
-      final String text = child.getText();
-      TextRange textRange = getNodeTextRange(text);
-      int offset = child.getTextRange().getStartOffset() - elStart + textRange.getStartOffset();
-      String undecoded = textRange.substring(text);
-      if (!iterateCharacterRanges(consumer, undecoded, offset, isRaw(text), isUnicode(text))) {
-        break;
+  @Override
+  @NotNull
+  public List<Pair<TextRange, String>> getDecodedFragments() {
+    if (myDecodedFragments == null) {
+      final List<Pair<TextRange, String>> result = new ArrayList<Pair<TextRange, String>>();
+      final int elementStart = getTextRange().getStartOffset();
+      for (ASTNode node : getStringNodes()) {
+        final String text = node.getText();
+        final TextRange textRange = getNodeTextRange(text);
+        final int offset = node.getTextRange().getStartOffset() - elementStart + textRange.getStartOffset();
+        final String encoded = textRange.substring(text);
+        result.addAll(getDecodedFragments(encoded, offset, isRaw(text), isUnicode(text)));
       }
+      myDecodedFragments = result;
     }
+    return myDecodedFragments;
   }
 
+  @NotNull
+  private static List<Pair<TextRange, String>> getDecodedFragments(@NotNull String encoded, int offset, boolean raw, boolean unicode) {
+    final List<Pair<TextRange, String>> result = new ArrayList<Pair<TextRange, String>>();
+    final Matcher escMatcher = PATTERN_ESCAPE.matcher(encoded);
+    int index = 0;
+    while (escMatcher.find(index)) {
+      if (index < escMatcher.start()) {
+        final TextRange range = TextRange.create(index, escMatcher.start());
+        final TextRange offsetRange = range.shiftRight(offset);
+        result.add(Pair.create(offsetRange, range.substring(encoded)));
+      }
 
+      final String octal = escapeRegexGroup(escMatcher, EscapeRegexGroup.OCTAL);
+      final String hex = escapeRegexGroup(escMatcher, EscapeRegexGroup.HEXADECIMAL);
+      // TODO: Implement unicode character name escapes: EscapeRegexGroup.UNICODE_NAMED
+      final String unicode16 = escapeRegexGroup(escMatcher, EscapeRegexGroup.UNICODE_16BIT);
+      final String unicode32 = escapeRegexGroup(escMatcher, EscapeRegexGroup.UNICODE_32BIT);
+
+      final boolean escapedUnicode = raw && unicode || !raw;
+
+      final String str;
+      if (!raw && octal != null) {
+        str = new String(new char[]{(char)Integer.parseInt(octal, 8)});
+      }
+      else if (!raw && hex != null) {
+        str = new String(new char[]{(char)Integer.parseInt(hex, 16)});
+      }
+      else if (escapedUnicode && unicode16 != null) {
+        str = unicode ? new String(new char[]{(char)Integer.parseInt(unicode16, 16)}) : unicode16;
+      }
+      else if (escapedUnicode && unicode32 != null) {
+        str = unicode ? new String(Character.toChars((int)Long.parseLong(unicode32, 16))) : unicode32;
+      }
+      else if (raw) {
+        str = escapeRegexGroup(escMatcher, EscapeRegexGroup.WHOLE_MATCH);
+      }
+      else {
+        final String toReplace = escapeRegexGroup(escMatcher, EscapeRegexGroup.ESCAPED_SUBSTRING);
+        str = escapeMap.get(toReplace);
+      }
+
+      if (str != null) {
+        final TextRange wholeMatch = TextRange.create(escMatcher.start(), escMatcher.end());
+        result.add(Pair.create(wholeMatch.shiftRight(offset), str));
+      }
+
+      index = escMatcher.end();
+    }
+    final TextRange range = TextRange.create(index, encoded.length());
+    final TextRange offRange = range.shiftRight(offset);
+    result.add(Pair.create(offRange, range.substring(encoded)));
+    return result;
+  }
+
+  @Nullable
+  private static String escapeRegexGroup(@NotNull Matcher matcher, EscapeRegexGroup group) {
+    return matcher.group(group.ordinal());
+  }
 
   public List<ASTNode> getStringNodes() {
     return Arrays.asList(getNode().getChildren(PyTokenTypes.STRING_NODES));
@@ -165,14 +239,11 @@
   public String getStringValue() {
     //ASTNode child = getNode().getFirstChildNode();
     //assert child != null;
-   if (stringValue == null) {
+    if (stringValue == null) {
       final StringBuilder out = new StringBuilder();
-      iterateCharacterRanges(new TextRangeConsumer() {
-        public boolean process(int startOffset, int endOffset, String value) {
-          out.append(value);
-          return true;
-        }
-      });
+      for (Pair<TextRange, String> fragment : getDecodedFragments()) {
+        out.append(fragment.getSecond());
+      }
       stringValue = out.toString();
     }
     return stringValue;
@@ -190,106 +261,6 @@
     return new TextRange(0, getTextLength());
   }
 
-  private static boolean iterateCharacterRanges(TextRangeConsumer consumer, String undecoded, int off, boolean raw, boolean unicode) {
-    if (raw) {
-      return iterateRawCharacterRanges(consumer, undecoded, off, unicode);
-    }
-    Matcher escMatcher = PATTERN_ESCAPE.matcher(undecoded);
-    int index = 0;
-    while (escMatcher.find(index)) {
-      for (int i = index; i < escMatcher.start(); i++) {
-        if (!consumer.process(off + i, off + i + 1, Character.toString(undecoded.charAt(i)))) {
-          return false;
-        }
-      }
-      String octal = escMatcher.group(2);
-      String hex = escMatcher.group(3);
-      String str = null;
-      if (octal != null) {
-        str = new String(new char[]{(char)Integer.parseInt(octal, 8)});
-
-      }
-      else if (hex != null) {
-        str = new String(new char[]{(char)Integer.parseInt(hex, 16)});
-
-      }
-      else {
-        String toReplace = escMatcher.group(1);
-        String replacement = escapeMap.get(toReplace);
-        if (replacement != null) {
-          str = replacement;
-        }
-      }
-      String unicodeName = escMatcher.group(4);
-      String unicode32 = escMatcher.group(6);
-
-      if (unicode32 != null) {
-        str = unicode ? new String(Character.toChars((int)Long.parseLong(unicode32, 16))) : unicode32;
-      }
-      if (unicodeName != null) {
-        //TOLATER: implement unicode character name escapes
-      }
-      String unicode16 = escMatcher.group(5);
-      if (unicode16 != null) {
-        str = unicode ? new String(new char[]{(char)Integer.parseInt(unicode16, 16)}) : unicode16;
-      }
-
-      if (str != null) {
-        int start = escMatcher.start();
-        int end = escMatcher.end();
-        if (!consumer.process(off + start, off + end, str)) {
-          return false;
-        }
-      }
-      index = escMatcher.end();
-    }
-    for (int i = index; i < undecoded.length(); i++) {
-      if (!consumer.process(off + i, off + i + 1, Character.toString(undecoded.charAt(i)))) {
-        return false;
-      }
-    }
-    return true;
-  }
-
-  private static boolean iterateRawCharacterRanges(TextRangeConsumer consumer, String undecoded, int off, boolean unicode) {
-    for (int i = 0; i < undecoded.length(); i++) {
-      char c = undecoded.charAt(i);
-      if (unicode && c == '\\' && i < undecoded.length()-1) {
-        char c2 = undecoded.charAt(i+1);
-        if (c2 == 'u' && i < undecoded.length()-5) {
-          try {
-            char u = (char) Integer.parseInt(undecoded.substring(i+2, i+6), 16);
-            if (!consumer.process(off+i, off+i+ 6, Character.toString(u))) {
-              return false;
-            }
-          }
-          catch (NumberFormatException ignore) { }
-          //noinspection AssignmentToForLoopParameter
-          i += 5;
-          continue;
-        }
-        if (c2 == 'U' && i < undecoded.length()-9) {
-          // note: Java has 16-bit chars, so this code will truncate characters which don't fit in 16 bits
-          try {
-            char u = (char) Long.parseLong(undecoded.substring(i+2, i+10), 16);
-            if (!consumer.process(off+i, off+i+10, Character.toString(u))) {
-              return false;
-            }
-          }
-          catch (NumberFormatException ignore) { }
-          //noinspection AssignmentToForLoopParameter
-          i += 9;
-          continue;
-        }
-      }
-      if (!consumer.process(off + i, off + i + 1, Character.toString(c))) {
-        return false;
-      }
-    }
-
-    return true;
-  }
-
   @Override
   public String toString() {
     return super.toString() + ": " + getStringValue();
@@ -368,57 +339,60 @@
 
     @Override
     public boolean decode(@NotNull final TextRange rangeInsideHost, @NotNull final StringBuilder outChars) {
-      final PyDocStringOwner
-        docStringOwner = PsiTreeUtil.getParentOfType(myHost, PyDocStringOwner.class);
-      if (docStringOwner != null && myHost.equals(docStringOwner.getDocStringExpression())) {
-        outChars.append(myHost.getText(), rangeInsideHost.getStartOffset(), rangeInsideHost.getEndOffset());
-      }
-      else {
-        myHost.iterateCharacterRanges(new TextRangeConsumer() {
-          public boolean process(int startOffset, int endOffset, String value) {
-            int xsectStart = Math.max(startOffset, rangeInsideHost.getStartOffset());
-            int xsectEnd = Math.min(endOffset, rangeInsideHost.getEndOffset());
-            if (xsectEnd > xsectStart) {
-              outChars.append(value);
-            }
-            return endOffset < rangeInsideHost.getEndOffset();
+      for (Pair<TextRange, String> fragment : myHost.getDecodedFragments()) {
+        final TextRange encodedTextRange = fragment.getFirst();
+        final TextRange intersection = encodedTextRange.intersection(rangeInsideHost);
+        if (intersection != null && !intersection.isEmpty()) {
+          final String value = fragment.getSecond();
+          final String intersectedValue;
+          if (value.length() == 1 || value.length() == intersection.getLength()) {
+            intersectedValue = value;
           }
-        });
+          else {
+            final int start = Math.max(0, rangeInsideHost.getStartOffset() - encodedTextRange.getStartOffset());
+            final int end = Math.min(value.length(), start + intersection.getLength());
+            intersectedValue = value.substring(start, end);
+          }
+          outChars.append(intersectedValue);
+        }
       }
       return true;
     }
 
     @Override
     public int getOffsetInHost(final int offsetInDecoded, @NotNull final TextRange rangeInsideHost) {
-      final Ref<Integer> resultRef = Ref.create(-1);
-      final Ref<Integer> indexRef = Ref.create(0);
-      final Ref<Integer> lastEndOffsetRef = Ref.create(-1);
-      myHost.iterateCharacterRanges(new TextRangeConsumer() {
-        @Override
-        public boolean process(int startOffset, int endOffset, String value) {
-          if (startOffset > rangeInsideHost.getEndOffset()) {
-            return false;
+      int offset = 0;
+      int endOffset = -1;
+      for (Pair<TextRange, String> fragment : myHost.getDecodedFragments()) {
+        final TextRange encodedTextRange = fragment.getFirst();
+        final TextRange intersection = encodedTextRange.intersection(rangeInsideHost);
+        if (intersection != null && !intersection.isEmpty()) {
+          final String value = fragment.getSecond();
+          final int valueLength = value.length();
+          final int intersectionLength = intersection.getLength();
+          if (valueLength == 0) {
+            return -1;
           }
-          lastEndOffsetRef.set(endOffset);
-          if (startOffset >= rangeInsideHost.getStartOffset()) {
-            final int i = indexRef.get();
-            if (i == offsetInDecoded) {
-              resultRef.set(startOffset);
-              return false;
+          else if (valueLength == 1) {
+            if (offset == offsetInDecoded) {
+              return intersection.getStartOffset();
             }
-            indexRef.set(i + 1);
+            offset++;
           }
-          return true;
+          else {
+            if (offset + intersectionLength >= offsetInDecoded) {
+              final int delta = offsetInDecoded - offset;
+              return intersection.getStartOffset() + delta;
+            }
+            offset += intersectionLength;
+          }
+          endOffset = intersection.getEndOffset();
         }
-      });
-      final int result = resultRef.get();
-      if (result != -1) {
-        return result;
       }
-      // We should handle the position of a character at the end of rangeInsideHost, because LeafPatcher expects it to be valid
-      final int lastEndOffset = lastEndOffsetRef.get();
-      if (indexRef.get() == offsetInDecoded && lastEndOffset == rangeInsideHost.getEndOffset()) {
-        return lastEndOffset;
+      // XXX: According to the real use of getOffsetInHost() it should return the correct host offset for the offset in decoded at the
+      // end of the range inside host, not -1
+      if (offset == offsetInDecoded) {
+        return endOffset;
       }
       return -1;
     }
@@ -431,23 +405,7 @@
 
   @Override
   public int valueOffsetToTextOffset(int valueOffset) {
-    final Ref<Integer> offsetInDecodedRef = new Ref<Integer>(valueOffset);
-    final Ref<Integer> result = new Ref<Integer>(-1);
-    iterateCharacterRanges(new TextRangeConsumer() {
-      public boolean process(int startOffset, int endOffset, String value) {
-        if (value.length() > offsetInDecodedRef.get()) {
-          result.set(startOffset + offsetInDecodedRef.get());
-          return false;
-        }
-        offsetInDecodedRef.set(offsetInDecodedRef.get() - value.length());
-        if (offsetInDecodedRef.get() == 0) {
-          result.set(endOffset);
-          return false;
-        }
-        return true;
-      }
-    });
-    return result.get();
+    return createLiteralTextEscaper().getOffsetInHost(valueOffset, getStringValueTextRange());
   }
 
   public boolean characterNeedsEscaping(char c) {
diff --git a/python/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java b/python/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java
index 57fe1a6..6a80851 100644
--- a/python/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java
+++ b/python/src/com/jetbrains/python/psi/resolve/ResolveImportUtil.java
@@ -15,6 +15,7 @@
  */
 package com.jetbrains.python.psi.resolve;
 
+import com.intellij.openapi.extensions.Extensions;
 import com.intellij.openapi.module.Module;
 import com.intellij.openapi.module.ModuleUtilCore;
 import com.intellij.openapi.projectRoots.Sdk;
@@ -366,6 +367,9 @@
           if (vFile != null && vFile.getLength() > 0) {
             rate += 100;
           }
+          for (PyResolveResultRater rater : Extensions.getExtensions(PyResolveResultRater.EP_NAME)) {
+            rate += rater.getRate(target);
+          }
         }
         ret.poke(target, rate);
       }
diff --git a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java
index f5ba918..9b11d15 100644
--- a/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java
+++ b/python/src/com/jetbrains/python/refactoring/classes/PyClassRefactoringUtil.java
@@ -25,16 +25,15 @@
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtilBase;
 import com.intellij.psi.util.PsiUtilCore;
+import com.intellij.psi.util.QualifiedName;
 import com.jetbrains.python.PyNames;
 import com.jetbrains.python.PythonFileType;
 import com.jetbrains.python.codeInsight.PyCodeInsightSettings;
 import com.jetbrains.python.codeInsight.imports.AddImportHelper;
-import com.jetbrains.python.documentation.DocStringTypeReference;
 import com.jetbrains.python.psi.*;
 import com.jetbrains.python.psi.impl.PyBuiltinCache;
 import com.jetbrains.python.psi.impl.PyImportedModule;
 import com.jetbrains.python.psi.impl.PyPsiUtils;
-import com.intellij.psi.util.QualifiedName;
 import com.jetbrains.python.psi.resolve.QualifiedNameFinder;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -190,7 +189,7 @@
       public void visitPyStringLiteralExpression(PyStringLiteralExpression node) {
         super.visitPyStringLiteralExpression(node);
         for (PsiReference ref : node.getReferences()) {
-          if (ref instanceof DocStringTypeReference && ref.isReferenceTo(oldElement)) {
+          if (ref.isReferenceTo(oldElement)) {
             ref.bindToElement(newElement);
           }
         }
diff --git a/python/src/com/jetbrains/python/refactoring/move/PyMoveClassOrFunctionProcessor.java b/python/src/com/jetbrains/python/refactoring/move/PyMoveClassOrFunctionProcessor.java
index fe4da8e..5c22514 100644
--- a/python/src/com/jetbrains/python/refactoring/move/PyMoveClassOrFunctionProcessor.java
+++ b/python/src/com/jetbrains/python/refactoring/move/PyMoveClassOrFunctionProcessor.java
@@ -23,6 +23,7 @@
 import com.intellij.psi.*;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.psi.util.PsiUtilCore;
+import com.intellij.psi.util.QualifiedName;
 import com.intellij.refactoring.BaseRefactoringProcessor;
 import com.intellij.refactoring.ui.UsageViewDescriptorAdapter;
 import com.intellij.refactoring.util.CommonRefactoringUtil;
@@ -33,9 +34,7 @@
 import com.jetbrains.python.PyNames;
 import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil;
 import com.jetbrains.python.codeInsight.imports.PyImportOptimizer;
-import com.jetbrains.python.documentation.DocStringTypeReference;
 import com.jetbrains.python.psi.*;
-import com.intellij.psi.util.QualifiedName;
 import com.jetbrains.python.psi.resolve.QualifiedNameFinder;
 import com.jetbrains.python.refactoring.PyRefactoringUtil;
 import com.jetbrains.python.refactoring.classes.PyClassRefactoringUtil;
@@ -193,7 +192,7 @@
     }
     if (usage instanceof PyStringLiteralExpression) {
       for (PsiReference ref : usage.getReferences()) {
-        if (ref instanceof DocStringTypeReference && ref.isReferenceTo(oldElement)) {
+        if (ref.isReferenceTo(oldElement)) {
           ref.bindToElement(newElement);
         }
       }
diff --git a/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryExceptSurrounder.java b/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryExceptSurrounder.java
index 5cdaba2..25a9f26 100644
--- a/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryExceptSurrounder.java
+++ b/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryExceptSurrounder.java
@@ -22,7 +22,6 @@
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
-import com.intellij.psi.codeStyle.CodeStyleManager;
 import com.intellij.psi.util.PsiTreeUtil;
 import com.intellij.util.IncorrectOperationException;
 import com.jetbrains.python.PyBundle;
@@ -53,9 +52,10 @@
 
     final PsiFile psiFile = parent.getContainingFile();
     final Document document = psiFile.getViewProvider().getDocument();
-    final RangeMarker rangeMarker = document.createRangeMarker(tryStatement.getTextRange());
+    final TextRange range = tryStatement.getTextRange();
+    assert document != null;
+    final RangeMarker rangeMarker = document.createRangeMarker(range);
 
-    CodeStyleManager.getInstance(project).reformat(psiFile);
     final PsiElement element = psiFile.findElementAt(rangeMarker.getStartOffset());
     tryStatement = PsiTreeUtil.getParentOfType(element, PyTryExceptStatement.class);
     if (tryStatement != null) {
@@ -70,7 +70,9 @@
 
   protected TextRange getResultRange(PyTryExceptStatement tryStatement) {
     final PyExceptPart part = tryStatement.getExceptParts()[0];
-    return part.getStatementList().getTextRange();
+    final PyStatementList list = part.getStatementList();
+    assert list != null;
+    return list.getTextRange();
   }
 
   public String getTemplateDescription() {
diff --git a/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryFinallySurrounder.java b/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryFinallySurrounder.java
index 54e2c27..d457e32 100644
--- a/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryFinallySurrounder.java
+++ b/python/src/com/jetbrains/python/refactoring/surround/surrounders/statements/PyWithTryFinallySurrounder.java
@@ -17,6 +17,8 @@
 
 import com.intellij.codeInsight.CodeInsightBundle;
 import com.intellij.openapi.util.TextRange;
+import com.jetbrains.python.psi.PyFinallyPart;
+import com.jetbrains.python.psi.PyStatementList;
 import com.jetbrains.python.psi.PyTryExceptStatement;
 
 /**
@@ -37,6 +39,10 @@
 
   @Override
   protected TextRange getResultRange(PyTryExceptStatement tryStatement) {
-    return tryStatement.getFinallyPart().getStatementList().getTextRange();
+    final PyFinallyPart finallyPart = tryStatement.getFinallyPart();
+    assert finallyPart != null;
+    final PyStatementList statementList = finallyPart.getStatementList();
+    assert statementList != null;
+    return statementList.getTextRange();
   }
 }
diff --git a/python/src/com/jetbrains/python/run/PyRemoteProcessStarter.java b/python/src/com/jetbrains/python/run/PyRemoteProcessStarter.java
index 5fc0bc8..ba272c6 100644
--- a/python/src/com/jetbrains/python/run/PyRemoteProcessStarter.java
+++ b/python/src/com/jetbrains/python/run/PyRemoteProcessStarter.java
@@ -23,7 +23,6 @@
 import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.projectRoots.Sdk;
-import com.intellij.openapi.ui.Messages;
 import com.intellij.util.PathMappingSettings;
 import com.jetbrains.python.remote.PyRemoteSdkData;
 import com.jetbrains.python.remote.PythonRemoteInterpreterManager;
@@ -43,21 +42,15 @@
     if (manager != null) {
       ProcessHandler processHandler;
 
-      while (true) {
-        try {
-          processHandler = doStartRemoteProcess(sdk, commandLine, manager, project, mappingSettings);
-          break;
+      try {
+        processHandler = doStartRemoteProcess(sdk, commandLine, manager, project, mappingSettings);
+      }
+      catch (ExecutionException e) {
+        final Application application = ApplicationManager.getApplication();
+        if (application != null && (application.isUnitTestMode() || application.isHeadlessEnvironment())) {
+          throw new RuntimeException(e);
         }
-        catch (ExecutionException e) {
-          final Application application = ApplicationManager.getApplication();
-          if (application != null && (application.isUnitTestMode() || application.isHeadlessEnvironment())) {
-            throw new RuntimeException(e);
-          }
-          if (Messages.showYesNoDialog(e.getMessage() + "\nTry again?", "Can't Run Remote Interpreter", Messages.getErrorIcon()) ==
-              Messages.NO) {
-            throw new ExecutionException("Can't run remote python interpreter: " + e.getMessage(), e);
-          }
-        }
+        throw new ExecutionException("Can't run remote python interpreter: " + e.getMessage(), e);
       }
       ProcessTerminatedListener.attach(processHandler);
       return processHandler;
diff --git a/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerStrategy.java b/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerStrategy.java
index 4a0a59d..b24e53c 100644
--- a/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerStrategy.java
+++ b/python/src/com/jetbrains/python/spellchecker/PythonSpellcheckerStrategy.java
@@ -15,6 +15,7 @@
  */
 package com.jetbrains.python.spellchecker;
 
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.PsiElement;
 import com.intellij.spellchecker.inspections.PlainTextSplitter;
@@ -26,7 +27,6 @@
 import com.jetbrains.python.inspections.PyStringFormatParser;
 import com.jetbrains.python.psi.PyBinaryExpression;
 import com.jetbrains.python.psi.PyStringLiteralExpression;
-import com.jetbrains.python.psi.impl.PyStringLiteralExpressionImpl;
 import org.jetbrains.annotations.NotNull;
 
 import java.util.List;
@@ -41,9 +41,11 @@
       Splitter splitter = PlainTextSplitter.getInstance();
       String text = element.getText();
       if (text.indexOf('\\') >= 0) {
-        MyTextRangeConsumer textRangeConsumer = new MyTextRangeConsumer(element, consumer);
-        ((PyStringLiteralExpressionImpl) element).iterateCharacterRanges(textRangeConsumer);
-        textRangeConsumer.processCurrentToken();   // process last token
+        for (Pair<TextRange, String> fragment : element.getDecodedFragments()) {
+          final String value = fragment.getSecond();
+          consumer.consumeToken(element, value, false, fragment.getFirst().getStartOffset(), TextRange.allOf(value),
+                                PlainTextSplitter.getInstance());
+        }
       }
       else if (text.startsWith("u") || text.startsWith("U") || text.startsWith("r") || text.startsWith("R") ||
           text.startsWith("b") || text.startsWith("B")) {
@@ -57,40 +59,6 @@
         consumer.consumeToken(element, splitter);
       }
     }
-
-    private static class MyTextRangeConsumer implements PyStringLiteralExpressionImpl.TextRangeConsumer {
-      private final StringBuilder myCurrentToken = new StringBuilder();
-      private final PyStringLiteralExpression myElement;
-      private final TokenConsumer myTokenConsumer;
-      private int myTokenStart;
-
-      public MyTextRangeConsumer(PyStringLiteralExpression element, TokenConsumer tokenConsumer) {
-        myElement = element;
-        myTokenConsumer = tokenConsumer;
-      }
-
-      @Override
-      public boolean process(int startOffset, int endOffset, String value) {
-        if (endOffset == startOffset + 1) {
-          if (myCurrentToken.length() == 0) {
-            myTokenStart = startOffset;
-          }
-          myCurrentToken.append(value);
-        }
-        else {
-          if (myCurrentToken.length() > 0) {
-            processCurrentToken();
-            myCurrentToken.setLength(0);
-          }
-        }
-        return true;
-      }
-
-      private void processCurrentToken() {
-        String token = myCurrentToken.toString();
-        myTokenConsumer.consumeToken(myElement, token, false, myTokenStart, TextRange.allOf(token), PlainTextSplitter.getInstance());
-      }
-    }
   }
 
   private static class FormatStringTokenizer extends Tokenizer<PyStringLiteralExpression> {
diff --git a/python/src/com/jetbrains/python/testing/PythonTestCommandLineStateBase.java b/python/src/com/jetbrains/python/testing/PythonTestCommandLineStateBase.java
index ef16a65..39e4e96 100644
--- a/python/src/com/jetbrains/python/testing/PythonTestCommandLineStateBase.java
+++ b/python/src/com/jetbrains/python/testing/PythonTestCommandLineStateBase.java
@@ -106,9 +106,10 @@
     return cmd;
   }
 
-  private void setWorkingDirectory(@NotNull final GeneralCommandLine cmd) {
-    if (!StringUtil.isEmptyOrSpaces(myConfiguration.getWorkingDirectory())) {
-      cmd.setWorkDirectory(myConfiguration.getWorkingDirectory());
+  protected void setWorkingDirectory(@NotNull final GeneralCommandLine cmd) {
+    final String workingDirectory = myConfiguration.getWorkingDirectory();
+    if (!StringUtil.isEmptyOrSpaces(workingDirectory)) {
+      cmd.setWorkDirectory(workingDirectory);
     }
     else if (myConfiguration instanceof AbstractPythonTestRunConfiguration) {
       final String folderName = ((AbstractPythonTestRunConfiguration)myConfiguration).getFolderName();
diff --git a/python/src/com/jetbrains/python/testing/PythonTestConfigurationProducer.java b/python/src/com/jetbrains/python/testing/PythonTestConfigurationProducer.java
index 3875cd3..8c28e08 100644
--- a/python/src/com/jetbrains/python/testing/PythonTestConfigurationProducer.java
+++ b/python/src/com/jetbrains/python/testing/PythonTestConfigurationProducer.java
@@ -18,6 +18,7 @@
 import com.google.common.collect.Sets;
 import com.intellij.execution.Location;
 import com.intellij.execution.actions.ConfigurationContext;
+import com.intellij.execution.actions.ConfigurationFromContext;
 import com.intellij.execution.actions.RunConfigurationProducer;
 import com.intellij.execution.configurations.ConfigurationFactory;
 import com.intellij.facet.Facet;
@@ -39,6 +40,7 @@
 import com.jetbrains.python.PythonModuleTypeBase;
 import com.jetbrains.python.facet.PythonFacetSettings;
 import com.jetbrains.python.psi.*;
+import com.jetbrains.python.run.PythonRunConfigurationProducer;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -254,4 +256,8 @@
     return PythonUnitTestUtil.getTestCaseClassesFromFile(pyFile);
   }
 
+  @Override
+  public boolean isPreferredConfiguration(ConfigurationFromContext self, ConfigurationFromContext other) {
+    return other.isProducedBy(PythonTestConfigurationProducer.class) || other.isProducedBy(PythonRunConfigurationProducer.class);
+  }
 }
\ No newline at end of file
diff --git a/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java b/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java
index d0b4ea1..9394143 100644
--- a/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java
+++ b/python/src/com/jetbrains/python/testing/PythonUnitTestUtil.java
@@ -93,7 +93,7 @@
       }
     }
     for (PyFunction cls : file.getTopLevelFunctions()) {
-      if (isTestCaseFunction(cls)) {
+      if (isTestCaseFunction(cls, false)) {
         result.add(cls);
       }
     }
@@ -115,9 +115,9 @@
     }
     if (checkAssert) {
       boolean hasAssert = hasAssertOrYield(function.getStatementList());
-      if (!hasAssert) return false;
+      if (hasAssert) return true;
     }
-    return true;
+    return false;
   }
 
   private static boolean hasAssertOrYield(PyStatementList list) {
diff --git a/python/src/com/jetbrains/python/testing/doctest/PythonDocTestConfigurationProducer.java b/python/src/com/jetbrains/python/testing/doctest/PythonDocTestConfigurationProducer.java
index cfa2be7..e3eef29 100644
--- a/python/src/com/jetbrains/python/testing/doctest/PythonDocTestConfigurationProducer.java
+++ b/python/src/com/jetbrains/python/testing/doctest/PythonDocTestConfigurationProducer.java
@@ -21,6 +21,8 @@
 
 import com.intellij.execution.Location;
 import com.intellij.openapi.module.Module;
+import com.intellij.openapi.project.Project;
+import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.PsiRecursiveElementVisitor;
@@ -85,4 +87,10 @@
       }
     }
   }
+
+  @Override
+  protected boolean isTestFolder(@NotNull VirtualFile virtualFile, @NotNull Project project) {
+    return false;
+  }
+
 }
\ No newline at end of file
diff --git a/python/src/com/jetbrains/python/testing/pytest/PyTestRunnableScriptFilter.java b/python/src/com/jetbrains/python/testing/pytest/PyTestRunnableScriptFilter.java
deleted file mode 100644
index 036663b..0000000
--- a/python/src/com/jetbrains/python/testing/pytest/PyTestRunnableScriptFilter.java
+++ /dev/null
@@ -1,83 +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.jetbrains.python.testing.pytest;
-
-import com.intellij.execution.Location;
-import com.intellij.openapi.module.Module;
-import com.intellij.openapi.projectRoots.Sdk;
-import com.intellij.psi.PsiFile;
-import com.jetbrains.python.psi.PyClass;
-import com.jetbrains.python.psi.PyFile;
-import com.jetbrains.python.psi.PyFunction;
-import com.jetbrains.python.psi.PyRecursiveElementVisitor;
-import com.jetbrains.python.run.RunnableScriptFilter;
-import com.jetbrains.python.sdk.PythonSdkType;
-import com.jetbrains.python.testing.PythonTestConfigurationsModel;
-import com.jetbrains.python.testing.TestRunnerService;
-import com.jetbrains.python.testing.VFSTestFrameworkListener;
-import org.jetbrains.annotations.NotNull;
-
-/**
- * @author yole
- */
-public class PyTestRunnableScriptFilter implements RunnableScriptFilter {
-  public boolean isRunnableScript(PsiFile script, @NotNull Module module, Location location) {
-    return isPyTestInstalled(module) && isPyTestScript(script) &&
-      TestRunnerService.getInstance(module).getProjectConfiguration().
-        equals(PythonTestConfigurationsModel.PY_TEST_NAME);
-  }
-
-  private static boolean isPyTestInstalled(Module module) {
-    // TODO[yole] add caching to avoid disk I/O in findPyTestRunner()?
-    final Sdk sdk = PythonSdkType.findPythonSdk(module);
-    return sdk != null && VFSTestFrameworkListener.getInstance().isPyTestInstalled(sdk);
-  }
-
-  public static boolean isPyTestScript(PsiFile script) {
-    if (!(script instanceof PyFile)) {
-      return false;
-    }
-    PyTestVisitor testVisitor = new PyTestVisitor();
-    script.accept(testVisitor);
-    return testVisitor.isTestsFound();
-  }
-
-  private static class PyTestVisitor extends PyRecursiveElementVisitor {
-    private boolean myTestsFound = false;
-
-    public boolean isTestsFound() {
-      return myTestsFound;
-    }
-
-    @Override
-    public void visitPyFunction(PyFunction node) {
-      super.visitPyFunction(node);
-      String name = node.getName();
-      if (name != null && name.startsWith("test")) {
-        myTestsFound = true;
-      }
-    }
-
-    @Override
-    public void visitPyClass(PyClass node) {
-      super.visitPyClass(node);
-      String name = node.getName();
-      if (name != null && name.startsWith("Test")) {
-        myTestsFound = true;
-      }
-    }
-  }
-}
diff --git a/python/testData/completion/epydocParamTag.py b/python/testData/completion/epydocParamTag.py
index 6323111..e74df8d 100644
--- a/python/testData/completion/epydocParamTag.py
+++ b/python/testData/completion/epydocParamTag.py
@@ -1,2 +1,2 @@
 def foo(bar):
-    """ @param <caret> """
\ No newline at end of file
+    """ @param b<caret> """
\ No newline at end of file
diff --git a/python/testData/completion/identifiersInPlainDocstring.after.py b/python/testData/completion/identifiersInPlainDocstring.after.py
deleted file mode 100644
index 440570b..0000000
--- a/python/testData/completion/identifiersInPlainDocstring.after.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def foo(bar):
-    """ Variable bar """
\ No newline at end of file
diff --git a/python/testData/inspections/PyMethodMayBeStaticInspection/decorated.py b/python/testData/inspections/PyMethodMayBeStaticInspection/decorated.py
new file mode 100644
index 0000000..c16da1e
--- /dev/null
+++ b/python/testData/inspections/PyMethodMayBeStaticInspection/decorated.py
@@ -0,0 +1,15 @@
+def bar(f):
+    def wrapper(self, *args, **kwargs):
+        print('running {cls}.{method}'.format(cls=type(self).__name__,
+                                              method=f.__name__))
+        return f(self, *args, **kwargs)
+    return wrapper
+
+
+class C(object):
+    @bar
+    def foo(self):  # False positive: self is used by @bar
+        return 'foo'
+
+
+C().foo()
\ No newline at end of file
diff --git a/python/testData/inspections/spelling/ignoreEscapeSequence.py b/python/testData/inspections/spelling/ignoreEscapeSequence.py
index 3bd99651..95e8df4 100644
--- a/python/testData/inspections/spelling/ignoreEscapeSequence.py
+++ b/python/testData/inspections/spelling/ignoreEscapeSequence.py
@@ -1 +1,2 @@
-print "foo\nsomething"
\ No newline at end of file
+print "foo\nsomething"
+print """foo\n<TYPO descr="Typo: In word 'brbrbr'">brbrbr</TYPO>"""
diff --git a/python/testData/psi/NotClosedBraceDict.py b/python/testData/psi/NotClosedBraceDict.py
new file mode 100644
index 0000000..9a72624
--- /dev/null
+++ b/python/testData/psi/NotClosedBraceDict.py
@@ -0,0 +1,3 @@
+a = {
+        'b': 'c',
+    ]
\ No newline at end of file
diff --git a/python/testData/psi/NotClosedBraceDict.txt b/python/testData/psi/NotClosedBraceDict.txt
new file mode 100644
index 0000000..1222ea3
--- /dev/null
+++ b/python/testData/psi/NotClosedBraceDict.txt
@@ -0,0 +1,24 @@
+PyFile:NotClosedBraceDict.py
+  PyAssignmentStatement
+    PyTargetExpression: a
+      PsiElement(Py:IDENTIFIER)('a')
+    PsiWhiteSpace(' ')
+    PsiElement(Py:EQ)('=')
+    PsiWhiteSpace(' ')
+    PyDictLiteralExpression
+      PsiElement(Py:LBRACE)('{')
+      PsiWhiteSpace('\n        ')
+      PyKeyValueExpression
+        PyStringLiteralExpression: b
+          PsiElement(Py:SINGLE_QUOTED_STRING)(''b'')
+        PsiElement(Py:COLON)(':')
+        PsiWhiteSpace(' ')
+        PyStringLiteralExpression: c
+          PsiElement(Py:SINGLE_QUOTED_STRING)(''c'')
+      PsiElement(Py:COMMA)(',')
+      PsiErrorElement:'}' expected
+        <empty list>
+  PsiWhiteSpace('\n    ')
+  PsiElement(Py:RBRACKET)(']')
+  PsiErrorElement:Statement expected, found Py:RBRACKET
+    <empty list>
\ No newline at end of file
diff --git a/python/testData/psi/NotClosedBraceSet.py b/python/testData/psi/NotClosedBraceSet.py
new file mode 100644
index 0000000..71817f2
--- /dev/null
+++ b/python/testData/psi/NotClosedBraceSet.py
@@ -0,0 +1 @@
+a = {'b',]
\ No newline at end of file
diff --git a/python/testData/psi/NotClosedBraceSet.txt b/python/testData/psi/NotClosedBraceSet.txt
new file mode 100644
index 0000000..95b97f0
--- /dev/null
+++ b/python/testData/psi/NotClosedBraceSet.txt
@@ -0,0 +1,17 @@
+PyFile:NotClosedBraceSet.py
+  PyAssignmentStatement
+    PyTargetExpression: a
+      PsiElement(Py:IDENTIFIER)('a')
+    PsiWhiteSpace(' ')
+    PsiElement(Py:EQ)('=')
+    PsiWhiteSpace(' ')
+    PySetLiteralExpression
+      PsiElement(Py:LBRACE)('{')
+      PyStringLiteralExpression: b
+        PsiElement(Py:SINGLE_QUOTED_STRING)(''b'')
+      PsiElement(Py:COMMA)(',')
+      PsiErrorElement:'}' expected
+        <empty list>
+  PsiElement(Py:RBRACKET)(']')
+  PsiErrorElement:Statement expected, found Py:RBRACKET
+    <empty list>
\ No newline at end of file
diff --git a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams.py b/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams.py
deleted file mode 100644
index 7cdd655..0000000
--- a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams.py
+++ /dev/null
@@ -1,10 +0,0 @@
-__author__ = 'ktisha'
-
-def foo(x):
-  return x
-
-class A():
-
-    @accepts(int, int)
-    def my_<caret>method(self):
-        print "Smth"
\ No newline at end of file
diff --git a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams_after.py b/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams_after.py
deleted file mode 100644
index 21293a9..0000000
--- a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/decoWithParams_after.py
+++ /dev/null
@@ -1,11 +0,0 @@
-__author__ = 'ktisha'
-
-def foo(x):
-  return x
-
-class A():
-
-    @staticmethod
-    @accepts(int, int)
-    def my_<caret>method():
-        print "Smth"
\ No newline at end of file
diff --git a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/functionWithDeco.py b/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/functionWithDeco.py
deleted file mode 100644
index dded2b0..0000000
--- a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/functionWithDeco.py
+++ /dev/null
@@ -1,10 +0,0 @@
-__author__ = 'ktisha'
-
-def foo(x):
-  return x
-
-class A():
-
-    @my_deco
-    def my_<caret>method(self):
-        print "Smth"
\ No newline at end of file
diff --git a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/functionWithDeco_after.py b/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/functionWithDeco_after.py
deleted file mode 100644
index 36607a4..0000000
--- a/python/testData/quickFixes/PyMakeMethodStaticQuickFixTest/functionWithDeco_after.py
+++ /dev/null
@@ -1,11 +0,0 @@
-__author__ = 'ktisha'
-
-def foo(x):
-  return x
-
-class A():
-
-    @staticmethod
-    @my_deco
-    def my_method():
-        print "Smth"
\ No newline at end of file
diff --git a/python/testData/surround/SurroundWithTryExcept.py b/python/testData/surround/SurroundWithTryExcept.py
index faee07e..ee6e2cb 100644
--- a/python/testData/surround/SurroundWithTryExcept.py
+++ b/python/testData/surround/SurroundWithTryExcept.py
@@ -1,2 +1,2 @@
 def foo():
-    <selection>print "hello"</selection>    
\ No newline at end of file
+    pr<caret>int "hello"
\ No newline at end of file
diff --git a/python/testData/surround/SurroundWithTryExcept_after.py b/python/testData/surround/SurroundWithTryExcept_after.py
index 54b20bc..ae244ff 100644
--- a/python/testData/surround/SurroundWithTryExcept_after.py
+++ b/python/testData/surround/SurroundWithTryExcept_after.py
@@ -2,4 +2,4 @@
     try:
         print "hello"
     except:
-        <selection>pass</selection>    
\ No newline at end of file
+        <selection>pass</selection>
diff --git a/python/testSrc/com/jetbrains/python/PyStringLiteralTest.java b/python/testSrc/com/jetbrains/python/PyStringLiteralTest.java
index 7f5b08a..3933584 100644
--- a/python/testSrc/com/jetbrains/python/PyStringLiteralTest.java
+++ b/python/testSrc/com/jetbrains/python/PyStringLiteralTest.java
@@ -15,6 +15,7 @@
  */
 package com.jetbrains.python;
 
+import com.intellij.openapi.util.Pair;
 import com.intellij.openapi.util.TextRange;
 import com.intellij.psi.LiteralTextEscaper;
 import com.intellij.psi.PsiFile;
@@ -64,19 +65,54 @@
     assertEquals(-1, escaper.getOffsetInHost(4, fooOnly));
   }
 
-  public void testIterateCharacterRanges() {
-    final PyStringLiteralExpression expr = createLiteralFromText("'\\nfoo'  'bar'");
+  public void testEscaperOffsetInSingleCharString() {
+    final PyStringLiteralExpression expr = createLiteralFromText("'c'");
     assertNotNull(expr);
-    final List<String> characters = new ArrayList<String>();
-    expr.iterateCharacterRanges(new PyStringLiteralExpression.TextRangeConsumer() {
-      @Override
-      public boolean process(int startOffset, int endOffset, String value) {
-        characters.add(value);
-        return true;
-      }
-    });
-    final List<String> expected = Arrays.asList("\n", "f", "o", "o", "b", "a", "r");
-    assertSameElements(characters, expected);
+    final LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = expr.createLiteralTextEscaper();
+    final TextRange range = TextRange.create(1, 2);
+    assertEquals(1, escaper.getOffsetInHost(0, range));
+    assertEquals(2, escaper.getOffsetInHost(1, range));
+    assertEquals(-1, escaper.getOffsetInHost(2, range));
+  }
+
+  public void testEscaperOffsetInSingleEscapedCharString() {
+    final PyStringLiteralExpression expr = createLiteralFromText("'\\n'");
+    assertNotNull(expr);
+    final LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = expr.createLiteralTextEscaper();
+    final TextRange range = TextRange.create(1, 3);
+    assertEquals(1, escaper.getOffsetInHost(0, range));
+    assertEquals(3, escaper.getOffsetInHost(1, range));
+    assertEquals(-1, escaper.getOffsetInHost(2, range));
+  }
+
+  public void testIterateCharacterRanges() {
+    assertSameElements(getCharacterRanges("'\\nfoo'  'bar'"),
+                       Arrays.asList("\n", "foo", "bar"));
+  }
+
+  public void testIterateEscapedBackslash() {
+    assertSameElements(getCharacterRanges("'''\n" +
+                                          "foo.\\\\\n" +
+                                          "bar\n" +
+                                          "'''\n"),
+                       Arrays.asList("\nfoo.", "\\", "\nbar\n"));
+  }
+
+  public void testEscaperOffsetInEscapedBackslash() {
+    final PyStringLiteralExpression expr = createLiteralFromText("'XXX foo.\\\\bar YYY'");
+    assertNotNull(expr);
+    final LiteralTextEscaper<? extends PsiLanguageInjectionHost> escaper = expr.createLiteralTextEscaper();
+    final TextRange range = TextRange.create(5, 14);
+    assertEquals(5, escaper.getOffsetInHost(0, range));
+    assertEquals(6, escaper.getOffsetInHost(1, range));
+    assertEquals(7, escaper.getOffsetInHost(2, range));
+    assertEquals(8, escaper.getOffsetInHost(3, range));
+    assertEquals(9, escaper.getOffsetInHost(4, range));
+    assertEquals(11, escaper.getOffsetInHost(5, range));
+    assertEquals(12, escaper.getOffsetInHost(6, range));
+    assertEquals(13, escaper.getOffsetInHost(7, range));
+    assertEquals(14, escaper.getOffsetInHost(8, range));
+    assertEquals(-1, escaper.getOffsetInHost(9, range));
   }
 
   private static String decodeRange(PyStringLiteralExpression expr, TextRange range) {
@@ -100,4 +136,14 @@
     assertEquals("b\\n", createLiteralFromText("ur'\\u0062\\n'").getStringValue());
     assertEquals("\\8", createLiteralFromText("'\\8'").getStringValue());
   }
+
+  private List<String> getCharacterRanges(String text) {
+    final PyStringLiteralExpression expr = createLiteralFromText(text);
+    assertNotNull(expr);
+    final List<String> characters = new ArrayList<String>();
+    for (Pair<TextRange, String> fragment : expr.getDecodedFragments()) {
+      characters.add(fragment.getSecond());
+    }
+    return characters;
+  }
 }
diff --git a/python/testSrc/com/jetbrains/python/PySurroundWithTest.java b/python/testSrc/com/jetbrains/python/PySurroundWithTest.java
index b2a1292..5f49581 100644
--- a/python/testSrc/com/jetbrains/python/PySurroundWithTest.java
+++ b/python/testSrc/com/jetbrains/python/PySurroundWithTest.java
@@ -35,7 +35,7 @@
     doTest(new PyWithWhileSurrounder());
   }
 
-  public void _testSurroundWithTryExcept() throws Exception {
+  public void testSurroundWithTryExcept() throws Exception {
     doTest(new PyWithTryExceptSurrounder());
   }
 
diff --git a/python/testSrc/com/jetbrains/python/PythonCompletionTest.java b/python/testSrc/com/jetbrains/python/PythonCompletionTest.java
index 4f93cca..da7888e 100644
--- a/python/testSrc/com/jetbrains/python/PythonCompletionTest.java
+++ b/python/testSrc/com/jetbrains/python/PythonCompletionTest.java
@@ -15,9 +15,12 @@
  */
 package com.jetbrains.python;
 
+import com.google.common.collect.Lists;
 import com.intellij.codeInsight.completion.impl.CamelHumpMatcher;
+import com.intellij.codeInsight.lookup.AutoCompletionPolicy;
 import com.intellij.codeInsight.lookup.Lookup;
 import com.intellij.codeInsight.lookup.LookupElement;
+import com.intellij.codeInsight.lookup.LookupElementBuilder;
 import com.jetbrains.python.documentation.DocStringFormat;
 import com.jetbrains.python.documentation.PyDocumentationSettings;
 import com.jetbrains.python.fixtures.PyTestCase;
@@ -387,8 +390,10 @@
     final PyDocumentationSettings settings = PyDocumentationSettings.getInstance(myFixture.getModule());
     settings.setFormat(DocStringFormat.PLAIN);
     myFixture.configureByFile("completion/identifiersInPlainDocstring.py");
-    myFixture.completeBasic();
-    myFixture.checkResultByFile("completion/identifiersInPlainDocstring.after.py");
+    final LookupElement[] elements = myFixture.completeBasic();
+    assertNotNull(elements);
+    assertContainsElements(Lists.newArrayList(elements),
+                           LookupElementBuilder.create("bar").withAutoCompletionPolicy(AutoCompletionPolicy.NEVER_AUTOCOMPLETE));
   }
 
   public void testPep328Completion() {  // PY-3409
diff --git a/python/testSrc/com/jetbrains/python/PythonParsingTest.java b/python/testSrc/com/jetbrains/python/PythonParsingTest.java
index 669ac3d..9f612a2 100644
--- a/python/testSrc/com/jetbrains/python/PythonParsingTest.java
+++ b/python/testSrc/com/jetbrains/python/PythonParsingTest.java
@@ -430,6 +430,14 @@
     doTest();
   }
 
+  public void testNotClosedBraceDict() {
+    doTest();
+  }
+
+  public void testNotClosedBraceSet() {
+    doTest(LanguageLevel.PYTHON33);
+  }
+
   public void doTest(LanguageLevel languageLevel) {
     LanguageLevel prev = myLanguageLevel;
     myLanguageLevel = languageLevel;
diff --git a/python/testSrc/com/jetbrains/python/inspections/PyMethodMayBeStaticInspectionTest.java b/python/testSrc/com/jetbrains/python/inspections/PyMethodMayBeStaticInspectionTest.java
index ea40830d..885f043 100644
--- a/python/testSrc/com/jetbrains/python/inspections/PyMethodMayBeStaticInspectionTest.java
+++ b/python/testSrc/com/jetbrains/python/inspections/PyMethodMayBeStaticInspectionTest.java
@@ -15,6 +15,7 @@
  */
 package com.jetbrains.python.inspections;
 
+import com.intellij.testFramework.TestDataPath;
 import com.jetbrains.python.PythonTestUtil;
 import com.jetbrains.python.fixtures.PyTestCase;
 
@@ -23,6 +24,7 @@
 /**
  * User: ktisha
  */
+@TestDataPath("$CONTENT_ROOT/../testData/inspections/PyMethodMayBeStaticInspection/")
 public class PyMethodMayBeStaticInspectionTest extends PyTestCase {
 
   public void testTruePositive() {
@@ -65,6 +67,10 @@
     doTest();
   }
 
+  public void testDecorated() {
+    doTest();
+  }
+
   public void testOverwrittenMethod() {
     doTest();
   }
diff --git a/python/testSrc/com/jetbrains/python/quickFixes/PyMakeMethodStaticQuickFixTest.java b/python/testSrc/com/jetbrains/python/quickFixes/PyMakeMethodStaticQuickFixTest.java
index 310c211..835e6ed 100644
--- a/python/testSrc/com/jetbrains/python/quickFixes/PyMakeMethodStaticQuickFixTest.java
+++ b/python/testSrc/com/jetbrains/python/quickFixes/PyMakeMethodStaticQuickFixTest.java
@@ -36,14 +36,6 @@
     doQuickFixTest(PyMethodMayBeStaticInspection.class, PyBundle.message("QFIX.NAME.make.static"));
   }
 
-  public void testFunctionWithDeco() {
-    doQuickFixTest(PyMethodMayBeStaticInspection.class, PyBundle.message("QFIX.NAME.make.static"));
-  }
-
-  public void testDecoWithParams() {
-    doQuickFixTest(PyMethodMayBeStaticInspection.class, PyBundle.message("QFIX.NAME.make.static"));
-  }
-
   public void testNoSelf() {
     doQuickFixTest(PyMethodMayBeStaticInspection.class, PyBundle.message("QFIX.NAME.make.static"));
   }
diff --git a/resources-en/src/inspectionDescriptions/CanBeFinal.html b/resources-en/src/inspectionDescriptions/CanBeFinal.html
index d293049..8caa553 100644
--- a/resources-en/src/inspectionDescriptions/CanBeFinal.html
+++ b/resources-en/src/inspectionDescriptions/CanBeFinal.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">This inspection reports all fields, methods or classes, found in the specified inspection
 scope, that may have a <b><font color="#000080">final</font></b> modifier added to their declarations.<br><br>
+<!-- tooltip end -->
 Use check boxes in the inspection options below, to define which declarations are to be reported.</font>
 </body>
 </html>
diff --git a/resources-en/src/inspectionDescriptions/Dependency.html b/resources-en/src/inspectionDescriptions/Dependency.html
index 387aeea..706c0e1 100644
--- a/resources-en/src/inspectionDescriptions/Dependency.html
+++ b/resources-en/src/inspectionDescriptions/Dependency.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">
 This inspection detects violations of rules specified for dependency validation.<br><br>
+<!-- tooltip end -->
 Use the "Configure dependency rules" button below to customize validation rules.
 </font>
 </body>
diff --git a/resources-en/src/inspectionDescriptions/EmptyMethod.html b/resources-en/src/inspectionDescriptions/EmptyMethod.html
index a8077ff..636fa4e 100644
--- a/resources-en/src/inspectionDescriptions/EmptyMethod.html
+++ b/resources-en/src/inspectionDescriptions/EmptyMethod.html
@@ -8,8 +8,9 @@
 call and passing its own parameter is also considered empty.
 <br><br>
 This inspection is automatically suppressed for methods annotated with special annotations,
-for example, EJB annotations javax.ejb.Init and javax.ejb.Remove. Additional annotations
-can be configured below.
+for example, EJB annotations javax.ejb.Init and javax.ejb.Remove.
+<!-- tooltip end -->
+Additional annotations can be configured below.
 </font>
 </body>
 </html>
diff --git a/resources-en/src/inspectionDescriptions/JavaDoc.html b/resources-en/src/inspectionDescriptions/JavaDoc.html
index e042b7d..e364c43 100644
--- a/resources-en/src/inspectionDescriptions/JavaDoc.html
+++ b/resources-en/src/inspectionDescriptions/JavaDoc.html
@@ -5,6 +5,7 @@
 &nbsp;- required tag is missing<br>
 &nbsp;- invalid or incomplete tag<br>
 &nbsp;- javadoc description is missing or incomplete<br><br>
+<!-- tooltip end -->
 Use tabs and corresponding inspection options below, to define visibility scope where javadoc is required, as well as the
 required javadoc tags for classes, methods, fields and inner classes.</font>
 </body>
diff --git a/resources-en/src/inspectionDescriptions/Local_CustomHtmlAttributes.html b/resources-en/src/inspectionDescriptions/Local_CustomHtmlAttributes.html
index df86302..42b845b 100644
--- a/resources-en/src/inspectionDescriptions/Local_CustomHtmlAttributes.html
+++ b/resources-en/src/inspectionDescriptions/Local_CustomHtmlAttributes.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">Shows custom html attributes in html or jsp.<br>
 <br>
+<!-- tooltip end -->
 Use options below to add attributes to known custom attributes list.</font>
 </body>
 </html>
\ No newline at end of file
diff --git a/resources-en/src/inspectionDescriptions/Local_CustomHtmlTags.html b/resources-en/src/inspectionDescriptions/Local_CustomHtmlTags.html
index ebe99ce..595cdf3 100644
--- a/resources-en/src/inspectionDescriptions/Local_CustomHtmlTags.html
+++ b/resources-en/src/inspectionDescriptions/Local_CustomHtmlTags.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">Shows custom html tags in html or jsp.<br>
 <br>
+<!-- tooltip end -->
 Use options below to add tags to known custom tags list.</font>
 </body>
 </html>
\ No newline at end of file
diff --git a/resources-en/src/inspectionDescriptions/Local_NotRequiredHtmlAttributes.html b/resources-en/src/inspectionDescriptions/Local_NotRequiredHtmlAttributes.html
index 0637e65..4b4b6b4 100644
--- a/resources-en/src/inspectionDescriptions/Local_NotRequiredHtmlAttributes.html
+++ b/resources-en/src/inspectionDescriptions/Local_NotRequiredHtmlAttributes.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">Shows not required html attributes in html or jsp.<br>
 <br>
+<!-- tooltip end -->
 Use options below to add attributes to not required attributes list.</font>
 </body>
 </html>
\ No newline at end of file
diff --git a/resources-en/src/inspectionDescriptions/UNUSED_SYMBOL.html b/resources-en/src/inspectionDescriptions/UNUSED_SYMBOL.html
index 6197860..b6a8b50 100644
--- a/resources-en/src/inspectionDescriptions/UNUSED_SYMBOL.html
+++ b/resources-en/src/inspectionDescriptions/UNUSED_SYMBOL.html
@@ -4,6 +4,7 @@
 Detects local variables and private members that are declared but not used,
 never accessed for reading or not initialized in a class.
 <br>Can ignore members that are annotated in a special way, for example, by EJB annotation javax.ejb.EJB.
+<!-- tooltip end -->
 Additional annotations can be configured below.
 <br>
   The <b>Report unused parameters in non-private method</b> setting is used to
diff --git a/resources-en/src/inspectionDescriptions/UnusedDeclaration.html b/resources-en/src/inspectionDescriptions/UnusedDeclaration.html
index f2204d0b..07da616 100644
--- a/resources-en/src/inspectionDescriptions/UnusedDeclaration.html
+++ b/resources-en/src/inspectionDescriptions/UnusedDeclaration.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">This inspection reports classes, methods or fields in the specified inspection scope that
 are not used or not reachable from entry points.<br><br>
+<!-- tooltip end -->
 Use check boxes in the inspection options below, to specify what should be automatically assumed entry points. You will
 also have a possibility to add entry points manually when inspection results are ready.</font>
 </body>
diff --git a/resources-en/src/inspectionDescriptions/WeakerAccess.html b/resources-en/src/inspectionDescriptions/WeakerAccess.html
index 55b124d..190d360 100644
--- a/resources-en/src/inspectionDescriptions/WeakerAccess.html
+++ b/resources-en/src/inspectionDescriptions/WeakerAccess.html
@@ -2,6 +2,7 @@
 <body>
 <font face="verdana" size="-1">This inspection reports all fields, methods or classes, found in the specified inspection
 scope, that may have their access modifier narrowed down.<br><br>
+<!-- tooltip end -->
 Use check boxes in the inspection options below, to define rules for the modifier change suggestions.</font>
 </body>
 </html>
diff --git a/resources-en/src/messages/AntBundle.properties b/resources-en/src/messages/AntBundle.properties
index c2b2b2b..80d351f7 100644
--- a/resources-en/src/messages/AntBundle.properties
+++ b/resources-en/src/messages/AntBundle.properties
@@ -33,10 +33,10 @@
 build.finished.status.ant.build.completed.successfully=Ant build completed successfully in {0} at {1}
 #0 - warnings count, 1 - formatted execution time as string (i.e. 2h 35m 29s), 2 - finish date (as string)
 build.finished.status.ant.build.completed.with.warnings=Ant build completed with \
-  {0, choice, 1#one warning|2#{0} warnings} in {1} at {2}
+  {0, choice, 0#no warnings|1#one warning|2#{0} warnings} in {1} at {2}
 #0 - errors count, 1 - warnings count, 2 - formatted execution time as string (i.e. 2h 35m 29s), 3 - finish date (as string)
 build.finished.status.ant.build.completed.with.errors.warnings=Ant build completed with \
-  {0, choice, 1#one error|2#{0} errors} {1, choice, 1#one warning|2#{0} warnings} \
+  {0, choice, 0#no errors|1#one error|2#{0} errors} and {1, choice, 0#no warnings|1#one warning|2#{1} warnings} \
    in {2} at {3}
 project.jdk.not.specified.error.message=Project JDK not specified
 jdk.with.name.not.configured.error.message=JDK ({0}) needed to run this ANT target is not configured. Please update your settings in the Project | Libraries menu.
diff --git a/resources-en/src/tips/AltInsertInEditor.html b/resources-en/src/tips/AltInsertInEditor.html
index a50b0ab..f73f02e 100644
--- a/resources-en/src/tips/AltInsertInEditor.html
+++ b/resources-en/src/tips/AltInsertInEditor.html
@@ -7,7 +7,7 @@
 
     <p>Using <span class="shortcut">&shortcut:Generate;</span> (<span class="control">Code | Generate</span>)
       in the editor, you may easily generate getter and setter methods for any fields of your class.</p>
-      <p class="image"><img src="images/alt_insert_in_editor.gif"></p>
+      <p class="image"><img src="images/alt_insert_in_editor.png"></p>
 
 
 
diff --git a/resources-en/src/tips/BreakpointSpeedmenu.html b/resources-en/src/tips/BreakpointSpeedmenu.html
index 49c1043..7afc19d 100644
--- a/resources-en/src/tips/BreakpointSpeedmenu.html
+++ b/resources-en/src/tips/BreakpointSpeedmenu.html
@@ -7,6 +7,6 @@
         Right-clicking on a breakpoint marker (on the bar to the left from the text) invokes the speedmenu where
         you can quickly enable/disable the breakpoint or adjust its properties.</p>
     <p class="image">
-        <img src="images/breakpoint_speedmenu.gif"></p>
+        <img src="images/breakpoint_speedmenu.png"></p>
 </body>
 </html>
diff --git a/resources-en/src/tips/CompleteMethod.html b/resources-en/src/tips/CompleteMethod.html
index c42ace4..4569298 100644
--- a/resources-en/src/tips/CompleteMethod.html
+++ b/resources-en/src/tips/CompleteMethod.html
@@ -9,7 +9,7 @@
       <p>You can create code constructs using statement completion. Start typing a method declaration or a statement, and
         press <span class="shortcut">&shortcut:EditorChooseLookupItemCompleteStatement;</span> after the opening parenthesis. The braces are created,
         with the caret placed inside:
-        <p class="image"><img src="images/complete_statement.gif" alt="img"></p>
+        <p class="image"><img src="images/complete_statement.png"></p>
 
 
 
diff --git a/resources-en/src/tips/CompleteStatement.html b/resources-en/src/tips/CompleteStatement.html
index cc7fed4..edd195e 100644
--- a/resources-en/src/tips/CompleteStatement.html
+++ b/resources-en/src/tips/CompleteStatement.html
@@ -11,7 +11,7 @@
       <span class="code_emphasis">try-catch</span>,
       <span class="code_emphasis">return</span>
       (or a method call) into a syntactically correct construct (e.g. add curly braces).</p>
-      <p class="image"><img src="images/complete_statement.gif"></p>
+      <p class="image"><img src="images/complete_statement.png"></p>
 
 
 
diff --git a/resources-en/src/tips/ConfiguringTerminal.html b/resources-en/src/tips/ConfiguringTerminal.html
new file mode 100644
index 0000000..81f4155
--- /dev/null
+++ b/resources-en/src/tips/ConfiguringTerminal.html
@@ -0,0 +1,15 @@
+<html>
+<head>
+    <link rel="stylesheet" type="text/css" href="css/tips.css">
+</head>
+<body>
+
+
+    <p>For the embedded local terminal, you can define your favorite shell, 
+default tab name, and other settings. 
+Choose 
+<span class="control">File | Settings</span> on the main menu, 
+and then open the page <span class="control">Terminal</span>. </p>
+
+</body>
+</html>
diff --git a/resources-en/src/tips/CopyPasteReference.html b/resources-en/src/tips/CopyPasteReference.html
index e4bf220..58d2ba3 100644
--- a/resources-en/src/tips/CopyPasteReference.html
+++ b/resources-en/src/tips/CopyPasteReference.html
@@ -10,7 +10,7 @@
       <p>For example, go to the <span class="code_emphasis">java.util.Collections</span> JDK class, place the cursor within the <span class="code_emphasis">EMPTY-MAP</span> field
         and press <span class="shortcut">&shortcut:CopyReference;</span>:</p>
       <p class="image"><img src="images/reference_copied.png"></p>
-      <p>Then return to your Java source and press <span class="shortcut">&shortcut:$Paste;</span>:</p>
+      <p>Then return to your source code and press <span class="shortcut">&shortcut:$Paste;</span>:</p>
       <p class="image"><img src="images/reference_pasted.png"></p>
       <p>You can also copy references in the <span class="control">GotoClass/GotoSymbol/GotoFile</span> dialogs.
     Just press <span class="shortcut">&shortcut:$Copy;</span> on any element in the lookup list.</p>
diff --git a/resources-en/src/tips/CreatePropertyTag.html b/resources-en/src/tips/CreatePropertyTag.html
index 0f89c60..624df5e 100644
--- a/resources-en/src/tips/CreatePropertyTag.html
+++ b/resources-en/src/tips/CreatePropertyTag.html
@@ -8,7 +8,7 @@
     <p>You can start referring to an Ant property or target even if it is not defined yet. An intention action feature
       will suggest you to automatically create the necessary tag, without the need for you to leave your current
       editing location.</p>
-      <p class="image"><img src="images/ant_property_intention.gif"></p>
+      <p class="image"><img src="images/ant_property_intention.png"></p>
 
 
 
diff --git a/resources-en/src/tips/CreateTargetTag.html b/resources-en/src/tips/CreateTargetTag.html
index d54c844..54e1c42 100644
--- a/resources-en/src/tips/CreateTargetTag.html
+++ b/resources-en/src/tips/CreateTargetTag.html
@@ -7,7 +7,7 @@
 
     <p>Refer to a non-existing target tag in your Ant build file, and IntelliJ IDEA will suggest you to automatically create the
       corresponding tag. This intention action will not even make you change your current editing location.</p>
-      <p class="image"><img src="images/ant_target_intention.gif"></p>
+      <p class="image"><img src="images/ant_target_intention.png"></p>
 
 
 
diff --git a/resources-en/src/tips/HierarchyBrowser.html b/resources-en/src/tips/HierarchyBrowser.html
index fa987ec..39ffec5 100644
--- a/resources-en/src/tips/HierarchyBrowser.html
+++ b/resources-en/src/tips/HierarchyBrowser.html
@@ -8,7 +8,7 @@
     <p>To see the inheritance hierarchy for a selected class, press <span class="shortcut">&shortcut:TypeHierarchy;</span>
       (<span class="control">View | Type Hierarchy</span>).
       You can also invoke the hierarchy view right from the editor to see the hierarchy for the currently edited class.</p>
-      <p class="image"><img src="images/hierarchy_browser.gif"></p>
+      <p class="image"><img src="images/hierarchy_browser.png"></p>
 
 
 
diff --git a/resources-en/src/tips/HighlightThrows.html b/resources-en/src/tips/HighlightThrows.html
index 29ddba1..a6d8468 100644
--- a/resources-en/src/tips/HighlightThrows.html
+++ b/resources-en/src/tips/HighlightThrows.html
@@ -11,7 +11,7 @@
           press <span class="shortcut">&shortcut:HighlightUsagesInFile;</span> and select the desired exception class from the list.
 This will also work for <span class="code_emphasis">try</span> and <span class="code_emphasis">catch</span>.
  </p>
-        <p class="image"><img src="images/highlightExceptions.gif"></p>
+        <p class="image"><img src="images/highlightExceptions.png"></p>
 
 
 
diff --git a/resources-en/src/tips/InsertLiveTemplate.html b/resources-en/src/tips/InsertLiveTemplate.html
index 6448c25..a8c080d 100644
--- a/resources-en/src/tips/InsertLiveTemplate.html
+++ b/resources-en/src/tips/InsertLiveTemplate.html
@@ -10,6 +10,6 @@
         press  <span class="shortcut">&shortcut:InsertLiveTemplate;</span>
         to see what happens.</p>
     <p class="image">
-        <img src="images/insert_live_template.gif"></p>
+        <img src="images/insert_live_template.png"></p>
 </body>
 </html>
diff --git a/resources-en/src/tips/IntroduceVariableIncompleteCode.html b/resources-en/src/tips/IntroduceVariableIncompleteCode.html
index 470358a..352b24a 100644
--- a/resources-en/src/tips/IntroduceVariableIncompleteCode.html
+++ b/resources-en/src/tips/IntroduceVariableIncompleteCode.html
@@ -9,7 +9,7 @@
         You can use the <span class="">Extract Variable</span>
         refactoring even on incomplete statements.
         Just select the necessary block in the editor and press <span class="shortcut">&shortcut:IntroduceVariable;</span>.</p>
-      <p class="image"><img src="images/introduce_variable_incomplete.gif"></p>
+      <p class="image"><img src="images/extract_variable_incomplete.png"></p>
 
 
 
diff --git a/resources-en/src/tips/LiveTemplates.html b/resources-en/src/tips/LiveTemplates.html
index b753bc6..e59849b 100644
--- a/resources-en/src/tips/LiveTemplates.html
+++ b/resources-en/src/tips/LiveTemplates.html
@@ -8,11 +8,11 @@
     <h1>Try Live Templates</h1>
       <p>Live Templates
       allow you to generate many typical code constructs in seconds! For example, type</p>
-      <p class="image"><img src="images/live_templates_1.gif"></p>
+      <p class="image"><img src="images/live_templates_1.png"></p>
 
       <p>in a method and press the <span class="shortcut">Tab</span>
       key to see what happens.</p>
-      <p class="image"><img src="images/live_templates_2.gif"></p>
+      <p class="image"><img src="images/live_templates_2.png"></p>
 
       <p>Use the <span class="shortcut">Tab</span> key to move between the template fields.
       See <span class="control">File | Settings | Live Templates</span>
diff --git a/resources-en/src/tips/MoveInnerToUpper.html b/resources-en/src/tips/MoveInnerToUpper.html
index ea3e496..968cc11 100644
--- a/resources-en/src/tips/MoveInnerToUpper.html
+++ b/resources-en/src/tips/MoveInnerToUpper.html
@@ -9,7 +9,7 @@
       refactoring (<span class="shortcut">&shortcut:Move;</span>) on an inner class that is declared
       <span class="code_emphasis">static</span>,
       you are provided with an option to either make it a top-level class, or move it to another class.</p>
-      <p class="image"><img src="images/move_inner.gif"></p>
+      <p class="image"><img src="images/move_inner.png"></p>
 
 
 
diff --git a/resources-en/src/tips/PropertiesCompletion.html b/resources-en/src/tips/PropertiesCompletion.html
index 47eafbfa..38bf67d 100644
--- a/resources-en/src/tips/PropertiesCompletion.html
+++ b/resources-en/src/tips/PropertiesCompletion.html
@@ -8,6 +8,6 @@
         (<span class="shortcut">&shortcut:CodeCompletion;</span>) within Java String literals and in other file types,
         for completing <span class="code_emphasis">.properties</span> keys.</p>
     <p class="image">
-        <img src="images/properties_completion.gif"></p>
+        <img src="images/properties_completion.png"></p>
 </body>
 </html>
diff --git a/resources-en/src/tips/SmartTypeAfterNew.html b/resources-en/src/tips/SmartTypeAfterNew.html
index a650f96..cf69a0d 100644
--- a/resources-en/src/tips/SmartTypeAfterNew.html
+++ b/resources-en/src/tips/SmartTypeAfterNew.html
@@ -8,9 +8,9 @@
     <p>The SmartType code completion may be used after the
       <span class="code_keyword">new</span> keyword,
       to instantiate an object of the expected type. For example, type</p>
-      <p class="image"><img src="images/smart_type_after_new_1.gif"></p>
+      <p class="image"><img src="images/smart_type_after_new_1.png"></p>
       <p>and press <span class="shortcut">&shortcut:SmartTypeCompletion;</span>:</p>
-      <p class="image"><img src="images/smart_type_after_new_2.gif"></p>
+      <p class="image"><img src="images/smart_type_after_new_2.png"></p>
 
 
 
diff --git a/resources-en/src/tips/SmartTypeCompletion.html b/resources-en/src/tips/SmartTypeCompletion.html
index bbc4db5..488d363 100644
--- a/resources-en/src/tips/SmartTypeCompletion.html
+++ b/resources-en/src/tips/SmartTypeCompletion.html
@@ -8,9 +8,9 @@
     <p>The SmartType code completion greatly helps to find methods and variables that are suitable in the current context,
       by analyzing the expected type of the whole expression. So doing, <span class="product">IntelliJ IDEA</span> pinpoints the top
         five most suitable results and highlights them on the green background. For example, type</p>
-      <p class="image"><img src="images/smart_type_completion_1.gif"></p>
+      <p class="image"><img src="images/smart_type_completion_1.png"></p>
       <p>and press <span class="shortcut">&shortcut:SmartTypeCompletion;</span>:</p>
-      <p class="image"><img src="images/smart_type_completion_2.gif"></p>
+      <p class="image"><img src="images/smart_type_completion_2.png"></p>
       <p>The SmartType completion also works after the
       <span class="code"><span class="keyword">return</span></span> keyword,
       in an assignment, in an argument list of a method call and other places.</p>
diff --git a/resources-en/src/tips/SurroundWith.html b/resources-en/src/tips/SurroundWith.html
index eb71b46..4de4f2b 100644
--- a/resources-en/src/tips/SurroundWith.html
+++ b/resources-en/src/tips/SurroundWith.html
@@ -12,7 +12,7 @@
       <span class="control">Code</span> tab of
       <span class="control">File | Settings | File Templates</span>.</p>
       <p>Use other items in the list to surround with other constructs.</p>
-      <p class="image"><img src="images/surround_with.gif"></p>
+      <p class="image"><img src="images/surround_with.png"></p>
 
 
 
diff --git a/resources-en/src/tips/Terminal.html b/resources-en/src/tips/Terminal.html
new file mode 100644
index 0000000..84957c7
--- /dev/null
+++ b/resources-en/src/tips/Terminal.html
@@ -0,0 +1,14 @@
+<html>
+<head>
+    <link rel="stylesheet" type="text/css" href="css/tips.css">
+</head>
+<body>
+
+
+    <p>You don't need to leave WebStorm to work with your favorite shell. Just choose 
+<span class="control">Tools | Open Terminal</span> on the main menu, 
+and enjoy using the embedded local terminal. </p>
+    <p class="image"><img src="images/terminal.png"></p>
+
+</body>
+</html>
diff --git a/resources-en/src/tips/VariableNameCompletion.html b/resources-en/src/tips/VariableNameCompletion.html
index 7002630..03082ed 100644
--- a/resources-en/src/tips/VariableNameCompletion.html
+++ b/resources-en/src/tips/VariableNameCompletion.html
@@ -11,7 +11,7 @@
     <p>
         and press <span class="shortcut">&shortcut:CodeCompletion;</span>.</p>
     <p class="image">
-        <img src="images/variable_name_completion.gif"></p>
+        <img src="images/variable_name_completion.png"></p>
     <p>
         You can customize name prefixes for local variables, parameters, instance and static fields in
         <span class="control">File | Settings | Code Style</span>.</p>
diff --git a/resources-en/src/tips/WideScreen.html b/resources-en/src/tips/WideScreen.html
new file mode 100644
index 0000000..ee5c16c
--- /dev/null
+++ b/resources-en/src/tips/WideScreen.html
@@ -0,0 +1,16 @@
+<html>
+<head>
+    <link rel="stylesheet" type="text/css" href="css/tips.css">
+</head>
+<body>
+
+
+<p>Tune the <span class="product">&productName;</span> tool windows layout to make better use of your screen.</p>
+<p>Toggle between the vertical and side-by-side placement of the tool windows by 
+Ctrl+click/Cmd+Click on the splitter:</p>    
+
+
+<p class="image"><img src="images/sidebyside.png"></p>
+
+</body>
+</html>
\ No newline at end of file
diff --git a/resources-en/src/tips/images/alt_insert_in_editor.gif b/resources-en/src/tips/images/alt_insert_in_editor.gif
deleted file mode 100644
index 5652971..0000000
--- a/resources-en/src/tips/images/alt_insert_in_editor.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/alt_insert_in_editor.png b/resources-en/src/tips/images/alt_insert_in_editor.png
new file mode 100644
index 0000000..e872be2
--- /dev/null
+++ b/resources-en/src/tips/images/alt_insert_in_editor.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..c89906f
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/alt_insert_in_editor@2x_dark.png b/resources-en/src/tips/images/alt_insert_in_editor@2x_dark.png
new file mode 100644
index 0000000..564f590
--- /dev/null
+++ b/resources-en/src/tips/images/alt_insert_in_editor@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/alt_insert_in_editor_dark.png b/resources-en/src/tips/images/alt_insert_in_editor_dark.png
new file mode 100644
index 0000000..0e9614f
--- /dev/null
+++ b/resources-en/src/tips/images/alt_insert_in_editor_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/ant_property_intention.gif b/resources-en/src/tips/images/ant_property_intention.gif
deleted file mode 100644
index a7dfe21..0000000
--- a/resources-en/src/tips/images/ant_property_intention.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/ant_property_intention.png b/resources-en/src/tips/images/ant_property_intention.png
new file mode 100644
index 0000000..b61675b
--- /dev/null
+++ b/resources-en/src/tips/images/ant_property_intention.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..9aead4e
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/ant_property_intention@2x_dark.png b/resources-en/src/tips/images/ant_property_intention@2x_dark.png
new file mode 100644
index 0000000..957435b
--- /dev/null
+++ b/resources-en/src/tips/images/ant_property_intention@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/ant_property_intention_dark.png b/resources-en/src/tips/images/ant_property_intention_dark.png
new file mode 100644
index 0000000..508abc3
--- /dev/null
+++ b/resources-en/src/tips/images/ant_property_intention_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/ant_target_intention.gif b/resources-en/src/tips/images/ant_target_intention.gif
deleted file mode 100644
index af5f44c..0000000
--- a/resources-en/src/tips/images/ant_target_intention.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/ant_target_intention.png b/resources-en/src/tips/images/ant_target_intention.png
new file mode 100644
index 0000000..ed15362
--- /dev/null
+++ b/resources-en/src/tips/images/ant_target_intention.png
Binary files differ
diff --git a/resources-en/src/tips/images/bookmarks1.png b/resources-en/src/tips/images/bookmarks1.png
index 828781c..33c17f4 100644
--- a/resources-en/src/tips/images/bookmarks1.png
+++ b/resources-en/src/tips/images/bookmarks1.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..07bd529
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/bookmarks1@2x_dark.png b/resources-en/src/tips/images/bookmarks1@2x_dark.png
new file mode 100644
index 0000000..a742952
--- /dev/null
+++ b/resources-en/src/tips/images/bookmarks1@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/bookmarks1_dark.png b/resources-en/src/tips/images/bookmarks1_dark.png
new file mode 100644
index 0000000..adf59ee
--- /dev/null
+++ b/resources-en/src/tips/images/bookmarks1_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/breakpoint_speedmenu.gif b/resources-en/src/tips/images/breakpoint_speedmenu.gif
deleted file mode 100644
index e9fef28..0000000
--- a/resources-en/src/tips/images/breakpoint_speedmenu.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/breakpoint_speedmenu.png b/resources-en/src/tips/images/breakpoint_speedmenu.png
new file mode 100644
index 0000000..2fddeea
--- /dev/null
+++ b/resources-en/src/tips/images/breakpoint_speedmenu.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..56e183d
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/breakpoint_speedmenu@2x_dark.png b/resources-en/src/tips/images/breakpoint_speedmenu@2x_dark.png
new file mode 100644
index 0000000..0b11982
--- /dev/null
+++ b/resources-en/src/tips/images/breakpoint_speedmenu@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/breakpoint_speedmenu_dark.png b/resources-en/src/tips/images/breakpoint_speedmenu_dark.png
new file mode 100644
index 0000000..cfa1e72e
--- /dev/null
+++ b/resources-en/src/tips/images/breakpoint_speedmenu_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/complete_statement.gif b/resources-en/src/tips/images/complete_statement.gif
deleted file mode 100644
index 83cfd51..0000000
--- a/resources-en/src/tips/images/complete_statement.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/complete_statement.png b/resources-en/src/tips/images/complete_statement.png
new file mode 100644
index 0000000..d0b55f9
--- /dev/null
+++ b/resources-en/src/tips/images/complete_statement.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..d5f5a9c
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/complete_statement@2x_dark.png b/resources-en/src/tips/images/complete_statement@2x_dark.png
new file mode 100644
index 0000000..f989cd0
--- /dev/null
+++ b/resources-en/src/tips/images/complete_statement@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/complete_statement_dark.png b/resources-en/src/tips/images/complete_statement_dark.png
new file mode 100644
index 0000000..747a012
--- /dev/null
+++ b/resources-en/src/tips/images/complete_statement_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/createTest.png b/resources-en/src/tips/images/createTest.png
index 55c6ea8..ed16a5b 100644
--- a/resources-en/src/tips/images/createTest.png
+++ b/resources-en/src/tips/images/createTest.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..a999418
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/createTest@2x_dark.png b/resources-en/src/tips/images/createTest@2x_dark.png
new file mode 100644
index 0000000..bd68fac
--- /dev/null
+++ b/resources-en/src/tips/images/createTest@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/createTest_dark.png b/resources-en/src/tips/images/createTest_dark.png
new file mode 100644
index 0000000..51d641c
--- /dev/null
+++ b/resources-en/src/tips/images/createTest_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/extract_variable_incomplete.png b/resources-en/src/tips/images/extract_variable_incomplete.png
new file mode 100644
index 0000000..7790f58
--- /dev/null
+++ b/resources-en/src/tips/images/extract_variable_incomplete.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..5433992
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/extract_variable_incomplete@2x_dark.png b/resources-en/src/tips/images/extract_variable_incomplete@2x_dark.png
new file mode 100644
index 0000000..bb18c0c
--- /dev/null
+++ b/resources-en/src/tips/images/extract_variable_incomplete@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/extract_variable_incomplete_dark.png b/resources-en/src/tips/images/extract_variable_incomplete_dark.png
new file mode 100644
index 0000000..bc3a10c
--- /dev/null
+++ b/resources-en/src/tips/images/extract_variable_incomplete_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/hierarchy_browser.gif b/resources-en/src/tips/images/hierarchy_browser.gif
deleted file mode 100644
index 12cd665..0000000
--- a/resources-en/src/tips/images/hierarchy_browser.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/hierarchy_browser.png b/resources-en/src/tips/images/hierarchy_browser.png
new file mode 100644
index 0000000..9c7b525
--- /dev/null
+++ b/resources-en/src/tips/images/hierarchy_browser.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..6825ed6
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/hierarchy_browser@2x_dark.png b/resources-en/src/tips/images/hierarchy_browser@2x_dark.png
new file mode 100644
index 0000000..8a19426
--- /dev/null
+++ b/resources-en/src/tips/images/hierarchy_browser@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/hierarchy_browser_dark.png b/resources-en/src/tips/images/hierarchy_browser_dark.png
new file mode 100644
index 0000000..92c4180
--- /dev/null
+++ b/resources-en/src/tips/images/hierarchy_browser_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/highlightExceptions.gif b/resources-en/src/tips/images/highlightExceptions.gif
deleted file mode 100644
index 51f3f2c..0000000
--- a/resources-en/src/tips/images/highlightExceptions.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/highlightExceptions.png b/resources-en/src/tips/images/highlightExceptions.png
new file mode 100644
index 0000000..3e98765
--- /dev/null
+++ b/resources-en/src/tips/images/highlightExceptions.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..1c27cdb
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/highlightExceptions@2x_dark.png b/resources-en/src/tips/images/highlightExceptions@2x_dark.png
new file mode 100644
index 0000000..0fe1134
--- /dev/null
+++ b/resources-en/src/tips/images/highlightExceptions@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/highlightExceptions_dark.png b/resources-en/src/tips/images/highlightExceptions_dark.png
new file mode 100644
index 0000000..2f3094d
--- /dev/null
+++ b/resources-en/src/tips/images/highlightExceptions_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/insert_live_template.gif b/resources-en/src/tips/images/insert_live_template.gif
deleted file mode 100644
index be038e6..0000000
--- a/resources-en/src/tips/images/insert_live_template.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/insert_live_template.png b/resources-en/src/tips/images/insert_live_template.png
new file mode 100644
index 0000000..8c7b6be
--- /dev/null
+++ b/resources-en/src/tips/images/insert_live_template.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..49275a4
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/insert_live_template@2x_dark.png b/resources-en/src/tips/images/insert_live_template@2x_dark.png
new file mode 100644
index 0000000..dede099
--- /dev/null
+++ b/resources-en/src/tips/images/insert_live_template@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/insert_live_template_dark.png b/resources-en/src/tips/images/insert_live_template_dark.png
new file mode 100644
index 0000000..a4310ac
--- /dev/null
+++ b/resources-en/src/tips/images/insert_live_template_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/introduce_variable_incomplete.gif b/resources-en/src/tips/images/introduce_variable_incomplete.gif
deleted file mode 100644
index ce46df9..0000000
--- a/resources-en/src/tips/images/introduce_variable_incomplete.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_1.gif b/resources-en/src/tips/images/live_templates_1.gif
deleted file mode 100644
index 73c56d8..0000000
--- a/resources-en/src/tips/images/live_templates_1.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_1.png b/resources-en/src/tips/images/live_templates_1.png
new file mode 100644
index 0000000..3b484ca
--- /dev/null
+++ b/resources-en/src/tips/images/live_templates_1.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..090f38a
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_1@2x_dark.png b/resources-en/src/tips/images/live_templates_1@2x_dark.png
new file mode 100644
index 0000000..5912b23
--- /dev/null
+++ b/resources-en/src/tips/images/live_templates_1@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_1_dark.png b/resources-en/src/tips/images/live_templates_1_dark.png
new file mode 100644
index 0000000..4b1ee58
--- /dev/null
+++ b/resources-en/src/tips/images/live_templates_1_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_2.gif b/resources-en/src/tips/images/live_templates_2.gif
deleted file mode 100644
index 8feba9a..0000000
--- a/resources-en/src/tips/images/live_templates_2.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_2.png b/resources-en/src/tips/images/live_templates_2.png
new file mode 100644
index 0000000..e436f03
--- /dev/null
+++ b/resources-en/src/tips/images/live_templates_2.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..4dc9016
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_2@2x_dark.png b/resources-en/src/tips/images/live_templates_2@2x_dark.png
new file mode 100644
index 0000000..63e8558
--- /dev/null
+++ b/resources-en/src/tips/images/live_templates_2@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/live_templates_2_dark.png b/resources-en/src/tips/images/live_templates_2_dark.png
new file mode 100644
index 0000000..5e0343c
--- /dev/null
+++ b/resources-en/src/tips/images/live_templates_2_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/move_inner.gif b/resources-en/src/tips/images/move_inner.gif
deleted file mode 100644
index 98e8426..0000000
--- a/resources-en/src/tips/images/move_inner.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/move_inner.png b/resources-en/src/tips/images/move_inner.png
new file mode 100644
index 0000000..3ea4b4d
--- /dev/null
+++ b/resources-en/src/tips/images/move_inner.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..bc318c9
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/move_inner@2x_dark.png b/resources-en/src/tips/images/move_inner@2x_dark.png
new file mode 100644
index 0000000..f32e1a7
--- /dev/null
+++ b/resources-en/src/tips/images/move_inner@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/move_inner_dark.png b/resources-en/src/tips/images/move_inner_dark.png
new file mode 100644
index 0000000..90ac5a7
--- /dev/null
+++ b/resources-en/src/tips/images/move_inner_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/properties_completion.gif b/resources-en/src/tips/images/properties_completion.gif
deleted file mode 100644
index 54ef057..0000000
--- a/resources-en/src/tips/images/properties_completion.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/properties_completion.png b/resources-en/src/tips/images/properties_completion.png
new file mode 100644
index 0000000..dc41748
--- /dev/null
+++ b/resources-en/src/tips/images/properties_completion.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..5ac32cf
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/properties_completion@2x_dark.png b/resources-en/src/tips/images/properties_completion@2x_dark.png
new file mode 100644
index 0000000..d9c26dc
--- /dev/null
+++ b/resources-en/src/tips/images/properties_completion@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/properties_completion_dark.png b/resources-en/src/tips/images/properties_completion_dark.png
new file mode 100644
index 0000000..cf3c584
--- /dev/null
+++ b/resources-en/src/tips/images/properties_completion_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/sidebyside.png b/resources-en/src/tips/images/sidebyside.png
new file mode 100644
index 0000000..1a9d16d
--- /dev/null
+++ b/resources-en/src/tips/images/sidebyside.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..d4a6892
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/sidebyside@2x_dark.png b/resources-en/src/tips/images/sidebyside@2x_dark.png
new file mode 100644
index 0000000..99bdfbf
--- /dev/null
+++ b/resources-en/src/tips/images/sidebyside@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/sidebyside_dark.png b/resources-en/src/tips/images/sidebyside_dark.png
new file mode 100644
index 0000000..7bd244a
--- /dev/null
+++ b/resources-en/src/tips/images/sidebyside_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_1.gif b/resources-en/src/tips/images/smart_type_after_new_1.gif
deleted file mode 100644
index c0c13ea..0000000
--- a/resources-en/src/tips/images/smart_type_after_new_1.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_1.png b/resources-en/src/tips/images/smart_type_after_new_1.png
new file mode 100644
index 0000000..9e5d60c5
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_after_new_1.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..31d5395
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_1@2x_dark.png b/resources-en/src/tips/images/smart_type_after_new_1@2x_dark.png
new file mode 100644
index 0000000..e6a1ee6
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_after_new_1@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_1_dark.png b/resources-en/src/tips/images/smart_type_after_new_1_dark.png
new file mode 100644
index 0000000..6ad123d
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_after_new_1_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_2.gif b/resources-en/src/tips/images/smart_type_after_new_2.gif
deleted file mode 100644
index 567f8fd..0000000
--- a/resources-en/src/tips/images/smart_type_after_new_2.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_2.png b/resources-en/src/tips/images/smart_type_after_new_2.png
new file mode 100644
index 0000000..e702c02
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_after_new_2.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..bee95dd
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_2@2x_dark.png b/resources-en/src/tips/images/smart_type_after_new_2@2x_dark.png
new file mode 100644
index 0000000..30ef846
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_after_new_2@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_after_new_2_dark.png b/resources-en/src/tips/images/smart_type_after_new_2_dark.png
new file mode 100644
index 0000000..680bc43
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_after_new_2_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_1.gif b/resources-en/src/tips/images/smart_type_completion_1.gif
deleted file mode 100644
index 43ef2b7..0000000
--- a/resources-en/src/tips/images/smart_type_completion_1.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_1.png b/resources-en/src/tips/images/smart_type_completion_1.png
new file mode 100644
index 0000000..bb1ac1c
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_completion_1.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..6a01294
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_1@2x_dark.png b/resources-en/src/tips/images/smart_type_completion_1@2x_dark.png
new file mode 100644
index 0000000..4dd3579
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_completion_1@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_1_dark.png b/resources-en/src/tips/images/smart_type_completion_1_dark.png
new file mode 100644
index 0000000..d41d984
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_completion_1_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_2.gif b/resources-en/src/tips/images/smart_type_completion_2.gif
deleted file mode 100644
index 887b9bc..0000000
--- a/resources-en/src/tips/images/smart_type_completion_2.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_2.png b/resources-en/src/tips/images/smart_type_completion_2.png
new file mode 100644
index 0000000..31e654d
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_completion_2.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..a7aebda
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_2@2x_dark.png b/resources-en/src/tips/images/smart_type_completion_2@2x_dark.png
new file mode 100644
index 0000000..5de6556
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_completion_2@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/smart_type_completion_2_dark.png b/resources-en/src/tips/images/smart_type_completion_2_dark.png
new file mode 100644
index 0000000..4fe0242
--- /dev/null
+++ b/resources-en/src/tips/images/smart_type_completion_2_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/surround_with.gif b/resources-en/src/tips/images/surround_with.gif
deleted file mode 100644
index c01fa73..0000000
--- a/resources-en/src/tips/images/surround_with.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/surround_with.png b/resources-en/src/tips/images/surround_with.png
new file mode 100644
index 0000000..5bdd859
--- /dev/null
+++ b/resources-en/src/tips/images/surround_with.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..0087227
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/surround_with@2x_dark.png b/resources-en/src/tips/images/surround_with@2x_dark.png
new file mode 100644
index 0000000..e9a55d3
--- /dev/null
+++ b/resources-en/src/tips/images/surround_with@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/surround_with_dark.png b/resources-en/src/tips/images/surround_with_dark.png
new file mode 100644
index 0000000..a558a1c
--- /dev/null
+++ b/resources-en/src/tips/images/surround_with_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/terminal.png b/resources-en/src/tips/images/terminal.png
new file mode 100644
index 0000000..ec8e14b
--- /dev/null
+++ b/resources-en/src/tips/images/terminal.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..99fe371
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/terminal@2x_dark.png b/resources-en/src/tips/images/terminal@2x_dark.png
new file mode 100644
index 0000000..2381bc1
--- /dev/null
+++ b/resources-en/src/tips/images/terminal@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/terminal_dark.png b/resources-en/src/tips/images/terminal_dark.png
new file mode 100644
index 0000000..4a8ba4f
--- /dev/null
+++ b/resources-en/src/tips/images/terminal_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/toar_after.png b/resources-en/src/tips/images/toar_after.png
index 29679d4..96efaeb 100644
--- a/resources-en/src/tips/images/toar_after.png
+++ b/resources-en/src/tips/images/toar_after.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..ea82e1c
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/toar_after@2x_dark.png b/resources-en/src/tips/images/toar_after@2x_dark.png
new file mode 100644
index 0000000..33b6466
--- /dev/null
+++ b/resources-en/src/tips/images/toar_after@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/toar_after_dark.png b/resources-en/src/tips/images/toar_after_dark.png
new file mode 100644
index 0000000..1fa53cb
--- /dev/null
+++ b/resources-en/src/tips/images/toar_after_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/toar_before.png b/resources-en/src/tips/images/toar_before.png
index 2d3593a..0fde13b 100644
--- a/resources-en/src/tips/images/toar_before.png
+++ b/resources-en/src/tips/images/toar_before.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..f09de7a
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/toar_before@2x_dark.png b/resources-en/src/tips/images/toar_before@2x_dark.png
new file mode 100644
index 0000000..23c3ccc
--- /dev/null
+++ b/resources-en/src/tips/images/toar_before@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/toar_before_dark.png b/resources-en/src/tips/images/toar_before_dark.png
new file mode 100644
index 0000000..0b726218
--- /dev/null
+++ b/resources-en/src/tips/images/toar_before_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/variable_name_completion.gif b/resources-en/src/tips/images/variable_name_completion.gif
deleted file mode 100644
index 3ff4f22..0000000
--- a/resources-en/src/tips/images/variable_name_completion.gif
+++ /dev/null
Binary files differ
diff --git a/resources-en/src/tips/images/variable_name_completion.png b/resources-en/src/tips/images/variable_name_completion.png
new file mode 100644
index 0000000..e60b430
--- /dev/null
+++ b/resources-en/src/tips/images/variable_name_completion.png
Binary files differ
diff --git a/resources-en/src/tips/images/[email protected] b/resources-en/src/tips/images/[email protected]
new file mode 100644
index 0000000..96f1bf5
--- /dev/null
+++ b/resources-en/src/tips/images/[email protected]
Binary files differ
diff --git a/resources-en/src/tips/images/variable_name_completion@2x_dark.png b/resources-en/src/tips/images/variable_name_completion@2x_dark.png
new file mode 100644
index 0000000..54289b2
--- /dev/null
+++ b/resources-en/src/tips/images/variable_name_completion@2x_dark.png
Binary files differ
diff --git a/resources-en/src/tips/images/variable_name_completion_dark.png b/resources-en/src/tips/images/variable_name_completion_dark.png
new file mode 100644
index 0000000..22139b4
--- /dev/null
+++ b/resources-en/src/tips/images/variable_name_completion_dark.png
Binary files differ
diff --git a/resources-en/src/tips/tips.xml b/resources-en/src/tips/tips.xml
index 7ec9c56..503f3859 100644
--- a/resources-en/src/tips/tips.xml
+++ b/resources-en/src/tips/tips.xml
@@ -159,4 +159,8 @@
   <tip file="RefactorThis.html"/>
   <tip file="FavoritesToolWindow1.html"/>
   <tip file="FavoritesToolWindow2.html"/>
+
+  <tip file="WideScreen.html"/>
+  <tip file="Terminal.html"/>
+  <tip file="ConfiguringTerminal.html"/>
 </tips>
diff --git a/resources/src/META-INF/IdeaPlugin.xml b/resources/src/META-INF/IdeaPlugin.xml
index 05517c4..c5e1481 100644
--- a/resources/src/META-INF/IdeaPlugin.xml
+++ b/resources/src/META-INF/IdeaPlugin.xml
@@ -1495,6 +1495,7 @@
             icon="AllIcons.General.ProjectStructure">
       <add-to-group group-id="FileMainSettingsGroup" anchor="after" relative-to-action="ShowSettings"/>
       <add-to-group group-id="MainToolBarSettings" anchor="after" relative-to-action="ShowSettings"/>
+      <add-to-group group-id="NavBarToolBar" anchor="last"/>
     </action>
     <action id="TemplateProjectStructure" class="com.intellij.ide.actions.TemplateProjectStructureAction">
       <add-to-group group-id="FileSettingsGroup" anchor="last"/>
diff --git a/updater/src/com/intellij/updater/Runner.java b/updater/src/com/intellij/updater/Runner.java
index 02c4550..2935f7c 100644
--- a/updater/src/com/intellij/updater/Runner.java
+++ b/updater/src/com/intellij/updater/Runner.java
@@ -70,7 +70,8 @@
 
   private static void printUsage() {
     System.err.println("Usage:\n" +
-                       "create <old_version_description> <new_version_description> <old_version_folder> <new_version_folder> <patch_file_name> [ignored=file1;file2;...] [critical=file1;file2;...] [optional=file1;file2;...]\n" +
+                       "create <old_version_description> <new_version_description> <old_version_folder> <new_version_folder>" +
+                       " <patch_file_name> [ignored=file1;file2;...] [critical=file1;file2;...] [optional=file1;file2;...]\n" +
                        "install <destination_folder>\n");
   }
 
@@ -94,8 +95,10 @@
                               ui);
 
       ui.startProcess("Packing jar file '" + patchFile + "'...");
-      ZipOutputWrapper out = new ZipOutputWrapper(new FileOutputStream(patchFile));
+
+      FileOutputStream fileOut = new FileOutputStream(patchFile);
       try {
+        ZipOutputWrapper out = new ZipOutputWrapper(fileOut);
         ZipInputStream in = new ZipInputStream(new FileInputStream(resolveJarFile()));
         try {
           ZipEntry e;
@@ -110,8 +113,8 @@
         ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
         try {
           Properties props = new Properties();
-          props.put(OLD_BUILD_DESCRIPTION, oldBuildDesc);
-          props.put(NEW_BUILD_DESCRIPTION, newBuildDesc);
+          props.setProperty(OLD_BUILD_DESCRIPTION, oldBuildDesc);
+          props.setProperty(NEW_BUILD_DESCRIPTION, newBuildDesc);
           props.store(byteOut, "");
         }
         finally {
@@ -120,9 +123,10 @@
 
         out.zipBytes(PATCH_PROPERTIES_ENTRY, byteOut);
         out.zipFile(PATCH_FILE_NAME, tempPatchFile);
+        out.finish();
       }
       finally {
-        out.close();
+        fileOut.close();
       }
     }
     finally {
diff --git a/updater/src/com/intellij/updater/SwingUpdaterUI.java b/updater/src/com/intellij/updater/SwingUpdaterUI.java
index 75af634..1fa8514 100644
--- a/updater/src/com/intellij/updater/SwingUpdaterUI.java
+++ b/updater/src/com/intellij/updater/SwingUpdaterUI.java
@@ -63,6 +63,7 @@
     myConsole.setWrapStyleWord(true);
     myConsole.setCaretPosition(myConsole.getText().length());
     myConsole.setTabSize(1);
+    myConsole.setMargin(new Insets(2, 4, 2, 4));
     myConsolePane = new JPanel(new BorderLayout());
     myConsolePane.add(new JScrollPane(myConsole));
     myConsolePane.setBorder(BUTTONS_BORDER);
@@ -314,18 +315,25 @@
   }
 
   public void showError(final Throwable e) {
+    hasError.set(true);
+
     myQueue.add(new UpdateRequest() {
       public void perform() {
         StringWriter w = new StringWriter();
+        if (!myConsolePane.isVisible()) {
+          w.write("Temp. directory: ");
+          w.write(System.getProperty("java.io.tmpdir"));
+          w.write("\n\n");
+        }
         e.printStackTrace(new PrintWriter(w));
         w.append("\n");
         myConsole.append(w.getBuffer().toString());
         if (!myConsolePane.isVisible()) {
+          myConsole.setCaretPosition(0);
           myConsolePane.setVisible(true);
           myConsolePane.setPreferredSize(new Dimension(10, 200));
           myFrame.pack();
         }
-        hasError.set(true);
       }
     });
   }
diff --git a/updater/src/com/intellij/updater/UpdateZipAction.java b/updater/src/com/intellij/updater/UpdateZipAction.java
index 553e7d8..672d357 100644
--- a/updater/src/com/intellij/updater/UpdateZipAction.java
+++ b/updater/src/com/intellij/updater/UpdateZipAction.java
@@ -149,11 +149,11 @@
 
   protected void doApply(final ZipFile patchFile, File toFile) throws IOException {
     File temp = Utils.createTempFile();
-    @SuppressWarnings("IOResourceOpenedButNotSafelyClosed")
-    final ZipOutputWrapper out = new ZipOutputWrapper(new FileOutputStream(temp));
-    out.setCompressionLevel(0);
-
+    FileOutputStream fileOut = new FileOutputStream(temp);
     try {
+      final ZipOutputWrapper out = new ZipOutputWrapper(fileOut);
+      out.setCompressionLevel(0);
+
       processZipFile(toFile, new Processor() {
         public void process(ZipEntry entry, InputStream in) throws IOException {
           String path = entry.getName();
@@ -183,9 +183,11 @@
           in.close();
         }
       }
+
+      out.finish();
     }
     finally {
-      out.close();
+      fileOut.close();
     }
 
     replaceUpdated(temp, toFile);
diff --git a/updater/src/com/intellij/updater/Utils.java b/updater/src/com/intellij/updater/Utils.java
index 427788e..666ac1a 100644
--- a/updater/src/com/intellij/updater/Utils.java
+++ b/updater/src/com/intellij/updater/Utils.java
@@ -17,12 +17,12 @@
   @SuppressWarnings({"SSBasedInspection"})
   public static File createTempFile() throws IOException {
     if (myTempDir == null) {
-      myTempDir = File.createTempFile("idea.updater", "tmp");
+      myTempDir = File.createTempFile("idea.updater.", ".tmp");
       delete(myTempDir);
       myTempDir.mkdirs();
     }
 
-    return File.createTempFile("temp", "tmp", myTempDir);
+    return File.createTempFile("temp.", ".tmp", myTempDir);
   }
 
   public static File createTempDir() throws IOException {
diff --git a/updater/src/com/intellij/updater/ZipOutputWrapper.java b/updater/src/com/intellij/updater/ZipOutputWrapper.java
index 1ccbc45..ec47546 100644
--- a/updater/src/com/intellij/updater/ZipOutputWrapper.java
+++ b/updater/src/com/intellij/updater/ZipOutputWrapper.java
@@ -74,14 +74,10 @@
     }
 
     myOut.putNextEntry(entry);
-    try {
-      byteOut.writeTo(myOut);
-    }
-    finally {
-      myOut.closeEntry();
-    }
+    byteOut.writeTo(myOut);
+    myOut.closeEntry();
   }
-  
+
   public void zipFile(String entryPath, File file) throws IOException {
     if (file.isDirectory()) {
       addDirs(entryPath, true);
@@ -124,20 +120,17 @@
     myDirs.addAll(temp);
   }
 
-  public void close() throws IOException {
-    try {
-      for (String each : myDirs) {
-        if (!each.endsWith("/")) each += "/";
-        ZipEntry e = new ZipEntry(each);
-        e.setMethod(ZipEntry.STORED);
-        e.setSize(0);
-        e.setCrc(0);
-        myOut.putNextEntry(e);
-        myOut.closeEntry();
-      }
+  public void finish() throws IOException {
+    for (String each : myDirs) {
+      if (!each.endsWith("/")) each += "/";
+      ZipEntry e = new ZipEntry(each);
+      e.setMethod(ZipEntry.STORED);
+      e.setSize(0);
+      e.setCrc(0);
+      myOut.putNextEntry(e);
+      myOut.closeEntry();
     }
-    finally {
-      myOut.close();
-    }
+
+    myOut.close();
   }
 }
diff --git a/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfoBuilder.java b/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfoBuilder.java
index 2aeca7f..e029fe1 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfoBuilder.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/impl/StaticGenericInfoBuilder.java
@@ -66,7 +66,7 @@
   public StaticGenericInfoBuilder(final Class aClass) {
     myClass = aClass;
 
-    final Set<JavaMethod> methods = new THashSet<JavaMethod>();
+    final Set<JavaMethod> methods = new LinkedHashSet<JavaMethod>();
     InvocationCache invocationCache = DomApplicationComponent.getInstance().getInvocationCache(myClass);
     for (final Method method : ReflectionCache.getMethods(myClass)) {
       methods.add(invocationCache.getInternedMethod(method));
diff --git a/xml/dom-impl/src/com/intellij/util/xml/stubs/index/DomNamespaceKeyIndex.java b/xml/dom-impl/src/com/intellij/util/xml/stubs/index/DomNamespaceKeyIndex.java
index 9ff7b32..a585f88 100644
--- a/xml/dom-impl/src/com/intellij/util/xml/stubs/index/DomNamespaceKeyIndex.java
+++ b/xml/dom-impl/src/com/intellij/util/xml/stubs/index/DomNamespaceKeyIndex.java
@@ -42,7 +42,7 @@
 
   public boolean hasStubElementsWithNamespaceKey(final DomFileElement domFileElement, final String namespaceKey) {
     final VirtualFile file = domFileElement.getFile().getVirtualFile();
-    assert file instanceof VirtualFileWithId : file;
+    if (!(file instanceof VirtualFileWithId)) return false;
 
     final int virtualFileId = ((VirtualFileWithId)file).getId();
     CommonProcessors.FindFirstProcessor<String> processor =
diff --git a/xml/dom-openapi/src/com/intellij/util/xml/converters/QuotedValueConverter.java b/xml/dom-openapi/src/com/intellij/util/xml/converters/QuotedValueConverter.java
index 7a72c2a..0de4cde 100644
--- a/xml/dom-openapi/src/com/intellij/util/xml/converters/QuotedValueConverter.java
+++ b/xml/dom-openapi/src/com/intellij/util/xml/converters/QuotedValueConverter.java
@@ -27,7 +27,7 @@
 import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.psi.*;
 import com.intellij.util.xml.*;
-import com.intellij.xml.util.XmlTagUtilBase;
+import org.jetbrains.annotations.Contract;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
@@ -85,13 +85,14 @@
                                          final ConvertContext context) {
     final String originalValue = genericDomValue.getStringValue();
     if (originalValue == null) return PsiReference.EMPTY_ARRAY;
-    final String unquotedValue = unquote(originalValue, getQuoteSigns());
-    int startOffset = originalValue == unquotedValue? 0 : XmlTagUtilBase.escapeString(originalValue.substring(0, 1), false).length();
-    int endOffset = originalValue == unquotedValue || quotationIsNotClosed(originalValue)? 0 : startOffset;
-    final ElementManipulator<PsiElement> manipulator = ElementManipulators.getManipulator(element);
-    assert manipulator != null : "manipulator not found";
-    final TextRange range = manipulator.getRangeInElement(element);
-    return new PsiReference[]{createPsiReference(element, range.getStartOffset()+startOffset, range.getEndOffset() - endOffset, true, context, genericDomValue, startOffset != endOffset)};
+    TextRange range = ElementManipulators.getValueTextRange(element);
+    String unquotedValue = unquote(originalValue, getQuoteSigns());
+    int valueOffset = range.substring(element.getText()).indexOf(unquotedValue);
+    if (valueOffset < 0) return PsiReference.EMPTY_ARRAY;
+    int start = range.getStartOffset() + valueOffset;
+    int end = start + unquotedValue.length();
+    boolean unclosedQuotation = valueOffset > 0 && end == range.getEndOffset();
+    return new PsiReference[]{createPsiReference(element, start, end, true, context, genericDomValue, unclosedQuotation)};
   }
 
   @Nullable
@@ -99,7 +100,7 @@
     return unquote(str, QUOTE_SIGNS);
   }
 
-  @Nullable
+  @Contract("null, _ -> null")
   public static String unquote(final String str, final char[] quoteSigns) {
     if (str != null && str.length() > 2) {
       final char c = str.charAt(0);
diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java
index 5cd0051..7e57a41 100644
--- a/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java
+++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditor.java
@@ -18,13 +18,13 @@
 
 import com.intellij.codeHighlighting.BackgroundEditorHighlighter;
 import com.intellij.ide.structureView.StructureViewBuilder;
+import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.openapi.editor.Document;
 import com.intellij.openapi.editor.ScrollType;
 import com.intellij.openapi.fileEditor.*;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.UserDataHolderBase;
 import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.openapi.application.ApplicationManager;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
@@ -46,7 +46,7 @@
  * @author Sergey.Vasiliev
  */
 abstract public class PerspectiveFileEditor extends UserDataHolderBase implements DocumentsEditor, Committable {
-  private final Wrapper myWrapprer = new Wrapper();
+  private final Wrapper myWrapper = new Wrapper();
   private boolean myInitialised = false;
 
   private final PropertyChangeSupport myPropertyChangeSupport = new PropertyChangeSupport(this);
@@ -55,22 +55,18 @@
   private final UndoHelper myUndoHelper;
   private boolean myInvalidated;
 
-  private static final FileEditorState FILE_EDITOR_STATE = new FileEditorState() {
-    public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
-      return true;
-    }
-  };
-
   protected PerspectiveFileEditor(final Project project, final VirtualFile file) {
     myProject = project;
     myUndoHelper = new UndoHelper(project, this);
     myFile = file;
 
     FileEditorManager.getInstance(myProject).addFileEditorManagerListener(new FileEditorManagerAdapter() {
+      @Override
       public void selectionChanged(@NotNull FileEditorManagerEvent event) {
         if (!isValid()) return;
 
         ApplicationManager.getApplication().invokeLater(new Runnable() {
+          @Override
           public void run() {
             if (myUndoHelper.isShowing() && !getComponent().isShowing()) {
               deselectNotify();
@@ -183,6 +179,7 @@
     return PsiManager.getInstance(myProject).findFile(myFile);
   }
 
+  @Override
   public final Document[] getDocuments() {
     return myUndoHelper.getDocuments();
   }
@@ -195,20 +192,24 @@
     return myFile;
   }
 
+  @Override
   public void dispose() {
     if (myInvalidated) return;
     myInvalidated = true;
     myUndoHelper.stopListeningDocuments();
   }
 
+  @Override
   public final boolean isModified() {
     return FileDocumentManager.getInstance().isFileModified(getVirtualFile());
   }
 
+  @Override
   public boolean isValid() {
     return getVirtualFile().isValid();
   }
 
+  @Override
   public void selectNotify() {
     if (!checkIsValid() || myInvalidated) return;
     ensureInitialized();
@@ -222,50 +223,60 @@
 
   protected final synchronized void ensureInitialized() {
     if (!isInitialised()) {
-      myWrapprer.setContent(createCustomComponent());
+      myWrapper.setContent(createCustomComponent());
       myInitialised = true;
     }
   }
 
+  @Override
   public void deselectNotify() {
     if (!checkIsValid() || myInvalidated) return;
     setShowing(false);
     commit();
   }
 
+  @Override
   public BackgroundEditorHighlighter getBackgroundHighlighter() {
     return null;
   }
 
+  @Override
   public FileEditorLocation getCurrentLocation() {
     return new FileEditorLocation() {
+      @Override
       @NotNull
       public FileEditor getEditor() {
         return PerspectiveFileEditor.this;
       }
 
-      public int compareTo(final FileEditorLocation fileEditorLocation) {
+      @Override
+      public int compareTo(@NotNull final FileEditorLocation fileEditorLocation) {
         return 0;
       }
     };
   }
 
+  @Override
   public StructureViewBuilder getStructureViewBuilder() {
     return null;
   }
 
+  @Override
   @NotNull
   public FileEditorState getState(@NotNull FileEditorStateLevel level) {
-    return FILE_EDITOR_STATE;
+    return FileEditorState.INSTANCE;
   }
 
+  @Override
   public void setState(@NotNull FileEditorState state) {
   }
 
+  @Override
   public void addPropertyChangeListener(@NotNull PropertyChangeListener listener) {
     myPropertyChangeSupport.addPropertyChangeListener(listener);
   }
 
+  @Override
   public void removePropertyChangeListener(@NotNull PropertyChangeListener listener) {
     myPropertyChangeSupport.removePropertyChangeListener(listener);
   }
@@ -278,6 +289,7 @@
     return !myInvalidated;
   }
 
+  @Override
   @NotNull
   public JComponent getComponent() {
     return getWrapper();
@@ -287,7 +299,7 @@
   protected abstract JComponent createCustomComponent();
 
   public Wrapper getWrapper() {
-    return myWrapprer;
+    return myWrapper;
   }
 
   protected final synchronized boolean isInitialised() {
diff --git a/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditorProvider.java b/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditorProvider.java
index 882f213..7e4ba4c 100644
--- a/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditorProvider.java
+++ b/xml/dom-openapi/src/com/intellij/util/xml/ui/PerspectiveFileEditorProvider.java
@@ -15,7 +15,10 @@
  */
 package com.intellij.util.xml.ui;
 
-import com.intellij.openapi.fileEditor.*;
+import com.intellij.openapi.fileEditor.FileEditor;
+import com.intellij.openapi.fileEditor.FileEditorPolicy;
+import com.intellij.openapi.fileEditor.FileEditorState;
+import com.intellij.openapi.fileEditor.WeighedFileEditorProvider;
 import com.intellij.openapi.project.Project;
 import com.intellij.openapi.util.Disposer;
 import com.intellij.openapi.vfs.VirtualFile;
@@ -27,31 +30,33 @@
  * @author peter
  */
 public abstract class PerspectiveFileEditorProvider extends WeighedFileEditorProvider {
+  @Override
   @NotNull
   public abstract PerspectiveFileEditor createEditor(@NotNull Project project, @NotNull VirtualFile file);
 
+  @Override
   public void disposeEditor(@NotNull FileEditor editor) {
     Disposer.dispose(editor);
   }
 
+  @Override
   @NotNull
   public FileEditorState readState(@NotNull Element sourceElement, @NotNull Project project, @NotNull VirtualFile file) {
-    return new FileEditorState() {
-      public boolean canBeMergedWith(FileEditorState otherState, FileEditorStateLevel level) {
-        return true;
-      }
-    };
+    return FileEditorState.INSTANCE;
   }
 
+  @Override
   public void writeState(@NotNull FileEditorState state, @NotNull Project project, @NotNull Element targetElement) {
   }
 
+  @Override
   @NotNull
   @NonNls
   public final String getEditorTypeId() {
     return getComponentName();
   }
 
+  @Override
   @NotNull
   public final FileEditorPolicy getPolicy() {
     return FileEditorPolicy.PLACE_AFTER_DEFAULT_EDITOR;
diff --git a/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java b/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
index 68447ae..40b7db8 100644
--- a/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
+++ b/xml/impl/src/com/intellij/codeInsight/completion/XmlTagInsertHandler.java
@@ -287,7 +287,7 @@
     }
     else if (completionChar == Lookup.AUTO_INSERT_SELECT_CHAR || completionChar == Lookup.NORMAL_SELECT_CHAR || completionChar == Lookup.REPLACE_SELECT_CHAR) {
       if (WebEditorOptions.getInstance().isAutomaticallyInsertClosingTag() && isHtmlCode && HtmlUtil.isSingleHtmlTag(tag.getName())) {
-        template.addTextSegment(tag instanceof HtmlTag ? ">" : "/>");
+        template.addTextSegment(HtmlUtil.isHtmlTag(tag) ? ">" : "/>");
       }
       else {
         if (needAlLeastOneAttribute(tag) && WebEditorOptions.getInstance().isAutomaticallyStartAttribute() && tag.getAttributes().length == 0
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 3797ae9..f6f5bda 100644
--- a/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
+++ b/xml/impl/src/com/intellij/codeInsight/template/emmet/ZenCodingTemplate.java
@@ -40,12 +40,15 @@
 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.Pair;
 import com.intellij.openapi.util.TextRange;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.wm.IdeFocusManager;
 import com.intellij.psi.PsiDocumentManager;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.ui.*;
+import com.intellij.util.containers.ContainerUtil;
 import com.intellij.xml.XmlBundle;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
@@ -274,8 +277,12 @@
   private static boolean isPrimitiveNode(@NotNull ZenCodingNode node) {
     if (node instanceof TemplateNode) {
       final TemplateToken token = ((TemplateNode)node).getTemplateToken();
-      if (token != null && token.getAttribute2Value().isEmpty()) {
-        return true;
+      if (token != null) {
+        final List<Pair<String,String>> attributes = token.getAttribute2Value();
+        final Pair<String, String> singleAttribute = ContainerUtil.getFirstItem(attributes);
+        if (singleAttribute == null || "class".equalsIgnoreCase(singleAttribute.first) && StringUtil.isEmpty(singleAttribute.second)) {
+          return true;
+        }
       }
     }
     return false;
@@ -349,6 +356,7 @@
       @Override
       public void run() {
         focusManager.requestFocus(field, true);
+        field.selectText();
       }
     });
   }
diff --git a/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java b/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java
index 20201d3..b2d5c6f 100644
--- a/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java
+++ b/xml/impl/src/com/intellij/ide/browsers/BrowserStarter.java
@@ -6,6 +6,7 @@
 import com.intellij.execution.process.ProcessHandler;
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.util.text.StringUtil;
+import com.intellij.util.Urls;
 import com.intellij.util.net.NetUtils;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
diff --git a/xml/impl/src/com/intellij/ide/browsers/LocalFileUrl.java b/xml/impl/src/com/intellij/ide/browsers/LocalFileUrl.java
deleted file mode 100644
index c91941f..0000000
--- a/xml/impl/src/com/intellij/ide/browsers/LocalFileUrl.java
+++ /dev/null
@@ -1,103 +0,0 @@
-package com.intellij.ide.browsers;
-
-import com.intellij.openapi.util.SystemInfo;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-
-public final class LocalFileUrl implements Url {
-  private final String path;
-
-  public LocalFileUrl(@NotNull String path) {
-    this.path = path;
-  }
-
-  @NotNull
-  @Override
-  public String getPath() {
-    return path;
-  }
-
-  @Override
-  public boolean isInLocalFileSystem() {
-    return true;
-  }
-
-  @Override
-  public String toDecodedForm(boolean skipQueryAndFragment) {
-    return path;
-  }
-
-  @NotNull
-  @Override
-  public String toExternalForm() {
-    return path;
-  }
-
-  @NotNull
-  @Override
-  public URI toJavaUriWithoutParameters() {
-    try {
-      String externalPath = path;
-      if (SystemInfo.isWindows && externalPath.charAt(0) != '/') {
-        externalPath = '/' + externalPath;
-      }
-      return new URI("file", "", externalPath, null, null);
-    }
-    catch (URISyntaxException e) {
-      throw new RuntimeException(e);
-    }
-  }
-
-  @NotNull
-  @Override
-  public String toExternalForm(boolean skipQueryAndFragment) {
-    return toExternalForm();
-  }
-
-  @Nullable
-  @Override
-  public String getScheme() {
-    return null;
-  }
-
-  @Nullable
-  @Override
-  public String getAuthority() {
-    return null;
-  }
-
-  @Nullable
-  @Override
-  public String getParametersPart() {
-    return null;
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) {
-      return true;
-    }
-    if (!(o instanceof LocalFileUrl)) {
-      return false;
-    }
-    return path.equals(((LocalFileUrl)o).path);
-  }
-
-  @Override
-  public boolean equalsIgnoreParameters(@Nullable Url url) {
-    return equals(url);
-  }
-
-  @Override
-  public int hashCode() {
-    return path.hashCode();
-  }
-
-  @Override
-  public String toString() {
-    return toExternalForm();
-  }
-}
\ No newline at end of file
diff --git a/xml/impl/src/com/intellij/ide/browsers/OpenFileInDefaultBrowserAction.java b/xml/impl/src/com/intellij/ide/browsers/OpenFileInDefaultBrowserAction.java
index 92f5abf..1ffc4d2 100644
--- a/xml/impl/src/com/intellij/ide/browsers/OpenFileInDefaultBrowserAction.java
+++ b/xml/impl/src/com/intellij/ide/browsers/OpenFileInDefaultBrowserAction.java
@@ -32,6 +32,7 @@
 import com.intellij.ui.ColoredListCellRenderer;
 import com.intellij.ui.components.JBList;
 import com.intellij.util.Consumer;
+import com.intellij.util.Url;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.xml.XmlBundle;
 import com.intellij.xml.util.HtmlUtil;
@@ -39,7 +40,7 @@
 
 import javax.swing.*;
 import java.awt.event.InputEvent;
-import java.util.Set;
+import java.util.Collection;
 
 public class OpenFileInDefaultBrowserAction extends DumbAwareAction {
   private static final Logger LOG = Logger.getInstance(OpenFileInDefaultBrowserAction.class);
@@ -56,7 +57,7 @@
       return;
     }
 
-    Pair<WebBrowserUrlProvider, Set<Url>> browserUrlProvider = WebBrowserServiceImpl.getProvider(file);
+    Pair<WebBrowserUrlProvider, Collection<Url>> browserUrlProvider = WebBrowserServiceImpl.getProvider(file);
     final boolean isHtmlFile = HtmlUtil.isHtmlFile(file);
     if (browserUrlProvider == null) {
       if (file.getVirtualFile() instanceof LightVirtualFile) {
@@ -117,7 +118,7 @@
 
   public static void doOpen(PsiElement psiFile, boolean preferLocalUrl, final WebBrowser browser) {
     try {
-      Set<Url> urls = WebBrowserService.getInstance().getUrlToOpen(psiFile, preferLocalUrl);
+      Collection<Url> urls = WebBrowserService.getInstance().getUrlToOpen(psiFile, preferLocalUrl);
       if (!urls.isEmpty()) {
         chooseUrl(urls).doWhenDone(new Consumer<Url>() {
           @Override
@@ -137,7 +138,7 @@
   }
 
   @NotNull
-  private static AsyncResult<Url> chooseUrl(Set<Url> urls) {
+  private static AsyncResult<Url> chooseUrl(Collection<Url> urls) {
     if (urls.size() == 1) {
       return new AsyncResult.Done<Url>(ContainerUtil.getFirstItem(urls));
     }
@@ -148,7 +149,7 @@
       protected void customizeCellRenderer(JList list, Object value, int index, boolean selected, boolean hasFocus) {
         // todo icons looks good, but is it really suitable for all URLs providers?
         setIcon(AllIcons.Nodes.Servlet);
-        append(((Url)value).getPath());
+        append(((Url)value).toDecodedForm());
       }
     });
 
diff --git a/xml/impl/src/com/intellij/ide/browsers/SelectInDefaultBrowserTarget.java b/xml/impl/src/com/intellij/ide/browsers/SelectInDefaultBrowserTarget.java
index 55ceeeb..f4a5c7e 100644
--- a/xml/impl/src/com/intellij/ide/browsers/SelectInDefaultBrowserTarget.java
+++ b/xml/impl/src/com/intellij/ide/browsers/SelectInDefaultBrowserTarget.java
@@ -24,10 +24,11 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.testFramework.LightVirtualFile;
+import com.intellij.util.Url;
 import com.intellij.xml.XmlBundle;
 import com.intellij.xml.util.HtmlUtil;
 
-import java.util.Set;
+import java.util.Collection;
 
 class SelectInDefaultBrowserTarget extends SelectInTargetBase {
   private static final Logger LOG = Logger.getInstance(SelectInDefaultBrowserTarget.class);
@@ -46,7 +47,7 @@
       return false;
     }
 
-    Pair<WebBrowserUrlProvider, Set<Url>> browserUrlProvider = WebBrowserServiceImpl.getProvider(file);
+    Pair<WebBrowserUrlProvider, Collection<Url>> browserUrlProvider = WebBrowserServiceImpl.getProvider(file);
     currentName = XmlBundle.message("browser.select.in.default.name");
     if (browserUrlProvider == null) {
       return HtmlUtil.isHtmlFile(file) && !(file.getVirtualFile() instanceof LightVirtualFile);
diff --git a/xml/impl/src/com/intellij/ide/browsers/StartBrowserPanel.java b/xml/impl/src/com/intellij/ide/browsers/StartBrowserPanel.java
index 8661a26..75cb440 100644
--- a/xml/impl/src/com/intellij/ide/browsers/StartBrowserPanel.java
+++ b/xml/impl/src/com/intellij/ide/browsers/StartBrowserPanel.java
@@ -3,6 +3,7 @@
 import com.intellij.ide.DataManager;
 import com.intellij.ide.browsers.impl.WebBrowserServiceImpl;
 import com.intellij.openapi.actionSystem.CommonDataKeys;
+import com.intellij.openapi.actionSystem.DataContext;
 import com.intellij.openapi.application.AccessToken;
 import com.intellij.openapi.application.ReadAction;
 import com.intellij.openapi.fileChooser.FileChooserDescriptor;
@@ -18,6 +19,8 @@
 import com.intellij.psi.PsiFile;
 import com.intellij.psi.PsiManager;
 import com.intellij.ui.AncestorListenerAdapter;
+import com.intellij.util.Consumer;
+import com.intellij.util.Url;
 import com.intellij.util.io.URLUtil;
 import com.intellij.util.ui.UIUtil;
 import com.intellij.xml.XmlBundle;
@@ -45,9 +48,20 @@
     myRoot.addAncestorListener(new AncestorListenerAdapter() {
       @Override
       public void ancestorAdded(AncestorEvent event) {
-        Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myUrlField));
-        assert project != null;
-        setupUrlField(myUrlField, project);
+        Project project = CommonDataKeys.PROJECT.getData(DataManager.getInstance().getDataContext(myRoot));
+        if (project == null) {
+          DataManager.getInstance().getDataContextFromFocus().doWhenDone(new Consumer<DataContext>() {
+            @Override
+            public void consume(DataContext context) {
+              Project project = CommonDataKeys.PROJECT.getData(context);
+              assert project != null;
+              setupUrlField(myUrlField, project);
+            }
+          });
+        }
+        else {
+          setupUrlField(myUrlField, project);
+        }
       }
     });
   }
@@ -126,7 +140,7 @@
       @NotNull
       @Override
       protected String chosenFileToResultingText(@NotNull VirtualFile chosenFile) {
-        return virtualFileToUrl(chosenFile, project).toDecodedForm(false);
+        return virtualFileToUrl(chosenFile, project).toDecodedForm();
       }
     });
   }
diff --git a/xml/impl/src/com/intellij/ide/browsers/UrlImpl.java b/xml/impl/src/com/intellij/ide/browsers/UrlImpl.java
deleted file mode 100644
index f4dd334..0000000
--- a/xml/impl/src/com/intellij/ide/browsers/UrlImpl.java
+++ /dev/null
@@ -1,209 +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.ide.browsers;
-
-import com.intellij.openapi.util.SystemInfo;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.vfs.StandardFileSystems;
-import com.intellij.util.io.URLUtil;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.net.URI;
-import java.net.URISyntaxException;
-
-public final class UrlImpl implements Url {
-  private String externalForm;
-
-  @Nullable
-  private final String scheme;
-
-  private final String authority;
-
-  private final String path;
-  private String decodedPath;
-
-  private final String parameters;
-
-  private String externalFormWithoutParameters;
-
-  public UrlImpl(@Nullable String path) {
-    this(null, null, path, null);
-  }
-
-  public UrlImpl(@NotNull String scheme, @Nullable String authority, @Nullable String path) {
-    this(scheme, authority, path, null);
-  }
-
-  public UrlImpl(@Nullable String scheme, @Nullable String authority, @Nullable String path, @Nullable String parameters) {
-    this.scheme = scheme;
-    this.authority = StringUtil.nullize(authority);
-    this.path = StringUtil.isEmpty(path) ? "/" : path;
-    this.parameters = StringUtil.nullize(parameters);
-  }
-
-  @NotNull
-  @Override
-  public String getPath() {
-    if (decodedPath == null) {
-      decodedPath = URLUtil.unescapePercentSequences(path);
-    }
-    return decodedPath;
-  }
-
-  @Nullable
-  @Override
-  public String getScheme() {
-    return scheme;
-  }
-
-  @Override
-  @Nullable
-  public String getAuthority() {
-    return authority;
-  }
-
-  @Override
-  public boolean isInLocalFileSystem() {
-    return StandardFileSystems.FILE_PROTOCOL.equals(scheme);
-  }
-
-  @Nullable
-  @Override
-  public String getParametersPart() {
-    return parameters;
-  }
-
-  @Override
-  public String toDecodedForm(boolean skipQueryAndFragment) {
-    StringBuilder builder = new StringBuilder();
-    if (scheme != null) {
-      builder.append(scheme).append("://");
-    }
-    if (authority != null) {
-      builder.append(authority);
-    }
-    builder.append(getPath());
-    if (!skipQueryAndFragment && parameters != null) {
-      builder.append(parameters);
-    }
-    return builder.toString();
-  }
-
-  @Override
-  @NotNull
-  public URI toJavaUriWithoutParameters() {
-    try {
-      String externalPath = path;
-      boolean inLocalFileSystem = isInLocalFileSystem();
-      if (inLocalFileSystem && SystemInfo.isWindows && externalPath.charAt(0) != '/') {
-        externalPath = '/' + externalPath;
-      }
-      return new URI(scheme, inLocalFileSystem ? "" : authority, externalPath, null, null);
-    }
-    catch (URISyntaxException e) {
-      throw new RuntimeException(e);
-    }
-  }
-
-  @Override
-  @NotNull
-  public String toExternalForm(boolean skipQueryAndFragment) {
-    if (parameters == null || !skipQueryAndFragment) {
-      if (externalForm != null) {
-        return externalForm;
-      }
-    }
-    else if (externalFormWithoutParameters != null) {
-      return externalFormWithoutParameters;
-    }
-
-    String result = toJavaUriWithoutParameters().toASCIIString();
-    if (skipQueryAndFragment) {
-      externalFormWithoutParameters = result;
-      if (parameters == null) {
-        externalForm = externalFormWithoutParameters;
-      }
-    }
-    else {
-      if (parameters != null) {
-        result += parameters;
-      }
-      externalForm = result;
-    }
-    return result;
-  }
-
-  @NotNull
-  @Override
-  public String toExternalForm() {
-    return toExternalForm(false);
-  }
-
-  @Override
-  public String toString() {
-    return toExternalForm(false);
-  }
-
-  @Override
-  public boolean equals(Object o) {
-    if (this == o) {
-      return true;
-    }
-    if (!(o instanceof UrlImpl)) {
-      return false;
-    }
-
-    UrlImpl url = (UrlImpl)o;
-    return equalsIgnoreParameters(url) && (parameters == null ? url.parameters == null : parameters.equals(url.parameters));
-  }
-
-  @Override
-  public boolean equalsIgnoreParameters(@Nullable Url o) {
-    if (this == o) {
-      return true;
-    }
-    if (!(o instanceof UrlImpl)) {
-      if (o instanceof LocalFileUrl && isInLocalFileSystem()) {
-        return o.getPath().equals(path);
-      }
-      return false;
-    }
-
-    UrlImpl url = (UrlImpl)o;
-    if (scheme == null ? url.scheme == null : !scheme.equals(url.scheme)) {
-      return false;
-    }
-    if (authority == null ? url.authority != null : !authority.equals(url.authority)) {
-      return false;
-    }
-    String decodedPath = getPath();
-    if (!decodedPath.equals(url.getPath())) {
-      return false;
-    }
-    return true;
-  }
-
-  @Override
-  public int hashCode() {
-    int result = scheme == null ? 0 : scheme.hashCode();
-    result = 31 * result + (authority != null ? authority.hashCode() : 0);
-    String decodedPath = getPath();
-    result = 31 * result + decodedPath.hashCode();
-    result = 31 * result + (parameters != null ? parameters.hashCode() : 0);
-    return result;
-  }
-}
\ No newline at end of file
diff --git a/xml/impl/src/com/intellij/ide/browsers/Urls.java b/xml/impl/src/com/intellij/ide/browsers/Urls.java
deleted file mode 100644
index 2431205..0000000
--- a/xml/impl/src/com/intellij/ide/browsers/Urls.java
+++ /dev/null
@@ -1,142 +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.ide.browsers;
-
-import com.google.common.base.CharMatcher;
-import com.intellij.openapi.diagnostic.Logger;
-import com.intellij.openapi.util.io.FileUtil;
-import com.intellij.openapi.util.text.StringUtil;
-import com.intellij.openapi.vfs.StandardFileSystems;
-import com.intellij.openapi.vfs.VfsUtilCore;
-import com.intellij.openapi.vfs.VirtualFile;
-import com.intellij.util.io.URLUtil;
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.net.URI;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-// We don't use Java URI due to problem — http://cns-etuat-2.localnet.englishtown.com/school/e12/#school/45383/201/221/382?c=countrycode=cc|culturecode=en-us|partnercode=mkge
-// it is illegal URI (fragment before query), but we must support such URI
-public final class Urls {
-  private static final Logger LOG = Logger.getInstance(Urls.class);
-
-  public static final CharMatcher SLASH_MATCHER = CharMatcher.is('/');
-
-  // about ";" see WEB-100359
-  private static final Pattern URI_PATTERN = Pattern.compile("^([^:/?#]+)://([^/?#]*)([^?#;]*)(.*)");
-
-  @NotNull
-  public static Url newFromEncoded(@NotNull String url) {
-    Url result = parse(url, true);
-    LOG.assertTrue(result != null);
-    return result;
-  }
-
-  @NotNull
-  public static Url newHttpUrl(@Nullable String authority, @Nullable String path) {
-    return new UrlImpl("http", authority, path);
-  }
-
-  // java.net.URI.create cannot parse "file:///Test Stuff" - but you don't need to worry about it - this method is aware
-  @Nullable
-  public static Url newFromIdea(@NotNull String url) {
-    return URLUtil.containsScheme(url) ? parseUrl(url) : new LocalFileUrl(url);
-  }
-
-  @Nullable
-  public static Url parse(@NotNull String url, boolean asLocalIfNoScheme) {
-    if (asLocalIfNoScheme && !URLUtil.containsScheme(url)) {
-      // nodejs debug — files only in local filesystem
-      return new LocalFileUrl(url);
-    }
-    return parseUrl(VfsUtilCore.toIdeaUrl(url));
-  }
-
-  @Nullable
-  public static URI parseAsJavaUriWithoutParameters(@NotNull String url) {
-    Url asUrl = parseUrl(url);
-    if (asUrl == null) {
-      return null;
-    }
-
-    try {
-      return asUrl.toJavaUriWithoutParameters();
-    }
-    catch (Exception e) {
-      LOG.info("Can't parse " + url, e);
-      return null;
-    }
-  }
-
-  @Nullable
-  private static Url parseUrl(@NotNull String url) {
-    String urlToParse;
-    if (url.startsWith("jar:file://")) {
-      urlToParse = url.substring("jar:".length());
-    }
-    else {
-      urlToParse = url;
-    }
-
-    Matcher matcher = URI_PATTERN.matcher(urlToParse);
-    if (!matcher.matches()) {
-      LOG.warn("Cannot parse url " + url);
-      return null;
-    }
-    String scheme = matcher.group(1);
-    if (urlToParse != url) {
-      scheme = "jar:" + scheme;
-    }
-
-    String authority = StringUtil.nullize(matcher.group(2));
-
-    String path = StringUtil.nullize(matcher.group(3));
-    if (path != null) {
-      path = FileUtil.toCanonicalUriPath(path);
-    }
-
-    String parameters = matcher.group(4);
-    if (authority != null && StandardFileSystems.FILE_PROTOCOL.equals(scheme)) {
-      path = path == null ? authority : (authority + path);
-      authority = null;
-    }
-    return new UrlImpl(scheme, authority, path, parameters);
-  }
-
-  // must not be used in NodeJS
-  public static Url newFromVirtualFile(@NotNull VirtualFile file) {
-    if (file.isInLocalFileSystem()) {
-      return new UrlImpl(file.getFileSystem().getProtocol(), null, file.getPath());
-    }
-    else {
-      return parseUrl(file.getUrl());
-    }
-  }
-
-  public static boolean equalsIgnoreParameters(@NotNull Url url, @NotNull VirtualFile file) {
-    if (file.isInLocalFileSystem()) {
-      return url.isInLocalFileSystem() && url.getPath().equals(file.getPath());
-    }
-    else if (url.isInLocalFileSystem()) {
-      return false;
-    }
-
-    Url fileUrl = parseUrl(file.getUrl());
-    return fileUrl != null && fileUrl.equalsIgnoreParameters(url);
-  }
-}
\ No newline at end of file
diff --git a/xml/impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.java b/xml/impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.java
index af7eb2e..6cba9ab 100644
--- a/xml/impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.java
+++ b/xml/impl/src/com/intellij/ide/browsers/impl/WebBrowserServiceImpl.java
@@ -15,8 +15,6 @@
  */
 package com.intellij.ide.browsers.impl;
 
-import com.intellij.ide.browsers.Url;
-import com.intellij.ide.browsers.Urls;
 import com.intellij.ide.browsers.WebBrowserService;
 import com.intellij.ide.browsers.WebBrowserUrlProvider;
 import com.intellij.openapi.project.DumbService;
@@ -27,11 +25,14 @@
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
 import com.intellij.testFramework.LightVirtualFile;
+import com.intellij.util.Url;
+import com.intellij.util.Urls;
 import com.intellij.util.containers.ContainerUtil;
 import com.intellij.xml.util.HtmlUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
+import java.util.Collection;
 import java.util.Collections;
 import java.util.Set;
 
@@ -46,7 +47,7 @@
 
   @NotNull
   @Override
-  public Set<Url> getUrlToOpen(@NotNull PsiElement psiElement, boolean preferLocalUrl) throws WebBrowserUrlProvider.BrowserException {
+  public Collection<Url> getUrlToOpen(@NotNull PsiElement psiElement, boolean preferLocalUrl) throws WebBrowserUrlProvider.BrowserException {
     final PsiFile psiFile = psiElement instanceof PsiFile ? (PsiFile)psiElement : psiElement.getContainingFile();
     if (psiFile == null) {
       return Collections.emptySet();
@@ -60,14 +61,14 @@
     }
 
     if (!(preferLocalUrl && HtmlUtil.isHtmlFile(psiFile))) {
-      Pair<WebBrowserUrlProvider, Set<Url>> provider = getProvider(psiElement);
+      Pair<WebBrowserUrlProvider, Collection<Url>> provider = getProvider(psiElement);
       if (provider != null) {
         if (provider.second != null) {
           return provider.second;
         }
 
         try {
-          Set<Url> urls = provider.first.getUrls(psiElement, psiFile, virtualFile);
+          Collection<Url> urls = provider.first.getUrls(psiElement, psiFile, virtualFile);
           if (!urls.isEmpty()) {
             return urls;
           }
@@ -83,17 +84,18 @@
   }
 
   @Nullable
-  public static Pair<WebBrowserUrlProvider, Set<Url>> getProvider(@Nullable PsiElement element) {
+  public static Pair<WebBrowserUrlProvider, Collection<Url>> getProvider(@Nullable PsiElement element) {
     PsiFile psiFile = element == null ? null : element.getContainingFile();
     return psiFile == null ? null : getProvider(element, psiFile);
   }
 
-  private static Pair<WebBrowserUrlProvider, Set<Url>> getProvider(PsiElement element, PsiFile psiFile) {
+  private static Pair<WebBrowserUrlProvider, Collection<Url>> getProvider(PsiElement element, PsiFile psiFile) {
     Ref<Set<Url>> result = Ref.create();
-    DumbService dumbService = DumbService.getInstance(element.getProject());
+    DumbService dumbService = DumbService.getInstance(psiFile.getProject());
     for (WebBrowserUrlProvider urlProvider : WebBrowserUrlProvider.EP_NAME.getExtensions()) {
+      //noinspection deprecation
       if ((!dumbService.isDumb() || DumbService.isDumbAware(urlProvider)) && urlProvider.canHandleElement(element, psiFile, result)) {
-        return Pair.create(urlProvider, result.get());
+        return new Pair<WebBrowserUrlProvider, Collection<Url>>(urlProvider, result.get());
       }
     }
     return null;
@@ -108,7 +110,7 @@
 
     Url url;
     try {
-      Set<Url> urls = WebBrowserService.getInstance().getUrlToOpen(sourceElement, false);
+      Collection<Url> urls = WebBrowserService.getInstance().getUrlToOpen(sourceElement, false);
       url = ContainerUtil.getFirstItem(urls);
       if (url == null) {
         return null;
diff --git a/xml/openapi/src/com/intellij/ide/browsers/Url.java b/xml/openapi/src/com/intellij/ide/browsers/Url.java
deleted file mode 100644
index 8d1efcc..0000000
--- a/xml/openapi/src/com/intellij/ide/browsers/Url.java
+++ /dev/null
@@ -1,35 +0,0 @@
-package com.intellij.ide.browsers;
-
-import org.jetbrains.annotations.NotNull;
-import org.jetbrains.annotations.Nullable;
-
-import java.net.URI;
-
-public interface Url {
-  @NotNull
-  String getPath();
-
-  boolean isInLocalFileSystem();
-
-  String toDecodedForm(boolean skipQueryAndFragment);
-
-  @NotNull
-  String toExternalForm();
-
-  @NotNull
-  String toExternalForm(boolean skipQueryAndFragment);
-
-  @Nullable
-  String getScheme();
-
-  @Nullable
-  String getAuthority();
-
-  @Nullable
-  String getParametersPart();
-
-  boolean equalsIgnoreParameters(@Nullable Url url);
-
-  @NotNull
-  URI toJavaUriWithoutParameters();
-}
diff --git a/xml/openapi/src/com/intellij/ide/browsers/WebBrowserService.java b/xml/openapi/src/com/intellij/ide/browsers/WebBrowserService.java
index 267cfd0..139d7ba 100644
--- a/xml/openapi/src/com/intellij/ide/browsers/WebBrowserService.java
+++ b/xml/openapi/src/com/intellij/ide/browsers/WebBrowserService.java
@@ -17,9 +17,10 @@
 
 import com.intellij.openapi.components.ServiceManager;
 import com.intellij.psi.PsiElement;
+import com.intellij.util.Url;
 import org.jetbrains.annotations.NotNull;
 
-import java.util.Set;
+import java.util.Collection;
 
 public abstract class WebBrowserService {
   public static WebBrowserService getInstance() {
@@ -29,5 +30,5 @@
   public abstract boolean canOpenInBrowser(@NotNull PsiElement psiElement);
 
   @NotNull
-  public abstract Set<Url> getUrlToOpen(@NotNull PsiElement psiElement, boolean preferLocalUrl) throws WebBrowserUrlProvider.BrowserException;
+  public abstract Collection<Url> getUrlToOpen(@NotNull PsiElement psiElement, boolean preferLocalUrl) throws WebBrowserUrlProvider.BrowserException;
 }
\ No newline at end of file
diff --git a/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java b/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java
index e0d0c85..6846dc8 100644
--- a/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java
+++ b/xml/openapi/src/com/intellij/ide/browsers/WebBrowserUrlProvider.java
@@ -20,14 +20,16 @@
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiElement;
 import com.intellij.psi.PsiFile;
+import com.intellij.util.Url;
+import com.intellij.util.containers.ContainerUtil;
 import org.jetbrains.annotations.NotNull;
 import org.jetbrains.annotations.Nullable;
 
-import java.util.Collections;
+import java.util.Collection;
 import java.util.Set;
 
 public abstract class WebBrowserUrlProvider {
-  public static ExtensionPointName<WebBrowserUrlProvider> EP_NAME = ExtensionPointName.create("com.intellij.webBrowserUrlProvider");
+  public static final ExtensionPointName<WebBrowserUrlProvider> EP_NAME = ExtensionPointName.create("com.intellij.webBrowserUrlProvider");
 
   /**
    * Browser exceptions are printed in Error Dialog when user presses any browser button
@@ -38,14 +40,27 @@
     }
   }
 
+  @Deprecated
+  /**
+   * @deprecated to remove in IDEA 14
+   */
   public boolean canHandleElement(@NotNull PsiElement element, @NotNull PsiFile psiFile, @NotNull Ref<Set<Url>> result) {
+    Ref<Collection<Url>> ref = Ref.create();
+    boolean canHandle = canHandle(element, psiFile, ref);
+    if (!ref.isNull()) {
+      result.set(ContainerUtil.newHashSet(ref.get()));
+    }
+    return canHandle;
+  }
+
+  public boolean canHandle(@NotNull PsiElement element, @NotNull PsiFile psiFile, @NotNull Ref<Collection<Url>> result) {
     VirtualFile file = psiFile.getVirtualFile();
     if (file == null) {
       return false;
     }
 
     try {
-      Set<Url> urls = getUrls(element, psiFile, file);
+      Collection<Url> urls = getUrls(element, psiFile, file);
       if (!urls.isEmpty()) {
         result.set(urls);
         return true;
@@ -62,9 +77,8 @@
     return null;
   }
 
-  public Set<Url> getUrls(@NotNull PsiElement element, @NotNull PsiFile psiFile, @NotNull VirtualFile virtualFile) throws BrowserException {
-    Url url = getUrl(element, psiFile, virtualFile);
-    return url == null ? Collections.<Url>emptySet() : Collections.singleton(url);
+  public Collection<Url> getUrls(@NotNull PsiElement element, @NotNull PsiFile psiFile, @NotNull VirtualFile virtualFile) throws BrowserException {
+    return ContainerUtil.createMaybeSingletonSet(getUrl(element, psiFile, virtualFile));
   }
 
   @Nullable
diff --git a/xml/tests/src/com/intellij/codeInsight/SoftWrapTest.java b/xml/tests/src/com/intellij/codeInsight/SoftWrapTest.java
new file mode 100644
index 0000000..4de8e70
--- /dev/null
+++ b/xml/tests/src/com/intellij/codeInsight/SoftWrapTest.java
@@ -0,0 +1,54 @@
+/*
+ * 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.codeInsight;
+
+import com.intellij.openapi.editor.Editor;
+import com.intellij.openapi.editor.impl.SoftWrapModelImpl;
+import com.intellij.openapi.editor.impl.softwrap.mapping.SoftWrapApplianceManager;
+import com.intellij.testFramework.fixtures.LightPlatformCodeInsightFixtureTestCase;
+
+/**
+ * @author Dmitry Avdeev
+ *         Date: 25.11.13
+ */
+public class SoftWrapTest extends LightPlatformCodeInsightFixtureTestCase {
+
+  public void testSoftWrapInInjection() throws Exception {
+
+    myFixture.configureByFile("softWrap.html");
+    Editor editor = myFixture.getEditor();
+    editor.getSettings().setUseSoftWraps(true);
+    ((SoftWrapModelImpl)editor.getSoftWrapModel()).getApplianceManager().setWidthProvider(new SoftWrapApplianceManager.VisibleAreaWidthProvider() {
+      @Override
+      public int getVisibleAreaWidth() {
+        return 600;
+      }
+    });
+
+    myFixture.type('j');
+    myFixture.checkResultByFile("softWrap_after.html");
+  }
+
+  @Override
+  protected String getBasePath() {
+    return "/xml/tests/testData/softWrap";
+  }
+
+  @Override
+  protected boolean isCommunity() {
+    return true;
+  }
+}
diff --git a/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java b/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java
index b0a6380..1edf485 100644
--- a/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java
+++ b/xml/tests/src/com/intellij/xml/index/XmlSchemaIndexTest.java
@@ -94,14 +94,14 @@
     assertEquals(2, files.size());
 
     IndexedRelevantResource<String, XsdNamespaceBuilder>
-      resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "3.0", myModule);
+      resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "3.0", myModule, getProject());
     assertNotNull(resource);
     XsdNamespaceBuilder builder = resource.getValue();
     assertEquals(NS, builder.getNamespace());
     assertEquals("3.0", builder.getVersion());
     assertEquals(Arrays.asList("web-app"), builder.getTags());
 
-    resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "2.5", myModule);
+    resource = XmlNamespaceIndex.guessSchema(NS, "web-app", "2.5", myModule, getProject());
     assertNotNull(resource);
     builder = resource.getValue();
     assertEquals(NS, builder.getNamespace());
diff --git a/xml/tests/testData/softWrap/softWrap.html b/xml/tests/testData/softWrap/softWrap.html
new file mode 100644
index 0000000..dfddbbf
--- /dev/null
+++ b/xml/tests/testData/softWrap/softWrap.html
@@ -0,0 +1,12 @@
+<!-- -->
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+    <!--[if IE]>
+    <link rel="stylesheet" href="<caret>" type="text/css" media="all"/>
+    <![endif]-->
+</head>
+
+<body></body>
+
+</html>
\ No newline at end of file
diff --git a/xml/tests/testData/softWrap/softWrap_after.html b/xml/tests/testData/softWrap/softWrap_after.html
new file mode 100644
index 0000000..7d5c77a
--- /dev/null
+++ b/xml/tests/testData/softWrap/softWrap_after.html
@@ -0,0 +1,12 @@
+<!-- -->
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
+<html xmlns="http://www.w3.org/1999/xhtml">
+<head>
+    <!--[if IE]>
+    <link rel="stylesheet" href="j<caret>" type="text/css" media="all"/>
+    <![endif]-->
+</head>
+
+<body></body>
+
+</html>
\ No newline at end of file
diff --git a/xml/xml-psi-api/src/com/intellij/javaee/UriUtil.java b/xml/xml-psi-api/src/com/intellij/javaee/UriUtil.java
index c9d9180..c2dd559 100644
--- a/xml/xml-psi-api/src/com/intellij/javaee/UriUtil.java
+++ b/xml/xml-psi-api/src/com/intellij/javaee/UriUtil.java
@@ -19,6 +19,7 @@
  */
 package com.intellij.javaee;
 
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.VfsUtilCore;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.psi.PsiFileSystemItem;
@@ -40,4 +41,10 @@
     String location = ExternalResourceManager.getInstance().getResourceLocation(uri, base.getProject());
     return VfsUtilCore.findRelativeFile(location, base.getVirtualFile());
   }
+
+  // cannot use UriUtil.SLASH_MATCHER.trimFrom - we don't depend on guava
+  @NotNull
+  public static String trimSlashFrom(@NotNull String path) {
+    return StringUtil.trimStart(StringUtil.trimEnd(path, "/"), "/");
+  }
 }
\ No newline at end of file
diff --git a/xml/xml-psi-impl/src/com/intellij/ide/highlighter/HtmlFileType.java b/xml/xml-psi-impl/src/com/intellij/ide/highlighter/HtmlFileType.java
index 9341d99..ca24a52 100644
--- a/xml/xml-psi-impl/src/com/intellij/ide/highlighter/HtmlFileType.java
+++ b/xml/xml-psi-impl/src/com/intellij/ide/highlighter/HtmlFileType.java
@@ -79,7 +79,7 @@
     catch (UnsupportedEncodingException e) {
       return null;
     }
-    Charset c = HtmlUtil.detectCharsetFromMetaHttpEquiv(strContent);
+    Charset c = HtmlUtil.detectCharsetFromMetaTag(strContent);
     return c == null ? null : c.name();
   }
 
@@ -91,6 +91,6 @@
     if (charset != null) {
       return charset;
     }
-    return HtmlUtil.detectCharsetFromMetaHttpEquiv(content);
+    return HtmlUtil.detectCharsetFromMetaTag(content);
   }
 }
diff --git a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java
index c0c22c6..1c33789 100644
--- a/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java
+++ b/xml/xml-psi-impl/src/com/intellij/psi/impl/source/xml/XmlTagImpl.java
@@ -56,8 +56,8 @@
 import com.intellij.xml.XmlElementDescriptor;
 import com.intellij.xml.XmlExtension;
 import com.intellij.xml.XmlNSDescriptor;
-import com.intellij.xml.impl.dtd.XmlNSDescriptorImpl;
 import com.intellij.xml.impl.schema.AnyXmlElementDescriptor;
+import com.intellij.xml.impl.schema.XmlNSDescriptorImpl;
 import com.intellij.xml.index.XmlNamespaceIndex;
 import com.intellij.xml.util.XmlTagUtil;
 import com.intellij.xml.util.XmlUtil;
@@ -361,7 +361,7 @@
             }
 
             // We want to get fixed xmlns attr from dtd and check its default with requested namespace
-            if (descriptor instanceof XmlNSDescriptorImpl) {
+            if (descriptor instanceof com.intellij.xml.impl.dtd.XmlNSDescriptorImpl) {
               final XmlElementDescriptor elementDescriptor = descriptor.getElementDescriptor(XmlTagImpl.this);
               if (elementDescriptor != null) {
                 final XmlAttributeDescriptor attributeDescriptor = elementDescriptor.getAttributeDescriptor("xmlns", XmlTagImpl.this);
@@ -910,6 +910,17 @@
     if (XmlUtil.XHTML_URI.equals(ns)) {
       return XmlUtil.getDefaultXhtmlNamespace(getProject());
     }
+    if (XmlNSDescriptorImpl.equalsToSchemaName(this, XmlNSDescriptorImpl.SCHEMA_TAG_NAME)) {
+      for (XmlTag subTag : getSubTags()) {
+        if (XmlNSDescriptorImpl.equalsToSchemaName(subTag, XmlNSDescriptorImpl.IMPORT_TAG_NAME) &&
+            ns.equals(subTag.getAttributeValue("namespace"))) {
+          String location = subTag.getAttributeValue("schemaLocation");
+          if (location != null) {
+            return location;
+          }
+        }
+      }
+    }
     return ns;
   }
 
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java b/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java
index 748d597..36ae151 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/impl/schema/XmlNSDescriptorImpl.java
@@ -69,9 +69,9 @@
   @NonNls static final String ATTRIBUTE_TAG_NAME = "attribute";
   @NonNls static final String COMPLEX_TYPE_TAG_NAME = "complexType";
   @NonNls static final String SEQUENCE_TAG_NAME = "sequence";
-  @NonNls static final String SCHEMA_TAG_NAME = "schema";
+  @NonNls public static final String SCHEMA_TAG_NAME = "schema";
   @NonNls private static final String INCLUDE_TAG_NAME = "include";
-  @NonNls private static final String IMPORT_TAG_NAME = "import";
+  @NonNls public static final String IMPORT_TAG_NAME = "import";
   @NonNls private static final String REDEFINE_TAG_NAME = "redefine";
 
   public XmlNSDescriptorImpl(XmlFile file) {
@@ -758,7 +758,7 @@
     return true;
   }
 
-  protected static boolean equalsToSchemaName(@NotNull XmlTag tag, @NonNls String schemaName) {
+  public static boolean equalsToSchemaName(@NotNull XmlTag tag, @NonNls String schemaName) {
     return schemaName.equals(tag.getLocalName()) && checkSchemaNamespace(tag);
   }
 
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/index/IndexedRelevantResource.java b/xml/xml-psi-impl/src/com/intellij/xml/index/IndexedRelevantResource.java
index 5b62a6a..9005a94 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/index/IndexedRelevantResource.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/index/IndexedRelevantResource.java
@@ -50,9 +50,7 @@
     FileBasedIndex.getInstance().processValues(indexId, key, null, new FileBasedIndex.ValueProcessor<V>() {
       public boolean process(VirtualFile file, V value) {
         ResourceRelevance relevance = ResourceRelevance.getRelevance(file, module, fileIndex, additionalScope);
-        if (relevance != ResourceRelevance.NONE) {
-          resources.add(new IndexedRelevantResource<K, V>(file, key, value, relevance));
-        }
+        resources.add(new IndexedRelevantResource<K, V>(file, key, value, relevance));
         return true;
       }
     }, new AdditionalIndexedRootsScope(GlobalSearchScope.allScope(project)));
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/index/ResourceRelevance.java b/xml/xml-psi-impl/src/com/intellij/xml/index/ResourceRelevance.java
index ffa06cd..a20842b 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/index/ResourceRelevance.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/index/ResourceRelevance.java
@@ -28,7 +28,6 @@
  */
 public enum ResourceRelevance {
 
-  NONE,
   STANDARD,
   LIBRARY,
   SOURCE,
@@ -55,12 +54,6 @@
       return LIBRARY;
     }
     ExternalResourceManagerEx resourceManager = (ExternalResourceManagerEx)ExternalResourceManager.getInstance();
-    if (resourceManager.isUserResource(resource)) {
-      return MAPPED;
-    }
-    if (resourceManager.isStandardResource(resource)) {
-      return STANDARD;
-    }
-    return NONE;
+    return resourceManager.isUserResource(resource) ? MAPPED : STANDARD;
   }
 }
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java b/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java
index 4806b87..55cde70 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/index/XmlNamespaceIndex.java
@@ -142,11 +142,9 @@
   public static IndexedRelevantResource<String, XsdNamespaceBuilder> guessSchema(String namespace,
                                                                                  @Nullable final String tagName,
                                                                                  @Nullable final String version,
-                                                                                 @Nullable Module module) {
+                                                                                 @Nullable Module module,
+                                                                                 @NotNull Project project) {
 
-    if (module == null) return null;
-
-    Project project = module.getProject();
     final List<IndexedRelevantResource<String, XsdNamespaceBuilder>>
       resources = getResourcesByNamespace(namespace, project, module);
 
@@ -157,9 +155,8 @@
         @Override
         public int compare(IndexedRelevantResource<String, XsdNamespaceBuilder> o1,
                            IndexedRelevantResource<String, XsdNamespaceBuilder> o2) {
-
-          int i = o1.getValue().getRating(tagName, version) - o2.getValue().getRating(tagName, version);
-          return i == 0 ? o1.compareTo(o2) : i;
+          int i = o1.compareTo(o2);
+          return i == 0 ? o1.getValue().getRating(tagName, version) - o2.getValue().getRating(tagName, version) : i;
         }
       });
   }
@@ -173,7 +170,7 @@
     if (DumbService.isDumb(file.getProject()) || XmlUtil.isStubBuilding()) return null;
 
     IndexedRelevantResource<String,XsdNamespaceBuilder> resource =
-      guessSchema(namespace, tagName, version, ModuleUtilCore.findModuleForPsiElement(file));
+      guessSchema(namespace, tagName, version, ModuleUtilCore.findModuleForPsiElement(file), file.getProject());
     if (resource == null) return null;
     return findSchemaFile(resource.getFile(), file);
   }
diff --git a/xml/xml-psi-impl/src/com/intellij/xml/util/HtmlUtil.java b/xml/xml-psi-impl/src/com/intellij/xml/util/HtmlUtil.java
index aee38e0..be744f3 100644
--- a/xml/xml-psi-impl/src/com/intellij/xml/util/HtmlUtil.java
+++ b/xml/xml-psi-impl/src/com/intellij/xml/util/HtmlUtil.java
@@ -27,6 +27,7 @@
 import com.intellij.openapi.diagnostic.Logger;
 import com.intellij.openapi.fileTypes.FileType;
 import com.intellij.openapi.util.Ref;
+import com.intellij.openapi.util.text.StringUtil;
 import com.intellij.openapi.vfs.CharsetToolkit;
 import com.intellij.openapi.vfs.VirtualFile;
 import com.intellij.profile.codeInspection.InspectionProjectProfileManager;
@@ -65,7 +66,8 @@
   private static final Logger LOG = Logger.getInstance("#com.intellij.xml.util.HtmlUtil");
 
   @NonNls private static final String JSFC = "jsfc";
-  @NonNls private static final String CHARSET_PREFIX = "charset=";
+  @NonNls private static final String CHARSET = "charset";
+  @NonNls private static final String CHARSET_PREFIX = CHARSET+"=";
   @NonNls private static final String HTML5_DATA_ATTR_PREFIX = "data-";
 
   public static final String[] CONTENT_TYPES =
@@ -443,12 +445,24 @@
     private static final TerminateException INSTANCE = new TerminateException();
   }
 
-  public static Charset detectCharsetFromMetaHttpEquiv(@NotNull String content) {
+  public static Charset detectCharsetFromMetaTag(@NotNull String content) {
+    // check for <meta http-equiv="charset=CharsetName" > or <meta charset="CharsetName"> and return Charset
+    // because we will lightly parse and explicit charset isn't used very often do quick check for applicability
+    int charPrefix = content.indexOf(CHARSET);
+    do {
+      if (charPrefix == -1) return null;
+      int charsetPrefixEnd = charPrefix + CHARSET.length();
+      while (charsetPrefixEnd < content.length() && Character.isWhitespace(content.charAt(charsetPrefixEnd))) ++charsetPrefixEnd;
+      if (charsetPrefixEnd < content.length() && content.charAt(charsetPrefixEnd) == '=') break;
+      charPrefix = content.indexOf(CHARSET, charsetPrefixEnd);
+    } while(true);
+
     final Ref<String> charsetNameRef = new Ref<String>();
     try {
       new HtmlBuilderDriver(content).build(new XmlBuilder() {
         @NonNls final Set<String> inTag = new THashSet<String>();
         boolean metHttpEquiv = false;
+        boolean metHttml5Charset = false;
 
         @Override
         public void doctype(@Nullable final CharSequence publicId,
@@ -473,13 +487,18 @@
         @Override
         public void endTag(final CharSequence localName, final String namespace, final int startoffset, final int endoffset) {
           @NonNls final String name = localName.toString().toLowerCase();
-          if ("meta".equals(name) && metHttpEquiv && contentAttributeValue != null) {
-            int start = contentAttributeValue.indexOf(CHARSET_PREFIX);
-            if (start == -1) return;
-            start += CHARSET_PREFIX.length();
-            int end = contentAttributeValue.indexOf(';', start);
-            if (end == -1) end = contentAttributeValue.length();
-            String charsetName = contentAttributeValue.substring(start, end);
+          if ("meta".equals(name) && (metHttpEquiv || metHttml5Charset) && contentAttributeValue != null) {
+            String charsetName = null;
+            if (metHttpEquiv) {
+              int start = contentAttributeValue.indexOf(CHARSET_PREFIX);
+              if (start == -1) return;
+              start += CHARSET_PREFIX.length();
+              int end = contentAttributeValue.indexOf(';', start);
+              if (end == -1) end = contentAttributeValue.length();
+              charsetName = contentAttributeValue.substring(start, end);
+            } else /*if (metHttml5Charset) */ {
+              charsetName = StringUtil.stripQuotesAroundValue(contentAttributeValue);
+            }
             charsetNameRef.set(charsetName);
             terminate();
           }
@@ -488,6 +507,7 @@
           }
           inTag.remove(name);
           metHttpEquiv = false;
+          metHttml5Charset = false;
           contentAttributeValue = null;
         }
 
@@ -500,6 +520,9 @@
             @NonNls String value = v.toString().toLowerCase();
             if (name.equals("http-equiv")) {
               metHttpEquiv |= value.equals("content-type");
+            } else if (name.equals(CHARSET)) {
+              metHttml5Charset = true;
+              contentAttributeValue = value;
             }
             if (name.equals("content")) {
               contentAttributeValue = value;