0

I just recently found a very nice command to search for a pattern in a document, and display all hits:

:g/pattern/z#.1

Since the command is a bit cumbersome to type, I would like to make a shortcut, so instead of typing the command above, I could simply type

:sl pattern

(sl stands for search & list, for lack of a better name.)

I wonder what is the best way to do this. I think one first needs to define a function

function! SearchList(pattern)
    f/a:pattern/z#.1
endfunction

But the only thing the function does, is to show its own content (since this is the only occurrence of a:pattern in my .vimrc.

So here I'm stuck. To create a mapping, is the function actually needed? Or what is the best way to define the mapping? And if indeed a function is the way to go, how would I write this function?

1
6

To create a custom command line command :command is a good choice:

:command! -nargs=1 SL g/<args>/z#.1

You'll need to use a name that starts with a capital letter, though, so I'm using "SL" instead of "sl". Run with :SL pattern.

The rest is pretty self-explanatory. Use a bang (!) after :command to allow subsequent overrides (good for including it in your vimrc file). Specify number of args as 1. Insert that in the command to be run with <args>. BTW, with -nargs=1 spaces are allowed in whatever comes after the command name (in our case the pattern) and it will still be considered one argument.

2
  • 1
    Nice! Extra points for nargs=1, which allows for whitespaces in the search pattern.
    – pfnuesel
    Jan 29 '19 at 13:15
  • @pfnuesel Yes, someone was using their noggin when they designed that part of :command. :) Cheers!
    – B Layer
    Jan 29 '19 at 13:18

This site is temporarily in read only mode and not accepting new answers.

Not the answer you're looking for? Browse other questions tagged .