ui.lua 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. local M = {}
  2. --- Prompts the user to pick a single item from a collection of entries
  3. ---
  4. ---@param items table Arbitrary items
  5. ---@param opts table Additional options
  6. --- - prompt (string|nil)
  7. --- Text of the prompt. Defaults to `Select one of:`
  8. --- - format_item (function item -> text)
  9. --- Function to format an
  10. --- individual item from `items`. Defaults to `tostring`.
  11. --- - kind (string|nil)
  12. --- Arbitrary hint string indicating the item shape.
  13. --- Plugins reimplementing `vim.ui.select` may wish to
  14. --- use this to infer the structure or semantics of
  15. --- `items`, or the context in which select() was called.
  16. ---@param on_choice function ((item|nil, idx|nil) -> ())
  17. --- Called once the user made a choice.
  18. --- `idx` is the 1-based index of `item` within `item`.
  19. --- `nil` if the user aborted the dialog.
  20. function M.select(items, opts, on_choice)
  21. vim.validate {
  22. items = { items, 'table', false },
  23. on_choice = { on_choice, 'function', false },
  24. }
  25. opts = opts or {}
  26. local choices = {opts.prompt or 'Select one of:'}
  27. local format_item = opts.format_item or tostring
  28. for i, item in pairs(items) do
  29. table.insert(choices, string.format('%d: %s', i, format_item(item)))
  30. end
  31. local choice = vim.fn.inputlist(choices)
  32. if choice < 1 or choice > #items then
  33. on_choice(nil, nil)
  34. else
  35. on_choice(items[choice], choice)
  36. end
  37. end
  38. --- Prompts the user for input
  39. ---
  40. ---@param opts table Additional options. See |input()|
  41. --- - prompt (string|nil)
  42. --- Text of the prompt. Defaults to `Input: `.
  43. --- - default (string|nil)
  44. --- Default reply to the input
  45. --- - completion (string|nil)
  46. --- Specifies type of completion supported
  47. --- for input. Supported types are the same
  48. --- that can be supplied to a user-defined
  49. --- command using the "-complete=" argument.
  50. --- See |:command-completion|
  51. --- - highlight (function)
  52. --- Function that will be used for highlighting
  53. --- user inputs.
  54. ---@param on_confirm function ((input|nil) -> ())
  55. --- Called once the user confirms or abort the input.
  56. --- `input` is what the user typed.
  57. --- `nil` if the user aborted the dialog.
  58. function M.input(opts, on_confirm)
  59. vim.validate {
  60. on_confirm = { on_confirm, 'function', false },
  61. }
  62. opts = opts or {}
  63. local input = vim.fn.input(opts)
  64. if #input > 0 then
  65. on_confirm(input)
  66. else
  67. on_confirm(nil)
  68. end
  69. end
  70. return M