Search code examples
emacsorg-modeorg-table

emacs org-mode: table <td> style


The default HTML table exported from org-mode has this style:

<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tom</td>
<td>Cruise</td>
</tr>

<tr>
<td>2</td>
<td>Arnold</td>
<td>Schwarzenegger</td>
</tr>

<tr>
<td>3</td>
<td>Sylvester</td>
<td>Stallone</td>
</tr>
</tbody>
</table>

Is there any way to make it more compact to be like this:

<table border="2" cellspacing="0" cellpadding="6" rules="groups" frame="hsides">
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">First Name</th>
<th scope="col">Last Name</th>
</tr>
</thead>
<tbody>
<tr><td>1</td><td>Tom</td><td>Cruise</td></tr>
<tr><td>2</td><td>Arnold</td><td>Schwarzenegger</td></tr>
<tr><td>3</td><td>Sylvester</td><td>Stallone</td></tr>
</tbody>
</table>

Since I have a very large size of table, the html file exported by the org-mode is simply too long all the way to the bottom.


Solution

  • A simple regex-replace on the html buffer does the job:

    (defun compactify-html-table ()
      (interactive)
      (goto-char (point-min))
      (while (re-search-forward "<\\(/?t[rd]\\)>\n<\\(/?t[rd]\\)>" nil t)
        (replace-match "<\\1><\\2>"))
      (goto-char (point-min))
      (while (re-search-forward "\n\n" nil t)
        (replace-match "\n")))
    

    UPD: how to apply to all open html buffers:

    (defun compactify-all-html-buffers ()
      (interactive)
      (mapc
       (lambda(b)
         (with-current-buffer b
           (when (eq major-mode 'html-mode)
             (compactify-html-table))))
       (buffer-list)))