Lua with Neovim: Writing a Neovim Plugin — Plugin Structure, Setup Pattern & Custom Commands | Ep 32
Video: Lua with Neovim: Writing a Neovim Plugin — Plugin Structure, Setup Pattern & Custom Commands | Ep 32 by Taught by Celeste AI - AI Coding Coach
Watch full page →Lua with Neovim: Writing a Neovim Plugin — Plugin Structure, Setup Pattern & Custom Commands
This guide demonstrates how to create a complete Neovim plugin in Lua from scratch. It covers the conventional plugin file structure, implementing a setup function for configuration, reading buffer lines using Neovim’s API, notifying users with messages, and defining custom commands like :WordCount.
Code
-- lua/wordcount/init.lua
local M = {}
-- Count all words in the current buffer
function M.count_words()
-- Get all lines from the current buffer (0) from start (0) to end (-1)
local lines = vim.api.nvim_buf_get_lines(0, 0, -1, false)
local word_count = 0
for _, line in ipairs(lines) do
-- Count words in each line by splitting on whitespace
for _ in string.gmatch(line, "%S+") do
word_count = word_count + 1
end
end
-- Notify user with total word count
vim.notify("Total words in buffer: " .. word_count, vim.log.levels.INFO)
end
-- Count words in the current line
function M.count_words_line()
local line = vim.api.nvim_get_current_line()
local count = 0
for _ in string.gmatch(line, "%S+") do
count = count + 1
end
vim.notify("Words in current line: " .. count, vim.log.levels.INFO)
end
-- Setup function to create user commands and accept options
function M.setup(opts)
opts = opts or {}
-- Create :WordCount command to count all words
vim.api.nvim_create_user_command("WordCount", function()
M.count_words()
end, {})
-- Create :WordCountLine command to count words in current line
vim.api.nvim_create_user_command("WordCountLine", function()
M.count_words_line()
end, {})
-- Example: could use opts here for configuration
end
return M
Key Points
- Neovim Lua plugins follow the
lua/pluginname/init.luafile structure for automatic discovery. - The
setup(opts)function is the standard entry point for plugin configuration and command registration. vim.api.nvim_buf_get_linesretrieves buffer lines as a Lua table for processing content.vim.notifyprovides a simple way to display messages to the user within Neovim.- Custom user commands like
:WordCountare created usingvim.api.nvim_create_user_commandto expose plugin functionality.