public

Emacs command to transpose the contents of a (La)TeX table.

  • Download Gist
LaTeX-transpose-table.el
Emacs Lisp
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
(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)
(insert
(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."))

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.