0

For now I have the feeling the answer is no, but I'm asking to make sure that's the case, and to know if people has found workarounds or can suggest good approaches.

From :help popup_menu I've found this example

func ColorSelected(id, result)
   " use a:result
endfunc
call popup_menu(['red', 'green', 'blue'], #{
    \ callback: 'ColorSelected',
    \ })

and tried it out, chainging the commented line to echo a:result, thus discovering that a:result is actually the 1-based index of the item into the list that is the first argument to popup_menu.

Indeed, at :help popup-callback I read that (my emphasis)

The callback is invoked with two arguments: the ID of the popup window and the result, which could be an index in the popup lines, or whatever was passed as the second argument of popup_close().

that seems to confirm my understanding.

So if I wanted the callback to echo back red/green/blue, what options would I have?

I'd be tempted to say that the only way to accomplish the task, without introducing code/data duplication, is to have a g:lobal variable that both the call to popup_menu and the definition of the callback share. Something like this:

let g:pumcolors = ['red', 'green', 'blue']
func ColorSelected(id, result)
  echo 'choice made: ' .. a:result .. ' which is ' .. g:pumcolors[a:result - 1]
endfunc
call popup_menu(g:pumcolors, #{ callback: 'ColorSelected', })

So is this the only way? Or am I missing some obvious approach?

2
  • vi.stackexchange.com/a/34710/22797
    – Matt
    Commented Jan 8, 2023 at 11:30
  • @Matt, Not exactly what OP asked, indeed. I think that answer belongs to this question more than to that. I wonder if somebody can move that answer here, together with comments and votes. Because this question is not a duplicate of that question.
    – Enlico
    Commented Jan 8, 2023 at 12:37

1 Answer 1

1

Popup windows, like all windows in vim, have buffers that contain the text within them. Thus, you can use getbufline to retrieve the text.

func ColorSelected(id, result)
  echo getbufline(winbufnr(a:id), a:result)
endfunc
call popup_menu(['red', 'green', 'blue'], #{
      \ callback: 'ColorSelected',
      \ })

Now, when the popup window is closed this buffer is removed. However, in the context of this callback, it seems to remain valid.

Your Answer

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

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