Skip to content

Instantly share code, notes, and snippets.

@riccardomurri
Created August 19, 2011 18:44
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save riccardomurri/1157646 to your computer and use it in GitHub Desktop.
Save riccardomurri/1157646 to your computer and use it in GitHub Desktop.
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)
(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."))
@fpoto
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