Skip to content

Instantly share code, notes, and snippets.

@VonHeikemen
Last active January 10, 2022 01:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save VonHeikemen/a0a58cab2c910065420ecf5f4102c58c to your computer and use it in GitHub Desktop.
Save VonHeikemen/a0a58cab2c910065420ecf5f4102c58c to your computer and use it in GitHub Desktop.
Neovim: Use backspace when `buftype=prompt`
-- Taken from here:
-- https://github.com/neovim/neovim/issues/14116#issuecomment-977555102
function PromptBackspace()
-- Have to know the length of the prompt
local prompt = 2
local cursor = vim.api.nvim_win_get_cursor(0)
local line = cursor[1]
local col = cursor[2]
if col ~= prompt then
vim.api.nvim_buf_set_text(0, line - 1, col - 1, line - 1, col, {''})
vim.api.nvim_win_set_cursor(0, {line, col - 1})
end
end
vim.api.nvim_buf_set_keymap(
0,
'i',
'<Bs>',
'<cmd>lua PromptBackspace()<CR>',
{noremap = true}
)
@VonHeikemen
Copy link
Author

VonHeikemen commented Nov 26, 2021

This also works.

function PromptBackspace()
  -- Have to know the length of the prompt
  local prompt = 2

  local line = vim.fn.getline('.'):len()
  local col = vim.fn.col('.')

  local feedkeys = function(keys)
    vim.api.nvim_feedkeys(
      vim.api.nvim_replace_termcodes(keys, true, true, true),
      'i',
      true
    )
  end

  if col == prompt + 1 then return end

  if col == prompt + 2 then
    vim.cmd([[normal ch]])
    vim.cmd([[startinsert]])
    return
  end

  if col == line + 1 then
    vim.cmd([[normal cl]])
    vim.cmd([[startinsert]])
    feedkeys('<Right>')
    return
  end

  vim.cmd([[normal ch]])
  vim.cmd([[startinsert]])
  feedkeys('<Right>')
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment