Skip to content

Instantly share code, notes, and snippets.

@jesseleite
Created December 21, 2023 04:53
Show Gist options
  • Save jesseleite/a61c73757ea51b6ced1de6b61c568546 to your computer and use it in GitHub Desktop.
Save jesseleite/a61c73757ea51b6ced1de6b61c568546 to your computer and use it in GitHub Desktop.
Toggle surrounding quote style mapping in Neovim (probably not perfect lol!)
local toggle_surrounding_quote_style = function ()
local current_line = vim.fn.line('.')
local next_single_quote = vim.fn.searchpos("'", 'cn')
local next_double_quote = vim.fn.searchpos('"', 'cn')
if next_single_quote[1] ~= current_line then
next_single_quote = false
end
if next_double_quote[1] ~= current_line then
next_double_quote = false
end
if next_single_quote == false and next_double_quote == false then
print('Could not find quotes on current line!')
elseif next_single_quote == false and next_double_quote ~= false then
vim.cmd.normal([[macs"'`a]])
elseif next_single_quote ~= false and next_double_quote == false then
vim.cmd.normal([[macs'"`a]])
elseif next_single_quote[2] > next_double_quote[2] then
vim.cmd.normal([[macs"'`a]])
else
vim.cmd.normal([[macs'"`a]])
end
end
vim.keymap.set('n', "<Leader>'", toggle_surrounding_quote_style)
@gcavanunez
Copy link

Loved this - I also wanted to give it support for backticks so tweaked it a lil bit

local toggle_surrounding_quote_style = function()
  local current_line = vim.fn.line('.')
  local next_single_quote = vim.fn.searchpos("'", 'cn')
  local next_double_quote = vim.fn.searchpos('"', 'cn')
  local next_backtick = vim.fn.searchpos('`', 'cn')

  if next_single_quote[1] ~= current_line then
    next_single_quote = false
  end
  if next_double_quote[1] ~= current_line then
    next_double_quote = false
  end
  if next_backtick[1] ~= current_line then
    next_backtick = false
  end

  if next_single_quote == false and next_double_quote == false and next_backtick == false then
    print('Could not find quotes or backticks on current line!')
  else
    -- Determine which quote type is the closest
    local closest = nil
    if next_single_quote then
      closest = next_single_quote
    end
    if next_double_quote and (not closest or next_double_quote[2] < closest[2]) then
      closest = next_double_quote
    end
    if next_backtick and (not closest or next_backtick[2] < closest[2]) then
      closest = next_backtick
    end

    if closest == next_single_quote then
      vim.cmd.normal([[macs'"a]])
    elseif closest == next_double_quote then
      vim.cmd.normal([[macs"`a]])
    elseif closest == next_backtick then
      vim.cmd.normal([[macs`'a]])
    end
  end
end

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