add modeline function and command

This commit is contained in:
tea 2024-09-03 19:24:01 +02:00
parent 7689f8a270
commit 3541a94115
No known key found for this signature in database

View File

@ -95,4 +95,51 @@ function M.current_function()
return '' return ''
end 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 return M