Emacs: HTML, Lines to Table 🚀

By Xah Lee. Date: . Last updated: .

Here's a command that turns lines into HTML table.

For example,

a b c
1 2 3

becomes a HTML table and is rendered in browser like this:

abc
123

with CSS code.

Solution

(defun xah-html-lines-to-table ()
  "Transform the current block or selection into a HTML table.
For example:

a|b|c
1|2|3

becomes

<table class=\"nrm\">
<tr><td>a</td><td>b</td><td>c</td></tr>
<tr><td>1</td><td>2</td><td>3</td></tr>
</table>

URL `http://xahlee.info/emacs/emacs/elisp_make-html-table.html'
Version: 2019-06-07 2021-12-12 2022-02-11"
  (interactive)
  (let* ((xsep (read-string "Table column separation string:" "|" nil "|"))
         (xbds (xah-get-bounds-of-thing-or-region 'block))
         (xp1 (car xbds))
         (xp2 (cdr xbds))
         (xinput (buffer-substring-no-properties xp1 xp2))
         (xlines (split-string xinput "\n" t " +"))
         (xrows
          (mapcar
           (lambda (x)
             (format "<tr><td>%s</td></tr>"
                     (mapconcat 'identity (split-string x xsep) "</td><td>")))
           xlines))
         (xresultStr
          (concat "<table class=\"nrm\">\n"
                  (mapconcat 'identity xrows "\n")
                  "\n</table>")))
    (delete-region xp1 xp2)
    (goto-char xp1)
    (insert xresultStr)))

requires package Emacs: xah-get-thing.el

HTML