From d4057a3fecc6f3969711f900eaddb968935213c2 Mon Sep 17 00:00:00 2001 From: Price Hiller Date: Wed, 6 Sep 2023 23:35:29 -0500 Subject: [PATCH] feat(nvim): add python f-string transformer Thanks to https://gist.github.com/linguini1/ee91b6d8c196cbd731d10a61447af6a3 --- dots/.config/nvim/after/ftplugin/python.lua | 31 +++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 dots/.config/nvim/after/ftplugin/python.lua diff --git a/dots/.config/nvim/after/ftplugin/python.lua b/dots/.config/nvim/after/ftplugin/python.lua new file mode 100644 index 00000000..3e795b0e --- /dev/null +++ b/dots/.config/nvim/after/ftplugin/python.lua @@ -0,0 +1,31 @@ +-- Treesitter automatic Python format strings +-- THANKS https://gist.github.com/linguini1/ee91b6d8c196cbd731d10a61447af6a3 +vim.api.nvim_create_augroup("py-fstring", { clear = true }) +vim.api.nvim_create_autocmd("InsertCharPre", { + pattern = { "*.py" }, + group = "py-fstring", + --- @return nil + callback = function(opts) + -- Only run if f-string escape character is typed + if vim.v.char ~= "{" then return end + + -- Get node and return early if not in a string + local node = vim.treesitter.get_node() + + if not node then return end + if node:type() ~= "string" then node = node:parent() end + if not node or node:type() ~= "string" then return end + + vim.print(node:type()) + local row, col, _, _ = vim.treesitter.get_node_range(node) + + -- Return early if string is already a format string + local first_char = vim.api.nvim_buf_get_text(opts.buf, row, col, row, col + 1, {})[1] + vim.print("row " .. row .. " col " .. col) + vim.print("char: '" .. first_char .. "'") + if first_char == "f" then return end + + -- Otherwise, make the string a format string + vim.api.nvim_input("m'" .. row + 1 .. "gg" .. col + 1 .. "|if`'la") + end, +})