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

<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>

and is rendered in browser like this:

abc
123

when you use CSS code like this:

th, td {padding:.25rem; border:solid thin grey}

[see Visual CSS]

Solution

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

If there's a text selection, use the selection as input.
Otherwise, used current text block delimited by empty lines.

@SEPARATOR is a string used as a delimitor for columns.

For example:

a.b.c
1.2.3

with “.” as separator, 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://ergoemacs.org/emacs/elisp_make-html-table.html'
Version 2019-06-07"
  (interactive)
  (let ($bds
        $p1 $p2
        ($sep (read-string "String for column separation:" ","))
        ($i 0)
        ($j 0))
    (setq $bds (xah-get-bounds-of-thing-or-region 'block))
    (setq $p1 (car $bds))
    (setq $p2 (cdr $bds))

    (when (equal (length $sep) 0) (user-error "separator cannot be empty."))

    (save-excursion
      (save-restriction
        (narrow-to-region $p1 $p2)
        (let ((case-fold-search nil))

          (goto-char (point-max))
          (insert "\n")

          (goto-char (point-min))
          (while (and
                  (search-forward $sep nil "NOERROR")
                  (< $i 2000))
            (replace-match "</td><td>")
            (1+ $i))

          (goto-char (point-min))
          (while (and
                  (search-forward "\n" nil "NOERROR")
                  (< $j 2000))
            (replace-match "</td></tr>
<tr><td>")
            (1+ $j))

          (goto-char (point-max))
          (beginning-of-line)
          (delete-char 8)

          (goto-char (point-min))
          (insert "<table class=\"nrm\">
<tr><td>")

          (goto-char (point-max))
          (insert "</table>")
          ;;
          )))))

You'll need the package xah-get-thing.el

[see Emacs: xah-get-thing.el]

HTML

Tags

Links

CSS

Misc

If you have a question, put $5 at patreon and message me on xah discord.
Or support me by Buy Xah Emacs Tutorial