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:
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.

  • I wonder why vim does not have a built-in solution for this – user1602 Nov 27 '19 at 7:54
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.

  • 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

Your Answer

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

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