I am using the following regular expression to match a documentation string underneath a Clojure function definition:


Is there a way to run the normal mode gq (format lines) command on all matches of this pattern in a given file?


Power of g:

:g/\vdefn.*\n\s*\zs"([^"]|\n)*"/normal gngq

The part between the /s is fairly self-explanatory, since it's the regex from your original question.

normal gngq at the end is somewhat interesting. gn will select the next match of the regular expression, and gq, of course, formats this selection (as you mentioned in your question).

:g is the really great part. This is, in my opinion, one of Vim's most useful features. The g ex command takes a regex and an Ex command, and it executes the command on every line the regex matches. If you haven't learned about :g already, I highly recommend doing so, as it'll vastly increase your productivity. A few resources are Vim's own :help :g or Power of g on Vim wiki.

  • The gn piece is selecting from the line where V is triggered to the next (not the one on the same line) occurrence of the pattern. Vim's documentation states that if visual mode is active, the selection is extended from the current line through the next pattern. This is causing unwanted behavior. – user489 Feb 19 '15 at 22:29
  • @merb Whoops, didn't realize that. Edited. – Doorknob Feb 19 '15 at 22:31
  • The selection is still from the line of the match to the next match. Stepping through the normal mode commands manually shows that //s<cr> leaves me at the beginning of the match on the current line, but //e<cr> leaves me at the end of the next match, not the current match. – user489 Feb 19 '15 at 22:36
  • 1
    The problem appears to be with //s<cr>V. When I run :normal V I go into visual line mode, as expected. When I run :normal //s<cr> my cursor lands on the first " of the match, as expected. When I run :normal //s<cr>V I do not get a visual selection. – user489 Feb 19 '15 at 23:04
  • 1
    Solved it. The command needs to be normal gngq. Suggesting an edit. – user489 Feb 19 '15 at 23:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy