Instantly share code, notes, and snippets.

What would you like to do?
Emacs command to transpose the contents of a (La)TeX table.
(defun LaTeX-transpose-table (start end)
(interactive "r")
(goto-char start)
(let ((last start)
(rows (list ()))
(nrows 0)
(ncols 0)
(maxcols 0))
(while (re-search-forward "&\\|\\\\\\\\" end t)
(setf (car rows)
(cons (buffer-substring last (match-beginning 0)) (car rows)))
(incf ncols)
(when (string= "\\\\" (match-string-no-properties 0))
(setq maxcols (max maxcols ncols))
(setq rows (cons () rows))
(incf nrows)
(setq ncols 0))
(setq last (match-end 0))
(goto-char last))
;; empty row
(setq rows (cdr rows))
;; now output the transposed variant
(kill-region start end)
(let (i j table trow)
(loop for j from 1 upto maxcols collect
(loop for i from 1 upto nrows
collect (let* ((row (nth (- nrows i) rows))
(cell (if row (nth (- maxcols j) row) "")))
(concat cell (if (< i nrows) "&" "\\\\\n")))
into trow
finally return (apply 'concat trow))
into table
finally return (apply 'concat table)))))
(message "Old table saved to kill ring."))

This comment has been minimized.

Copy link

fpoto commented Feb 15, 2018

Very nice, simple and flexible. I just downloaded it, tried it, and it worked!

Thank you :)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment