From 1b6a74520c983f951b3a7ffb721ebab110d78146 Mon Sep 17 00:00:00 2001 From: tastytea Date: Tue, 9 Aug 2022 13:28:46 +0200 Subject: [PATCH] nvim: add function to insert/update modeline --- .config/nvim/lua/functions.lua | 39 ++++++++++++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/.config/nvim/lua/functions.lua b/.config/nvim/lua/functions.lua index f4d821e..7555399 100644 --- a/.config/nvim/lua/functions.lua +++ b/.config/nvim/lua/functions.lua @@ -14,3 +14,42 @@ vim.api.nvim_create_autocmd( callback = my_remove_trailing_whitespace } ) + +function my_insert_modeline() + local comment_string = vim.o.commentstring + 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', + ' fenc=' .. fenc, + ' ts=' .. vim.o.tabstop, + ' sw=' .. vim.o.shiftwidth, + (vim.o.expandtab and ' et' or ' noet'), + ' tw=' .. vim.o.textwidth, + ':', + 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.cmd([[command! ModelineInsert lua my_insert_modeline()]])