Index: include-fixer/IncludeFixer.cpp
===================================================================
--- include-fixer/IncludeFixer.cpp
+++ include-fixer/IncludeFixer.cpp
@@ -115,6 +115,21 @@
     if (getCompilerInstance().getSema().isSFINAEContext())
       return clang::TypoCorrection();
 
+    std::string TypoScopeString;
+    if (S) {
+      // FIXME: Currently we only use namespace contexts.
+      // Use other context types for query.
+      for (const auto *Context = S->getEntity(); Context;
+           Context = Context->getParent()) {
+        if (const auto *ND = dyn_cast<NamespaceDecl>(Context)) {
+          if (!ND->getName().empty())
+            TypoScopeString = ND->getNameAsString() + "::" + TypoScopeString;
+        }
+        else
+          break;
+      }
+    }
+
     /// If we have a scope specification, use that to get more precise results.
     std::string QueryString;
     if (SS && SS->getRange().isValid()) {
@@ -144,9 +159,9 @@
       while (isIdentifierBody(*End) || *End == ':')
         ++End;
 
-      QueryString = std::string(Source.begin(), End);
+      QueryString = TypoScopeString + std::string(Source.begin(), End);
     } else {
-      QueryString = Typo.getAsString();
+      QueryString = TypoScopeString + Typo.getAsString();
     }
 
     return query(QueryString, Typo.getLoc());
Index: include-fixer/XrefsDBManager.cpp
===================================================================
--- include-fixer/XrefsDBManager.cpp
+++ include-fixer/XrefsDBManager.cpp
@@ -39,10 +39,10 @@
     if (Symbol.getName() == Names.back()) {
       bool IsMatched = true;
       auto SymbolContext = Symbol.getContexts().begin();
+      auto IdentiferContext = Names.rbegin() + 1; // Skip the name;
       // Match the remaining context names.
-      for (auto IdentiferContext = Names.rbegin() + 1;
-           IdentiferContext != Names.rend() &&
-           SymbolContext != Symbol.getContexts().end();
+      for (; IdentiferContext != Names.rend() &&
+             SymbolContext != Symbol.getContexts().end();
            ++IdentiferContext, ++SymbolContext) {
         if (SymbolContext->second != *IdentiferContext) {
           IsMatched = false;
@@ -50,7 +50,7 @@
         }
       }
 
-      if (IsMatched) {
+      if (IsMatched && IdentiferContext == Names.rend()) {
         // FIXME: file path should never be in the form of <...> or "...", but
         // the unit test with fixed database use <...> file path, which might
         // need to be changed.
Index: test/include-fixer/scoped_namespace.cpp
===================================================================
--- /dev/null
+++ test/include-fixer/scoped_namespace.cpp
@@ -0,0 +1,12 @@
+// REQUIRES: shell
+// RUN: sed -e 's#//.*$##' %s > %t.cpp
+// RUN: clang-include-fixer -db=yaml -input=%p/Inputs/fake_yaml_db.yaml %t.cpp --
+// RUN: FileCheck %s -input-file=%t.cpp
+
+// CHECK: namespace B {
+// CHECK: a::foo f;
+// CHECK: }
+
+namespace B {
+a::foo f;
+}