--- gtkkeyhash.c.ORIGINAL	2008-12-06 16:22:41.000000000 +0000
+++ gtkkeyhash.c	2008-12-07 00:34:46.000000000 +0000
@@ -304,6 +304,54 @@
   return g_slist_sort (slist, lookup_result_compare);
 }
 
+static gint
+lookup_result_compare_by_keyval (gconstpointer a,
+		                 gconstpointer b)
+{
+  const GtkKeyHashEntry *entry_a = a;
+  const GtkKeyHashEntry *entry_b = b;
+
+  if (entry_a->keyval < entry_b->keyval)
+	return -1;
+  else if (entry_a->keyval > entry_b->keyval)
+	return 1;
+  else
+	return 0;
+}
+
+static GSList *
+sort_lookup_results_by_keyval (GSList *slist)
+{
+  return g_slist_sort (slist, lookup_result_compare_by_keyval);
+}
+
+/* Return true if keyval is defined in keyboard group
+ */
+static gboolean 
+keyval_in_group (GdkKeymap  *keymap,
+                 guint      keyval,
+                 gint       group)
+{                 
+  GtkKeyHashEntry entry;
+  gint i;
+
+  gdk_keymap_get_entries_for_keyval (keymap,
+				     keyval,
+				     &entry.keys, &entry.n_keys);
+
+  for (i = 0; i < entry.n_keys; i++)
+    {
+      if (entry.keys[i].group == group)
+        {
+          g_free(entry.keys);
+          return TRUE;
+        }
+    }
+
+  g_free(entry.keys);
+  return FALSE;
+}
+
 /**
  * _gtk_key_hash_lookup:
  * @key_hash: a #GtkKeyHash
@@ -409,6 +457,32 @@
 	}
     }
 
+  if (!have_exact && results && getenv("GTK_IM_SEPARATE_SHORTCUTS")) 
+    {
+      /* If there are fuzzy matches, check that the current group doesn't also define 
+       * these keyvals; if yes, discard results because a widget up in the stack may have 
+       * an exact match and we don't want to 'steal' it.
+       */
+      gint oldkeyval;
+      GtkKeyHashEntry *keyhashentry;
+
+printf("%s: GTK_IM_SEPARATE_SHORTCUTS enabled, performing check.\n", __FUNCTION__);
+      results = sort_lookup_results_by_keyval (results);
+      for (l = results; l; l = l->next)
+        {
+          keyhashentry = l->data;
+          if (l == results || oldkeyval != keyhashentry->keyval)
+            {
+              oldkeyval =  keyhashentry->keyval;
+              if (keyval_in_group(key_hash->keymap, oldkeyval, group))
+                {
+       	          g_slist_free (results);
+       	          return NULL;
+                }
+            }
+        }
+    }
+    
   results = sort_lookup_results (results);
   for (l = results; l; l = l->next)
     l->data = ((GtkKeyHashEntry *)l->data)->value;
