Skip to content

Instantly share code, notes, and snippets.

@phelipetls
Created October 15, 2022 15:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save phelipetls/70b1cf29791501cae99887938008cc6a to your computer and use it in GitHub Desktop.
Save phelipetls/70b1cf29791501cae99887938008cc6a to your computer and use it in GitHub Desktop.
Convert JavaScript string into template string, if it contains `${`, with treesitter in neovim
-- in ~/.config/nvim/lua/convert-to-template-string.lua
local M = {}
local replace_surroundings_with = function(node, char)
local start_row, start_col, end_row, end_col = node:range()
vim.api.nvim_buf_set_text(0, start_row, start_col, start_row, start_col + 1, { char })
vim.api.nvim_buf_set_text(0, end_row, end_col - 1, end_row, end_col, { char })
end
M.convert = function()
local node = require("nvim-treesitter.ts_utils").get_node_at_cursor()
local is_string = node:type() == "string"
local is_parent_string = node:parent() and node:parent():type() == "string"
if not (is_string or is_parent_string) then
return
end
if is_parent_string then
node = node:parent()
end
local has_interpolation = false
for child in node:iter_children() do
local child_text = vim.treesitter.query.get_node_text(child, 0)
has_interpolation = child_text:match("${")
if has_interpolation then
break
end
end
if has_interpolation then
replace_surroundings_with(node, "`")
end
end
return M
-- in ~/.config/nvim/after/ftplugin/javascript.vim
if has('nvim')
augroup ConvertToTemplateString
autocmd!
autocmd InsertLeave,TextChanged <buffer> lua require("convert-to-template-string").convert()
augroup END
endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment