vi and sphinx table formatting

sphinx rst tables look great when formatted in html or pdf, but they require some effort to type. Here is an example:


+----------+--------------+
| Scale    | Convergence  |
+==========+==============+
| 0.1 Mpc: | 0.1          |
+----------+--------------+
| 1 Mpc:   | kappa ~ 0.03 |
+----------+--------------+
| 3 Mpc    | 0.01         |
+----------+--------------+

The delimiters need to have exactly the same length in each row, encompassing the text, and the crosses, equal signs and dashes have to be at right places. If a column gets enlarged, the whole table has to be changed, which is a pain.

Luckily, vi has extensions that automatically transforms text in an rst file into a table, and reformats an existing table that has been edited. As usual, installing and making it work took more time than I thought. The package is available for download here, and has a description how to install it. However, it turned out not to be complete, and I had to fiddle around for quite a while until it worked. Here are the steps I needed to do:

1. Install vim_bridge. I used pip. Since I have more than one python versions on my system (Mac OS 10.9.5), and I didn’t know which version is used by vim, I installed it under all versions:

pip-2.7 install vim_bridge
pip-3.3 install vim_bridge
pip-3.4 install vim_bridge

2. Download vim-rst-tables. My default directory to download software from the internet is ~/share.

cd ~/share
git clone git://github.com/nvie/vim-rst-tables.git

3. Copy the extension file. I had to create the vim filetype plugins directory (ftplugin) first.

mkdir ~/.vim/ftplugin
cp ftplugin/rst_tables.vim ~/.vim/ftplugin

4. Unfortunately, the promised commands to create and reformat rst tables (“,,c” and “,,f”) did not do anything in vim. To find out this hack took me the longest. It turned out that the plugin was found (in vim, after loading a .rst file, type
“:scriptnames”, without the quotation marks, the newly added rst_tables.vim should appear in the list), the filtype was correctly recognized as rst (type “set ft”), and rst_tables.vim was indeed parsed (add some random characters to a line in that file, and vim will on start give an error message). I also realized that the long command names did work (type “call ReformatTable()”). To get the key shortcuts work, I had to add to the last part of rst_tables.vim, after the line “if !exists(“no_plugin_maps”) && !exists(“no_rst_table_maps”)” the following line:

:let mapleader = ","

I don’t know whether this is only required on my system, but here you are. It’s finally working. It took me more than an hour to get it working, so according to https://xkcd.com/1205, if this plugin saves me 30 seconds of manual table reformatting once a week over the next five years, it was totally worth it!

Advertisements