Index: taxonomy.pages.inc
===================================================================
RCS file: /cvs/drupal/drupal/modules/taxonomy/taxonomy.pages.inc,v
retrieving revision 1.23
diff -u -p -r1.23 taxonomy.pages.inc
--- taxonomy.pages.inc	27 Jan 2009 00:22:27 -0000	1.23
+++ taxonomy.pages.inc	18 Feb 2009 01:22:20 -0000
@@ -117,27 +117,37 @@ function taxonomy_term_edit($term) {
  * Helper function for autocompletion
  */
 function taxonomy_autocomplete($vid, $string = '') {
+
+  // Return empty array if the last term is empty
+  if (preg_match('/[,\"]+$/', $string)) {
+      drupal_json(array());
+      return;
+  }
+
+  // Add closing double quote if there are an odd number of double quotes in $string.
+  if (preg_match_all('/(\")/', $string, $quotes)) {
+    if ((count($quotes[1]) % 2) != 0) {
+      $string .= '"';
+    }
+  }
+
   // The user enters a comma-separated list of tags. We only autocomplete the last tag.
   $array = drupal_explode_tags($string);
 
   // Fetch last tag
   $last_string = trim(array_pop($array));
+  
   $matches = array();
-  if ($last_string != '') {
-    $result = db_query_range(db_rewrite_sql("SELECT t.tid, t.name FROM {taxonomy_term_data} t WHERE t.vid = :vid AND LOWER(t.name) LIKE LOWER(:last_string)", 't', 'tid'), array(
-      ':vid' => $vid,
-      ':last_string' => '%'. $last_string .'%',
-    ), 0, 10);
-
-    $prefix = count($array) ? implode(', ', $array) . ', ' : '';
-
-    while ($tag = db_fetch_object($result)) {
-      $n = $tag->name;
-      // Commas and quotes in terms are special cases, so encode 'em.
-      if (strpos($tag->name, ',') !== FALSE || strpos($tag->name, '"') !== FALSE) {
-        $n = '"' . str_replace('"', '""', $tag->name) . '"';
-      }
-      $matches[$prefix . $n] = check_plain($tag->name);
+  $result = db_query_range(db_rewrite_sql("SELECT t.tid, t.name FROM {taxonomy_term_data} t WHERE t.vid = :vid AND LOWER(t.name) LIKE LOWER(:last_string)", 't', 'tid'), array(
+    ':vid' => $vid,
+    ':last_string' => '%'. $last_string .'%',
+  ), 0, 10);
+
+  while ($tag = db_fetch_object($result)) {
+    // Skip tags that would create a duplicate
+    if (array_search($tag->name, $array) === FALSE) {
+      $replacement = drupal_implode_tags(array_merge($array, array($tag->name)));
+      $matches[$replacement] = check_plain($tag->name);
     }
   }
 
