DEV Community

Cover image for Writing useful lua functions to my neovim
Sérgio Araújo
Sérgio Araújo

Posted on • Updated on

Writing useful lua functions to my neovim

Intro

I used to have a very large vimrc but now, I decided to write my own init.lua, after writing almost everything essential I started to port my functions, things like the Preserve function, so I can delete trailing spaces without moving my cursor.

-- https://bit.ly/3g6vYIW
function _G.preserve(cmd)
    cmd = string.format('keepjumps keeppatterns execute %q', cmd)
    local original_cursor = vim.fn.winsaveview()
    vim.api.nvim_command(cmd)
    vim.fn.winrestview(original_cursor)
end
Enter fullscreen mode Exit fullscreen mode

After writing the above function you can do:

vim.cmd([[cnoreab cls Preserve]])
vim.cmd([[command! Preserve lua preserve('%s/\\s\\+$//ge')]])
vim.cmd([[command! Reindent lua preserve("sil keepj normal! gg=G")]])
vim.cmd([[command! BufOnly lua preserve("silent! %bd|e#|bd#")]])
Enter fullscreen mode Exit fullscreen mode

Change file header helper

What about updating your file header every time you save, I mean, type:
:update<cr>?

--> :lua changeheader()
-- This function is called with the BufWritePre event (autocmd)
-- and when I want to save a file I use ":update" which
-- only writes a buffer if it was modified
function _G.changeheader()
    if (vim.fn.line('$') >= 7) then
        time = os.date("%a, %m %Y %H:%M")
        preserve('sil! keepp keepj 1,7s/\\vlast (modified|change):\\zs.*/ ' .. time .. '/ei') 
    end
end
Enter fullscreen mode Exit fullscreen mode

Next section you can see how the function above is triggered/associated with the BufWritePre event, changing automatically your file header where you can read: "Last Change:".

For you autocommands you can do:

-- autocommands
-------- This function is taken from https://github.com/norcalli/nvim_utils
function nvim_create_augroups(definitions)
    for group_name, definition in pairs(definitions) do
        api.nvim_command('augroup '..group_name)
        api.nvim_command('autocmd!')
        for _, def in ipairs(definition) do
            local command = table.concat(vim.tbl_flatten{'autocmd', def}, ' ')
            api.nvim_command(command)
        end
        api.nvim_command('augroup END')
    end
end

local autocmds = {
    reload_vimrc = {
        -- Reload vim config automatically
        {"BufWritePost",[[$VIM_PATH/{*.vim,*.yaml,vimrc} nested source $MYVIMRC | redraw]]};
    };
    change_header = {
        {"BufWritePre", "*", "lua changeheader()"}
    };
    packer = {
        { "BufWritePost", "plugins.lua", "PackerCompile" };
    };
    terminal_job = {
        { "TermOpen", "*", [[tnoremap <buffer> <Esc> <c-\><c-n>]] };
        { "TermOpen", "*", "startinsert" };
        { "TermOpen", "*", "setlocal listchars= nonumber norelativenumber" };
    };
    restore_cursor = {
        { 'BufRead', '*', [[call setpos(".", getpos("'\""))]] };
    };
    save_shada = {
        {"VimLeave", "*", "wshada!"};
    };
    resize_windows_proportionally = {
        { "VimResized", "*", ":wincmd =" };
    };
    toggle_search_highlighting = {
        { "InsertEnter", "*", "setlocal nohlsearch" };
    };
    lua_highlight = {
        { "TextYankPost", "*", [[silent! lua vim.highlight.on_yank() {higroup="IncSearch", timeout=400}]] };
    };
    ansi_esc_log = {
        { "BufEnter", "*.log", ":AnsiEsc" };
    };
}

nvim_create_augroups(autocmds)
-- autocommands END
Enter fullscreen mode Exit fullscreen mode

Deleting blank lines

-- see mappings after map helper
function _G.delblanklines()
    if (vim.bo.filetype ~= 'binary') or (vim.bo.filetype ~= 'diff') then
        preserve('sil! keepp keepj %s/^\\n\\{2,}/\\r/ge')
        preserve('sil! keepp keepj %s/\\v($\\n\\s*)+%$/\\r/e')
    end
end
Enter fullscreen mode Exit fullscreen mode

map helper

-- map helper
local function map(mode, lhs, rhs, opts)
    local options = {noremap = true}
    if opts then options = vim.tbl_extend('force', options, opts) end
    vim.api.nvim_set_keymap(mode, lhs, rhs, options)
end

map('n', '<leader>d', ':lua delblanklines()<cr>')
Enter fullscreen mode Exit fullscreen mode

This article can change/grow a little bit

References:

The main source I have used was this post on neovim.discourse.group

Discussion (0)