Reformat a Markdown Table


Requirements


This markdown table is badly messed up:

1| File  | Category |
2|:------|:---------|
3| calendar.md           | tex|
4| tex_packages.md           | tex|
5| completion.md           | vim|
6| csv_to_md.md           | vim|
7| format_md.md           | vim|

Highight from the top with V6j, then run column to fix the output:

1:!column -ts'|' -o '|'

It displays like this:

1:'<,'>!column -ts'|' -o '|'
1| File                      | Category |
2|:------                    |:---------|
3| calendar.md               | tex      |
4| tex_packages.md           | tex      |
5| completion.md             | vim      |
6| csv_to_md.md              | vim      |
7| format_md.md              | vim      |

That's better, but the header is broken. Fix is by replacing spaces with dashes.

1:s/ /-/g

The lines have too much whitespace. You can fix this with the 'truncate' command, to squeeze repeating spaces or dashes.

1tr -s ' -' |column -ts '|' -o '|'
1| File            | Category |
2|:----------------|:---------|
3| calendar.md     | tex      |
4| tex_packages.md | tex      |
5| completion.md   | vim      |
6| csv_to_md.md    | vim      |
7| format_md.md    | vim      |

Keyboard Shortcut

Put this in your ~/.vimrc to map 'Control + t' to reformat markdown tables in visual mode.

1vmap <C-t> :!tr -s ' -' \|column -ts '\|' -o '\|'<Enter>j:s/ /-/g<Enter>k