Created
August 19, 2011 18:44
-
-
Save riccardomurri/1157646 to your computer and use it in GitHub Desktop.
Emacs command to transpose the contents of a (La)TeX table.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(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.")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Very nice, simple and flexible. I just downloaded it, tried it, and it worked!
Thank you :)