From 3541a9411512a4ba689713ce5908f0c24f316c8c Mon Sep 17 00:00:00 2001 From: tea Date: Tue, 3 Sep 2024 19:24:01 +0200 Subject: [PATCH] add modeline function and command --- .config/nvim/lua/my/functions.lua | 47 +++++++++++++++++++++++++++++++ 1 file changed, 47 insertions(+) diff --git a/.config/nvim/lua/my/functions.lua b/.config/nvim/lua/my/functions.lua index 8a2ae08..ec424c9 100644 --- a/.config/nvim/lua/my/functions.lua +++ b/.config/nvim/lua/my/functions.lua @@ -95,4 +95,51 @@ function M.current_function() return '' end + +-- Insert or update a modeline at the bottom of the buffer +function M.insert_modeline() + local comment_string = vim.o.commentstring + if comment_string == '' then + comment_string = '%s' + end + local space_maybe = '' + if string.match(comment_string, '%%s(.*)') ~= '' then + space_maybe = ' ' + end + + local fenc = vim.o.fileencoding + if fenc == '' then + fenc = 'utf-8' + end + + local modeline_elements = { + ' vim: set', + ' ts=' .. vim.o.tabstop, + ' sw=' .. vim.o.shiftwidth, + (vim.o.expandtab and ' et' or ' noet'), + ' tw=' .. vim.o.textwidth, + ' ft=' .. vim.o.filetype, + (vim.o.spell and ' spell' .. ' spl=' .. vim.o.spelllang or ''), + (vim.o.wrap and ' wrap' or ' nowrap'), + ':', + space_maybe + } + local modeline = comment_string:gsub('%%s', table.concat(modeline_elements)) + modeline = modeline:gsub(' ', ' ') + + local buffer = vim.api.nvim_win_get_buf(0) + local current = vim.api.nvim_buf_get_lines(buffer, -2, -1, true)[1] + if current == modeline then + print('modeline already exists') + elseif string.match(current, 'vim:') then + vim.api.nvim_buf_set_lines(buffer, -2, -1, true, { modeline }) + print('modeline updated') + else + vim.api.nvim_buf_set_lines(buffer, -1, -1, true, { '', modeline }) + print('modeline inserted') + end +end + +vim.api.nvim_create_user_command('ModelineInsert', M.insert_modeline, {}) + return M