A latex table needs to contain spaces to be aligned. However, when aligning, we want to remove all those extra spaces that we've added for alignment. A simple rule is that we want one space after the ampersand, and then one space after the last non-space character in the cell.

A properly collapsed table:

\begin { tabular }{lrr} Left & Right & Right long \\ Left long & Right long & Right \\ \end { tabular }

This is compact, but doesn't really allow you to quickly scan across cells to find missing ampersands. An aligned table, however, does:

\begin { tabular }{lrr} Left & Right & Right long \\ Left long & Right long & Right \\ \end { tabular }

As you can see, the table is aligned, and we can easily see which column a value is part of. We define a function that can do this by running a regex over our table.

( defun LaTeX-collapse-table () ( interactive ) ( save-excursion (LaTeX-mark-environment) ( while (re-search-forward "[[:space:]]+ \\ ( & \\ | \\\\\\\\ \\ ) " (region-end) t) (replace-match " \\1" ))))

This marks the current environment, and replaces all spaces before ampersands or newlines (double backslash) with a single space. We don't have lookahead in Elisp, so we need to save our last character (ampersand or double backslash) in a group. In a sane regex syntax, the expression would be "\s+(&|\\\\)", but Emacs' regexes are… special.