Created
October 15, 2022 15:40
-
-
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- 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