diff --git a/includes/mail.inc b/includes/mail.inc
index be2df92..3b63459 100644
--- a/includes/mail.inc
+++ b/includes/mail.inc
@@ -267,7 +267,7 @@ interface MailSystemInterface {
    * @return
    *   The formatted $message.
    */
-   public function format(array $message);
+  public function format(array $message);
 
   /**
    * Send a message composed by drupal_mail().
@@ -294,7 +294,7 @@ interface MailSystemInterface {
    * @return
    *   TRUE if the mail was successfully accepted for delivery, otherwise FALSE.
    */
-   public function mail(array $message);
+  public function mail(array $message);
 }
 
 /**
@@ -303,39 +303,41 @@ interface MailSystemInterface {
  * We use delsp=yes wrapping, but only break non-spaced languages when
  * absolutely necessary to avoid compatibility issues.
  *
- * We deliberately use LF rather than CRLF, see drupal_mail().
+ * We deliberately use MAIL_LINE_ENDINGS rather than CRLF.
  *
  * @param $text
  *   The plain text to process.
  * @param $indent (optional)
  *   A string to indent the text with. Only '>' characters are repeated on
  *   subsequent wrapped lines. Others are replaced by spaces.
+ *
+ * @see drupal_mail()
  */
 function drupal_wrap_mail($text, $indent = '') {
-  // Convert CRLF into LF.
-  $text = str_replace("\r", '', $text);
+  // Convert CRLF into MAIL_LINE_ENDINGS.
+  $text = preg_replace('/\r?\n/', MAIL_LINE_ENDINGS, $text);
   // See if soft-wrapping is allowed.
   $clean_indent = _drupal_html_to_text_clean($indent);
   $soft = strpos($clean_indent, ' ') === FALSE;
   // Check if the string has line breaks.
-  if (strpos($text, "\n") !== FALSE) {
+  if (strpos($text, MAIL_LINE_ENDINGS) !== FALSE) {
     // Remove trailing spaces to make existing breaks hard.
-    $text = preg_replace('/ +\n/m', "\n", $text);
+    $text = preg_replace('/ +\r?\n/m', MAIL_LINE_ENDINGS, $text);
     // Wrap each line at the needed width.
-    $lines = explode("\n", $text);
-    array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent)));
-    $text = implode("\n", $lines);
+    $lines = explode(MAIL_LINE_ENDINGS, $text);
+    array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => drupal_strlen($indent)));
+    $text = implode(MAIL_LINE_ENDINGS, $lines);
   }
   else {
     // Wrap this line.
-    _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => strlen($indent)));
+    _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => drupal_strlen($indent)));
   }
   // Empty lines with nothing but spaces.
-  $text = preg_replace('/^ +\n/m', "\n", $text);
+  $text = preg_replace('/^ +\r?\n/m', MAIL_LINE_ENDINGS, $text);
   // Space-stuff special lines.
-  $text = preg_replace('/^(>| |From)/m', ' $1', $text);
+  $text = preg_replace('/^(>|From)/m', ' $1', $text);
   // Apply indentation. We only include non-'>' indentation on the first line.
-  $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
+  $text = $indent . drupal_substr(preg_replace('/^/m', $clean_indent, $text), drupal_strlen($indent));
 
   return $text;
 }
@@ -347,11 +349,18 @@ function drupal_wrap_mail($text, $indent = '') {
  * The output will be suitable for use as 'format=flowed; delsp=yes' text
  * (RFC 3676) and can be passed directly to drupal_mail() for sending.
  *
- * We deliberately use LF rather than CRLF, see drupal_mail().
+ * We deliberately use MAIL_LINE_ENDINGS rather than CRLF.
  *
  * This function provides suitable alternatives for the following tags:
- * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
- * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
+ *
+ * <a> <address> <b> <blockquote> <br /> <dd> <dl> <dt> <em>
+ * <h1> <h2> <h3> <h4> <h5> <h6> <hr /> <i> <li> <ol> <p> <pre> <strong> <ul>
+ *
+ * The following tags are also handled:
+ *
+ * <del> <div> <ins> <tr>: Rendered the same as a <p> tag.
+ *
+ * <td>: A space is inserted between adjacent table cells.
  *
  * @param $string
  *   The string to be transformed.
@@ -361,12 +370,18 @@ function drupal_wrap_mail($text, $indent = '') {
  *
  * @return
  *   The transformed string.
+ *
+ * @see drupal_mail()
  */
 function drupal_html_to_text($string, $allowed_tags = NULL) {
   // Cache list of supported tags.
   static $supported_tags;
   if (empty($supported_tags)) {
-    $supported_tags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p', 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr');
+    $supported_tags = array(
+      'a', 'address', 'b', 'blockquote', 'br', 'dd', 'del', 'div', 'dl', 'dt',
+      'em', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'ins', 'li', 'ol',
+      'p', 'pre', 'strong', 'td', 'tr', 'ul',
+    );
   }
 
   // Make sure only supported tags are kept.
@@ -374,11 +389,13 @@ function drupal_html_to_text($string, $allowed_tags = NULL) {
 
   // Make sure tags, entities and attributes are well-formed and properly nested.
   $string = _filter_htmlcorrector(filter_xss($string, $allowed_tags));
-
   // Apply inline styles.
   $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
   $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
 
+  // Separate adjacent table cells.
+  $string = preg_replace('!(</td>)?<td>!i', ' ', $string);
+
   // Replace inline <a> tags with the text of link and a footnote.
   // 'See <a href="http://drupal.org">the Drupal site</a>' becomes
   // 'See the Drupal site [1]' with the URL included as a footnote.
@@ -388,9 +405,9 @@ function drupal_html_to_text($string, $allowed_tags = NULL) {
   $urls = _drupal_html_to_mail_urls();
   $footnotes = '';
   if (count($urls)) {
-    $footnotes .= "\n";
+    $footnotes .= MAIL_LINE_ENDINGS;
     for ($i = 0, $max = count($urls); $i < $max; $i++) {
-      $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
+      $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . MAIL_LINE_ENDINGS;
     }
   }
 
@@ -399,125 +416,215 @@ function drupal_html_to_text($string, $allowed_tags = NULL) {
   // Note: PHP ensures the array consists of alternating delimiters and literals
   // and begins and ends with a literal (inserting $null as required).
 
-  $tag = FALSE; // Odd/even counter (tag or no tag)
-  $casing = NULL; // Case conversion function
+  $tag = FALSE; // Odd/even counter (tag or no tag).
+  $value = ''; // Holds a tag's value. Necessary to allow a closing tag to change its behaviour based on contents.
+  $casing = NULL; // Case conversion function.
+  $pre = 0; // Counter for <pre> tags.
   $output = '';
-  $indent = array(); // All current indentation string chunks
-  $lists = array(); // Array of counters for opened lists
-  foreach ($split as $value) {
+  $indent = array(); // All current indentation string chunks.
+  $lists = array(); // Array of counters for opened lists. This gets a '*' for each ul and an integer for each ol.
+  foreach ($split as $item) {
     $chunk = NULL; // Holds a string ready to be formatted and output.
 
-    // Process HTML tags (but don't output any literally).
+    // Process HTML tags.
     if ($tag) {
-      list($tagname) = explode(' ', strtolower($value), 2);
+      list($tagname) = explode(' ', drupal_strtolower($item), 2);
       switch ($tagname) {
-        // List counters
+
+        // Lists.
         case 'ul':
           array_unshift($lists, '*');
+          if (count($lists) == 1) {
+            // No line break when nested.
+            $chunk = MAIL_LINE_ENDINGS;
+          }
           break;
         case 'ol':
-          array_unshift($lists, 1);
+          // Support start attribute.
+          if (preg_match('/\bstart\s*=\s*([\'"]?)([0-9]+)\b/i', $item, $matches)) {
+            array_unshift($lists, $matches[2]);
+          }
+          else {
+            array_unshift($lists, 1);
+          }
+          if (count($lists) == 1) {
+            // No line break when nested.
+            $chunk = MAIL_LINE_ENDINGS;
+          }
+          break;
+        case 'dl':
+          array_unshift($lists, ' ');
+          if (count($lists) == 1) {
+            // No line break when nested.
+            $chunk = MAIL_LINE_ENDINGS;
+          }
           break;
         case '/ul':
         case '/ol':
+        case '/dl':
           array_shift($lists);
-          $chunk = ''; // Ensure blank new-line.
           break;
 
-        // Quotation/list markers, non-fancy headers
-        case 'blockquote':
-          // Format=flowed indentation cannot be mixed with lists.
-          $indent[] = count($lists) ? ' "' : '>';
-          break;
+        // List items.
         case 'li':
-          $indent[] = is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
+          if (isset($lists[0]) && is_numeric($lists[0])) {
+            $inc = ' ';
+            // Support value attribute.
+            if (preg_match('/\bvalue\s*=\s*([\'"]?)([0-9]+)\b/i', $item, $matches)) {
+              $inc .= $matches[2];
+              $lists[0] = $matches[2] + 1;
+            }
+            else {
+              $inc .= $lists[0]++;
+            }
+            $indent[] = $inc . ') ';
+          }
+          else {
+            $indent[] = ' * ';
+          }
+          break;
+        case 'dt':
+          $indent[] = '';
           break;
         case 'dd':
           $indent[] = '    ';
           break;
-        case 'h3':
-          $indent[] = '.... ';
-          break;
-        case 'h4':
-          $indent[] = '.. ';
-          break;
-        case '/blockquote':
-          if (count($lists)) {
-            // Append closing quote for inline quotes (immediately).
-            $output = rtrim($output, "> \n") . "\"\n";
-            $chunk = ''; // Ensure blank new-line.
-          }
-          // Fall-through
         case '/li':
+        case '/dt':
         case '/dd':
           array_pop($indent);
-          break;
-        case '/h3':
-        case '/h4':
-          array_pop($indent);
-        case '/h5':
-        case '/h6':
-          $chunk = ''; // Ensure blank new-line.
+          if ($value) {
+            // Only have new line if the list item had a value (as opposed to containing another list).
+            $chunk = MAIL_LINE_ENDINGS;
+          }
           break;
 
-        // Fancy headers
+        // Headers
         case 'h1':
-          $indent[] = '======== ';
-          $casing = 'drupal_strtoupper';
-          break;
         case 'h2':
-          $indent[] = '-------- ';
+          $indent[] = ($tagname == 'h1') ? '======== ' : '-------- ';
           $casing = 'drupal_strtoupper';
+          $chunk = MAIL_LINE_ENDINGS;
           break;
         case '/h1':
         case '/h2':
           $casing = NULL;
+          array_pop($indent);
           // Pad the line with dashes.
           $output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' ');
+          $chunk = MAIL_LINE_ENDINGS;
+          break;
+        case 'h3':
+          $indent[] = '.... ';
+          $chunk = MAIL_LINE_ENDINGS;
+          break;
+        case 'h4':
+          $indent[] = '.. ';
+          $chunk = MAIL_LINE_ENDINGS;
+          break;
+        case '/h3':
+        case '/h4':
           array_pop($indent);
-          $chunk = ''; // Ensure blank new-line.
+          $chunk = MAIL_LINE_ENDINGS;
           break;
 
-        // Horizontal rulers
+        // Horizontal rulers.
         case 'hr':
-          // Insert immediately.
-          $output .= drupal_wrap_mail('', implode('', $indent)) . "\n";
-          $output = _drupal_html_to_text_pad($output, '-');
+          $chunk = MAIL_LINE_ENDINGS.str_repeat('-', 78).MAIL_LINE_ENDINGS;
           break;
 
-        // Paragraphs and definition lists
+        // Quotes.
+        case 'blockquote':
+          // Format=flowed indentation cannot be mixed with lists.
+          $indent[] = count($lists) ? ' "' : '> ';
+          $chunk = MAIL_LINE_ENDINGS;
+          break;
+        case '/blockquote':
+          array_pop($indent);
+          if (count($lists)) {
+            // Append closing quote for inline quotes (immediately).
+            $output = rtrim($output, "> " . MAIL_LINE_ENDINGS) . '"';
+          }
+          $chunk = MAIL_LINE_ENDINGS;
+          break;
+
+        // Preformatted plain text.
+        case 'pre':
+          if (!$pre) {
+            $chunk = MAIL_LINE_ENDINGS;
+          }
+          $pre++;
+          break;
+        case '/pre':
+          if ($pre) {
+            $pre--;
+          }
+          if (!$pre) {
+            $chunk = MAIL_LINE_ENDINGS;
+          }
+          break;
+
+        // Paragraphs and other block-level tags.
+        case 'br':
+        case 'address':
+        case 'ins':
+        case 'del':
+        case 'div':
+        case 'p':
+        case 'h5':
+        case 'h6':
+        case 'table':
+        case '/address':
+        case '/ins':
+        case '/del':
+        case '/div':
         case '/p':
-        case '/dl':
-          $chunk = ''; // Ensure blank new-line.
+        case '/tr':
+        case '/h5':
+        case '/h6':
+          $chunk = MAIL_LINE_ENDINGS;
+          break;
+
+        default:
           break;
       }
     }
-    // Process blocks of text.
+    // Process text.
     else {
-      // Convert inline HTML text to plain text; not removing line-breaks or
-      // white-space, since that breaks newlines when sanitizing plain-text.
-      $value = trim(decode_entities($value));
-      if (drupal_strlen($value)) {
-        $chunk = $value;
+      $value = decode_entities($item);
+      if ($pre) {
+        // Within <pre> tags, preserve whitespace.
+        if ($value) {
+          $chunk = $value;
+        }
+      }
+      else {
+        $value = trim($value);
+        if (drupal_strlen($value)) {
+          $chunk =  preg_replace('/\s+/', ' ', $value);
+        }
       }
     }
 
-    // See if there is something waiting to be output.
+    // See if there a chunk waiting to be output.
     if (isset($chunk)) {
       // Apply any necessary case conversion.
       if (isset($casing)) {
         $chunk = $casing($chunk);
       }
-      // Format it and apply the current indentation.
-      $output .= drupal_wrap_mail($chunk, implode('', $indent));
-      // Remove non-quotation markers from indentation.
-      $indent = array_map('_drupal_html_to_text_clean', $indent);
+      // Add chunk to output (applying wrapping and indentation).
+      if ($tag) {
+        $output .= drupal_wrap_mail($chunk); // Tags don't get indentation, their values do.
+      } else {
+        $output .= drupal_wrap_mail($chunk, implode('', $indent));
+        // Remove non-quotation markers from indentation.
+        $indent = array_map('_drupal_html_to_text_clean', $indent);
+      }
     }
 
     $tag = !$tag;
   }
-
-  return $output . $footnotes;
+  return ltrim(rtrim($output . $footnotes, " " . MAIL_LINE_ENDINGS), MAIL_LINE_ENDINGS);
 }
 
 /**
@@ -527,9 +634,9 @@ function drupal_html_to_text($string, $allowed_tags = NULL) {
  */
 function _drupal_wrap_mail_line(&$line, $key, $values) {
   // Use soft-breaks only for purely quoted or unindented text.
-  $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? "  \n" : "\n");
+  $line = wordwrap($line, 77 - $values['length'], ($values['soft'] ? ' ' : '') . MAIL_LINE_ENDINGS);
   // Break really long words at the maximum width allowed.
-  $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n");
+  $line = wordwrap($line, 996 - $values['length'], ($values['soft'] ? ' ' : '') . MAIL_LINE_ENDINGS);
 }
 
 /**
@@ -574,13 +681,11 @@ function _drupal_html_to_text_clean($indent) {
  * Pad the last line with the given character.
  */
 function _drupal_html_to_text_pad($text, $pad, $prefix = '') {
-  // Remove last line break.
-  $text = substr($text, 0, -1);
   // Calculate needed padding space and add it.
-  if (($p = strrpos($text, "\n")) === FALSE) {
+  if (($p = strrpos($text, MAIL_LINE_ENDINGS)) === FALSE) {
     $p = -1;
   }
-  $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
+  $n = max(0, 79 - (drupal_strlen($text) - $p) - drupal_strlen($prefix));
   // Add prefix and padding, and restore linebreak.
-  return $text . $prefix . str_repeat($pad, $n) . "\n";
+  return $text . $prefix . str_repeat($pad, $n);
 }
diff --git a/modules/simpletest/tests/mail.test b/modules/simpletest/tests/mail.test
index 8a7b152..156b11a 100644
--- a/modules/simpletest/tests/mail.test
+++ b/modules/simpletest/tests/mail.test
@@ -1,6 +1,7 @@
 <?php
 
 /**
+ * @file
  * Test the Drupal mailing system.
  */
 class MailTestCase extends DrupalWebTestCase implements MailSystemInterface {
@@ -43,7 +44,7 @@ class MailTestCase extends DrupalWebTestCase implements MailSystemInterface {
   /**
    * Concatenate and wrap the e-mail body for plain-text mails.
    *
-   * @see DefaultMailSystem
+   * @see DefaultMailSystem()
    */
   public function format(array $message) {
     // Join the body array into one string.
@@ -63,3 +64,197 @@ class MailTestCase extends DrupalWebTestCase implements MailSystemInterface {
   }
 }
 
+/**
+ * Unit tests for drupal_html_to_text().
+ */
+class DrupalHtmlToTextTestCase extends DrupalUnitTestCase {
+  public static function getInfo() {
+    return array(
+      'name'  => 'HTML to text conversion',
+      'description' => 'Tests drupal_html_to_text().',
+      'group' => 'Mail',
+    );
+  }
+
+  /**
+   * Test all supported tags of drupal_html_to_text().
+   */
+  function testTags() {
+    $tests = array(
+      '<a href = "http://drupal.org">Drupal.org</a>' => "Drupal.org [1]\n[1] http://drupal.org",
+      '<address>Drupal</address>' => "Drupal",
+      '<address>Drupal</address><address>Drupal</address>' => "Drupal\n\nDrupal",
+      '<b>Drupal</b>' => "*Drupal*",
+      '<blockquote>Drupal</blockquote>' => "> Drupal",
+      '<blockquote>Drupal</blockquote><blockquote>Drupal</blockquote>' => "> Drupal\n\n> Drupal",
+      '<br />Drupal<br />Drupal<br /><br />Drupal' => "Drupal\nDrupal\n\nDrupal",
+      '<br/>Drupal<br/>Drupal<br/><br/>Drupal' => "Drupal\nDrupal\n\nDrupal",
+      '<br/>Drupal<br/>Drupal<br/><br/>Drupal<p>Drupal</p>' => "Drupal\nDrupal\n\nDrupal\nDrupal",
+      '<del>Drupal</del>' => "Drupal",
+      '<del>Drupal</del><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<del>Drupal</del><del>Drupal</del>' => "Drupal\n\nDrupal",
+      '<div>Drupal</div>' => "Drupal",
+      '<div>Drupal</div><div>Drupal</div>' => "Drupal\n\nDrupal",
+      '<em>Drupal</em>' => "/Drupal/",
+      '<h1>Drupal</h1>' => "======== DRUPAL " . str_repeat('=', 62) . "",
+      '<h1>Drupal</h1><p>Drupal</p>' => "======== DRUPAL " . str_repeat('=', 62) . "\n\nDrupal",
+      '<h2>Drupal</h2>' => "-------- DRUPAL " . str_repeat('-', 62) . "",
+      '<h2>Drupal</h2><p>Drupal</p>' => "-------- DRUPAL " . str_repeat('-', 62) . "\n\nDrupal",
+      '<h3>Drupal</h3>' => ".... Drupal",
+      '<h3>Drupal</h3><p>Drupal</p>' => ".... Drupal\n\nDrupal",
+      '<h4>Drupal</h4>' => ".. Drupal",
+      '<h4>Drupal</h4><p>Drupal</p>' => ".. Drupal\n\nDrupal",
+      '<h5>Drupal</h5>' => "Drupal",
+      '<h5>Drupal</h5><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<h6>Drupal</h6>' => "Drupal",
+      '<h6>Drupal</h6><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<hr />Drupal<hr />' => str_repeat('-', 78) . "\nDrupal\n" . str_repeat('-', 78),
+      '<hr/>Drupal<hr/>' => str_repeat('-', 78) . "\nDrupal\n" . str_repeat('-', 78),
+      '<hr/>Drupal<hr/><p>Drupal</p>' => str_repeat('-', 78) . "\nDrupal\n" . str_repeat('-', 78) . "\n\nDrupal",
+      '<ins>Drupal</ins>' => "Drupal",
+      '<i>Drupal</i>' => "/Drupal/",
+      '<p>Drupal</p>' => "Drupal",
+      '<p>Drupal</p><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<pre>Drupal</pre>' => "Drupal",
+      '<pre>Drupal</pre>Drupal' => "Drupal\nDrupal",
+      '<pre>Drupal</pre><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<strong>Drupal</strong>' => "*Drupal*",
+      '<table><tr><td>Drupal</td><td>Drupal</td></tr><tr><td>Drupal</td><td>Drupal</td></tr></table>' => "Drupal Drupal\nDrupal Drupal",
+      '<table><tr><td>Drupal</td></tr></table><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<ul><li>Drupal</li></ul>' => " * Drupal",
+      '<ul><li>Drupal <em>Drupal</em> Drupal</li></ul>' => " * Drupal /Drupal/ Drupal",
+      '<ul><li>Drupal</li><li><ol><li>Drupal</li><li>Drupal</li></ol></li></ul>' => " * Drupal\n *  1) Drupal\n    2) Drupal",
+      '<ul><li>Drupal</li><li><ol><li>Drupal</li></ol></li><li>Drupal</li></ul>' => " * Drupal\n *  1) Drupal\n * Drupal",
+      '<ul><li>Drupal</li><li>Drupal</li></ul>' => " * Drupal\n * Drupal",
+      '<ul><li>Drupal</li></ul><p>Drupal</p>' => " * Drupal\n\nDrupal",
+      '<ol><li>Drupal</li></ol>' => " 1) Drupal",
+      '<ol><li>Drupal</li><li><ul><li>Drupal</li><li>Drupal</li></ul></li></ol>' => " 1) Drupal\n 2)  * Drupal\n     * Drupal",
+      '<ol><li>Drupal</li><li>Drupal</li></ol>' => " 1) Drupal\n 2) Drupal",
+      '<ol>Drupal</ol>' => "Drupal",
+      '<ol><li>Drupal</li></ol><p>Drupal</p>' => " 1) Drupal\n\nDrupal",
+      '<dl><dt>Drupal</dt></dl>' => "Drupal",
+      '<dl><dt>Drupal</dt><dd>Drupal</dd></dl>' => "Drupal\n    Drupal",
+      '<dl><dt>Drupal</dt><dd>Drupal</dd><dt>Drupal</dt><dd>Drupal</dd></dl>' => "Drupal\n    Drupal\nDrupal\n    Drupal",
+      '<dl><dt>Drupal</dt><dd>Drupal</dd></dl><p>Drupal</p>' => "Drupal\n    Drupal\n\nDrupal",
+      '<dl><dt>Drupal<dd>Drupal</dl>' => "Drupal\n    Drupal",
+      '<dl><dt>Drupal</dt></dl><p>Drupal</p>' => "Drupal\n\nDrupal",
+      '<ul><li>Drupal</li><li><dl><dt>Drupal</dt><dd>Drupal</dd><dt>Drupal</dt><dd>Drupal</dd></dl></li><li>Drupal</li></ul>' => " * Drupal\n * Drupal\n       Drupal\n   Drupal\n       Drupal\n * Drupal",
+      // Tests malformed HTML tags.
+      '<br>Drupal<br>Drupal' => "Drupal\nDrupal",
+      '<hr>Drupal<hr>Drupal' => str_repeat('-', 78) . "\nDrupal\n" . str_repeat('-', 78) . "\nDrupal",
+      '<ol><li>Drupal<li>Drupal</ol>' => " 1) Drupal\n 2) Drupal",
+      '<ul><li>Drupal <em>Drupal</em> Drupal</ul></ul>' => " * Drupal /Drupal/ Drupal",
+      '<ul><li>Drupal<li>Drupal</ol>' => " * Drupal\n * Drupal",
+      '<ul><li>Drupal<li>Drupal</ul>' => " * Drupal\n * Drupal",
+      '<ul>Drupal</ul>' => "Drupal",
+      'Drupal</ul></ol></dl><li>Drupal' => "Drupal * Drupal",
+      '<dl>Drupal</dl>' => "Drupal",
+      '<dl>Drupal</dl><p>Drupal</p>' => "Drupal\nDrupal",
+      '<dt>Drupal</dt>' => "Drupal",
+      // Tests some unsupported HTML tags.
+      '<html>Drupal</html>' => "Drupal",
+      '<script type="text/javascript">Drupal</script>' => "Drupal",
+    );
+
+    foreach ($tests as $html => $text) {
+      $result = drupal_html_to_text($html);
+      $this->assertEqual($result, $text,
+        var_export($html, TRUE)
+        . '<br />'
+        . str_replace("\n", '\n', check_plain(var_export($result, TRUE)))
+        . '<br />is equal to<br />'
+        . str_replace("\n", '\n', check_plain(var_export($text, TRUE)))
+      );
+    }
+  }
+
+  /**
+   * Test $allowed_tags argument of drupal_html_to_text().
+   */
+  function testDrupalHtmlToTextArgs() {
+    // The second parameter of drupal_html_to_text() overrules the allowed tags.
+    $result = drupal_html_to_text('Drupal <b>Drupal</b> Drupal', array('b'));
+    $this->assertEqual($result, 'Drupal *Drupal* Drupal', 'Allowed &lt;b&gt; tag found.');
+
+    $result = drupal_html_to_text('Drupal <h1>Drupal</h1> Drupal', array('b'));
+    $this->assertEqual($result, 'Drupal Drupal Drupal', 'Disallowed &lt;h1&gt; tag not found.');
+
+    $result = drupal_html_to_text('Drupal <p><em><b>Drupal</b></em><p> Drupal', array('a', 'br', 'h1'));
+    $this->assertEqual($result, 'Drupal Drupal Drupal', 'Disallowed &lt;p&gt;, &lt;em&gt;, and &lt;b&gt; tags not found.');
+
+    $result = drupal_html_to_text('<html><body>Drupal</body></html>', array('html', 'body'));
+    $this->assertEqual($result, 'Drupal', 'Unsupported &lt;html&gt; and &lt;body&gt; tags not found.');
+  }
+
+  /**
+   * Test that whitespace is collapsed, except within <pre> tags.
+   */
+  function testDrupalHtmltoTextCollapsesWhitespace() {
+    $input = "\n\n \n  \n<pre>Drupal\n\n <pre>Drupal\n\n  </pre>Drupal\n Drupal</pre>\n \n  \n\n";
+    $collapsed = "Drupal Drupal Drupal Drupal";
+    $preserved = "Drupal\n\n Drupal\n\n  Drupal\n Drupal";
+    $result = drupal_html_to_text($input, array('p'));
+    $this->assertEqual($result, $collapsed,
+      'Whitespace inside &lt;pre&gt; tags is collapsed if &lt;pre&gt; is disallowed:<br />'
+      . "<pre>$input</pre><br />becomes<br /><pre>$result</pre>"
+    );
+    $result = drupal_html_to_text($input);
+    $this->assertEqual($result, $preserved,
+      'Whitespace inside &lt;pre&gt; tags is preserved if &lt;pre&gt; is allowed:<br />'
+      . "<pre>$input</pre><br />becomes<br /><pre>$result</pre>"
+    );
+  }
+
+  /**
+   * Test that text separated by block-level tags in HTML get separated by
+   * (at least) a newline in the plaintext version.
+   */
+  function testDrupalHtmlToTextBlockTagToNewline() {
+    $input = '[text]'
+      . '<address>[address]</address>'
+      . '<blockquote>[blockquote]</blockquote>'
+      . '<br />[br]'
+      . '<del>[del]</del>'
+      . '<div>[div]</div>'
+      . '<dl><dt>[dl-dt]</dt>'
+      . '<dt>[dt]</dt>'
+      . '<dd>[dd]</dd>'
+      . '<dd>[dd-dl]</dd></dl>'
+      . '<h1>[h1]</h1>'
+      . '<h2>[h2]</h2>'
+      . '<h3>[h3]</h3>'
+      . '<h4>[h4]</h4>'
+      . '<h5>[h5]</h5>'
+      . '<h6>[h6]</h6>'
+      . '<hr />[hr]'
+      . '<ins>[ins]</ins>'
+      . '<ol><li>[ol-li]</li>'
+      . '<li>[li]</li>'
+      . '<li>[li-ol]</li></ol>'
+      . '<p>[p]</p>'
+      . '<pre>[pre]</pre>'
+      . '<table><thead><tr><td>[table-thead--tr-td]</td></tr></thead>'
+      . '<tbody><tr><td>[tbody-tr-td]</td></tr>'
+      . '<tr><td>[tr-td]</td></tr></tbody></table>'
+      . '<ul><li>[ul-li]</li>'
+      . '<li>[li-ul]</li></ul>'
+      . '[text]';
+    $output = drupal_html_to_text($input);
+    $this->assertFalse(
+      preg_match('/\][^\n]*\[/s', $output),
+      'Block-level HTML tags should force newlines: '
+      . nl2br(check_plain($output))
+    );
+    $output_upper = drupal_strtoupper($output);
+    $upper_input = drupal_strtoupper($input);
+    $upper_output = drupal_html_to_text($upper_input);
+    $this->assertEqual(
+      $upper_output,
+      $output_upper,
+      'Tag recognition should be case-insensitive:<br />'
+      . $upper_output
+      . '<br />should  be equal to <br />'
+      . $output_upper
+    );
+  }
+}
