Skip to content

Instantly share code, notes, and snippets.

@thibaultcha
Last active September 9, 2020 18:07
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thibaultcha/0b24aa13ffe4b4308a0bba3c6e734d27 to your computer and use it in GitHub Desktop.
Save thibaultcha/0b24aa13ffe4b4308a0bba3c6e734d27 to your computer and use it in GitHub Desktop.
Align Nginx variables declarations with Vim

The Nginx code style asks for a specific alignment of variables declarations that is strainuous to manually enforce:

size_t                    slen;
uint32_t                  hash;
ngx_int_t                 rc;
const u_char             *p;
ngx_shm_zone_t           *shm_zone;
ngx_slab_pool_t          *shpool;
ngx_rbtree_node_t        *node, *sentinel;
ngx_ssl_session_t        *sess;
ngx_ssl_sess_id_t        *sess_id;
ngx_ssl_session_cache_t  *cache;
u_char                    buf[NGX_SSL_MAX_SESSION_SIZE];
ngx_connection_t         *c;

Now, I make a point to respect a project's codestyle and architectural paradigms, but manually enforcing this style is particularly slow and tedious.

Here is a Tabular command I wrote to automate this task in Vim:

:Tabularize /\v\w\s*\zs(\s\|\*+)\ze\S+([,;]\|\s+\=)/l2r0l0

And here is a screencast showing it in action: https://terminalizer.com/view/48ca6d4c4091.

Personally, I mapped it to <leader>an as in "align nginx-style":

nnoremap <leader>an :Tabularize /\v\w\s*\zs(\s\|\*+)\ze\S+([,;]\|\s+\=)/l2r0l0<cr>

The degree of extensibility and workflow optimization made possible by Vim and its third-paty plugins has never ceased to amaze me, and this is a small example of it.

Are there more formatting tools available to enforce such code style requirements? I could not find any!

@kidd
Copy link

kidd commented Jul 12, 2020

That's a nice one! the [,;] is a cool trick! :)

GNU Emacs knows how to align those by default using m-x align RET. The only difference being the 2 spaces in between vs 1.

The hand-made version with 2 spaces would be something like this: m-x align-regexp RET \( \(\*\| \)[^ ]+[;,]\). (or modify the default used by align)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment