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


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.

function _G.preserve(cmd)
    cmd = string.format('keepjumps keeppatterns execute %q', cmd)
    local original_cursor = vim.fn.winsaveview()
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:

--> :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 ="%a, %m %Y %H:%M")
        preserve('sil! keepp keepj 1,7s/\\vlast (modified|change):\\zs.*/ ' .. time .. '/ei') 
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
function nvim_create_augroups(definitions)
    for group_name, definition in pairs(definitions) do
        api.nvim_command('augroup '..group_name)
        for _, def in ipairs(definition) do
            local command = table.concat(vim.tbl_flatten{'autocmd', def}, ' ')
        api.nvim_command('augroup 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" };

-- autocommands END
Enter fullscreen mode Exit fullscreen mode

Deleting blank lines

-- see mappings after map helper
function _G.delblanklines()
    if ( ~= 'binary') or ( ~= 'diff') then
        preserve('sil! keepp keepj %s/^\\n\\{2,}/\\r/ge')
        preserve('sil! keepp keepj %s/\\v($\\n\\s*)+%$/\\r/e')
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)

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

This article can change/grow a little bit


The main source I have used was this post on

Discussion (0)