Last active
September 7, 2025 03:43
-
-
Save joshnuss/b53da2cd3c381ef498d499ed91bae151 to your computer and use it in GitHub Desktop.
neovim snippets from scratch
This file contains hidden or 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
| -- neovim snippets from scratch | |
| local api = vim.api | |
| local Snippets = { | |
| list = { | |
| lua = { | |
| ["if"] = "if $ then\nend", | |
| p = "print($)", | |
| func = "function $()\nend" | |
| }, | |
| javascript = { | |
| let = "let $ = ", | |
| const = "const $ = " | |
| } | |
| } | |
| } | |
| local function find_prev_word(line, column) | |
| local text = '' | |
| local i = column | |
| while i >= 0 do | |
| local char = string.sub(line, i, i) | |
| if char == ' ' then | |
| break | |
| end | |
| text = char .. text | |
| i = i - 1 | |
| end | |
| return text | |
| end | |
| local function find_name(row, column) | |
| local lines = api.nvim_buf_get_lines(0, row-1, row, true) | |
| return find_prev_word(lines[1], column) | |
| end | |
| local function find_snippet(name) | |
| local filetype = vim.o.filetype | |
| local snippets = Snippets.list[filetype] or {} | |
| return snippets[name] | |
| end | |
| Snippets.expand = function () | |
| local row, column = unpack(api.nvim_win_get_cursor(0)) | |
| local name = find_name(row, column) | |
| local snippet = find_snippet(name) | |
| if snippet == nil then | |
| vim.notify(string.format("Snippet %s was not found.", name), vim.log.levels.ERROR) | |
| return | |
| end | |
| local cursor_pos = string.find(snippet, "[$]") | |
| if cursor_pos then | |
| snippet = string.gsub(snippet, "[$]", "") | |
| end | |
| local lines = vim.split(snippet, "\n") | |
| api.nvim_buf_set_text(0, row - 1, column - string.len(name), row - 1, column, { "" } ) | |
| api.nvim_put(lines, "", true, true) | |
| if cursor_pos then | |
| api.nvim_win_set_cursor(0, { row, cursor_pos - 1 }) | |
| end | |
| end | |
| vim.keymap.set('i', '<S-Tab>', Snippets.expand) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment