3

How to sort the output of let or get? E.g., I want to sort all global variables containing "python":

:filter python let g:
muru
  • 24,838
  • 8
  • 82
  • 143

2 Answers2

5
  1. You can capture output with execute() function and then pump it through sort(). The whole command could be then:

    command! -bang -nargs=1 -complete=command Sorted
        \ echo join(sort(split(execute(<q-mods> . ' ' . <q-args>), "\n"),
            \ {s1, s2 -> <bang>(s1 ># s2) - <bang>(s1 <# s2)}), "\n")
    

Now you can do :Sorted filter python let g:

  1. If it makes sense to create a more flexible solution, you can capture command output into a temporary buffer instead. And once it's in a buffer, :sort-ing (or any other kind of processing) becomes easy.

    nnoremap <silent><leader>x :put =trim(execute(input(':', '', 'command')))<CR>
    

Now press <leader>x and enter your command. When the output gets into a buffer you can :sort it as usual.

Matt
  • 20,685
  • 1
  • 11
  • 24
2

Here is a different approach. :filter let will only look for matching variable names, so you can re-implement it using filter() function and sort the resulting dict and output all matches afterwards. This is using the new method functionality of Vim 8.1 and a lambda expression.

for val in sort(keys((copy(g:)->filter({k -> k =~# 'python'}))))|echo printf("%s: %s", val, g:[val])|endfor

Note: we are copy()ing the global dict first, because filter() filters the given dictionary in place, which we do not want here.

Christian Brabandt
  • 25,820
  • 1
  • 52
  • 77
  • FYI, that command gives me multiple errors (Vim 8.1.1772): E731 (using dictionary as string), 2 x E116 (invalid args). I'm able to run with one less lambda, i.e iterate over sort(keys(filter(copy(g:), {k -> k =~# 'python'}))). (Oh, and it appears you have a superfluous pair of parens in there.) – B Layer Nov 28 '19 at 16:41
  • yes, please update your vim. The latest patch that mentions methods is 8.1.2013 – Christian Brabandt Nov 28 '19 at 16:44
  • Got it. Thanks. – B Layer Nov 28 '19 at 16:44