2

Simple question: I might have content formatted like

item1 item2 # this is a comment
longer_name1 foobarbaz # another comment

that I want to see aligned as follows:

item1        item2     # this is a comment
longer_name1 foobarbaz # another comment

and notice the spaces in the comments are not matched or aligned. How can I do this?

1 Answer 1

2

I solved this problem and wanted to share with everyone: just takes a little regex-magic to match the first space after non-whitespace text, except where it is preceded by a comment character anywhere in the line.

In short, you can place these lines in your .vimrc:

vnoremap <expr> -<Space> ':Tabularize /\S\(' . split(&commentstring, '%s')[0] . '.*\)\@<!\zs\ /l0<CR>'
nnoremap <expr> -<Space> ':Tabularize /\S\(' . split(&commentstring, '%s')[0] . '.*\)\@<!\zs\ /l0<CR>'

Note we can detect the filetype comment-character by parsing &commentstring (try :echo &commentstring to see what it looks like). You can also replace that call to split() as follows

vnoremap <expr> -<Space> ':Tabularize /\S\(' . b:NERDCommenterDelims['left'] . '.*\)\@<!\zs\ /l0<CR>'
nnoremap <expr> -<Space> ':Tabularize /\S\(' . b:NERDCommenterDelims['left'] . '.*\)\@<!\zs\ /l0<CR>'

if you happen to use the NERDCommenter plugin.


Came across a great example of where this is useful today: case statements in bash scripts -- so the following

case "$string" in
  foo) command ;; # here's a command
  foobarbaz) longer_command ;; # and another one
  abcdef) f ;; # the last command
  *) hello ;; # and the default case
esac

becomes

case "$string" in
  foo)       command        ;; # here's a command
  foobarbaz) longer_command ;; # and another one
  abcdef)    f              ;; # a final command
  *)         hello          ;; # default case
esac

note again that the spaces in end-of-line comments are ignored.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.