0

About three years ago, I had gathered chunks of code from the net and made my init.vim config file. Now, with Lua released, I am unable to convert it.

And it's down to you folks whether you can help me. You are my last hope.

Yes, I've read the documentation and whatnot. Still, I don't get it. Most of the code in my init.vim file are complex while I can do only simpler ones.

au TextYankPost * silent! lua vim.highlight.on_yank {higroup="IncSearch", timeout=300}

au BufReadPost * if line("'\"") > 1 && line("'\"") <= line("$") | exe "normal! g'\"" | endif

" type :messages to see all the changed files
set autoread
autocmd FocusGained,BufEnter,CursorHold,CursorHoldI *
   \ if mode() !~ '\v(c|r.?|!|t)' && getcmdwintype() == '' | checktime | endif
autocmd FileChangedShellPost *
  \ echohl WarningMsg | echom "File " . expand('<afile>') . " changed on disk. Buffer reloaded." | echohl None

function! TabLcd()
    let current_tab = tabpagenr()
    tabdo lcd %:p:h
    execute 'tabnext' current_tab
endfunction

nnoremap <silent> <leader>lcd :call TabLcd()<cr>
nnoremap <leader>cd :execute 'cd' getcwd(-1)<cr>

This block is solved by me: https://vi.stackexchange.com/a/43276/36876

" No highlight after search - triggers on motion or going into insert mode
noremap <expr> <Plug>(StopHL) execute('nohlsearch')[-1]
noremap! <expr> <Plug>(StopHL) execute('nohlsearch')[-1]

fu! HlSearch()
    let s:pos = match(getline('.'), @/, col('.') - 1) + 1
    if s:pos != col('.')
        call StopHL()
    endif
endfu

fu! StopHL()
    if !v:hlsearch || mode() isnot 'n'
        return
    else
        sil call feedkeys("\<Plug>(StopHL)", 'm')
    endif
endfu

augroup SearchHighlight
au!
    au CursorMoved * call HlSearch()
    au InsertEnter * call StopHL()
augroup end

This block is solved by @vivian-de-smedt in https://vi.stackexchange.com/a/43279/36876

if !exists("g:os")
    if has("win64") || has("win32") || has("win16")
        let g:os = "Windows"
    else
        let g:os = substitute(system('uname'), '\n', '', '')
    endif
endif

This block solved in https://vi.stackexchange.com/a/43284/36876

tnoremap <Esc> <C-\><C-n>

" https://vi.stackexchange.com/a/22327/36876
if has('nvim')
    augroup terminal_setup | au!
        autocmd TermOpen * nnoremap <buffer><LeftRelease> <LeftRelease>i
    augroup end
endif

function! TermWrapper(command) abort
    if !exists('g:split_term_style') | let g:split_term_style = 'vertical' | endif
    if g:split_term_style ==# 'vertical'
        let buffercmd = 'vnew'
    elseif g:split_term_style ==# 'horizontal'
        let buffercmd = 'new'
    else
        echoerr 'ERROR! g:split_term_style is not a valid value (must be ''horizontal'' or ''vertical'' but is currently set to ''' . g:split_term_style . ''')'
        throw 'ERROR! g:split_term_style is not a valid value (must be ''horizontal'' or ''vertical'')'
    endif
    exec buffercmd
    if exists('g:split_term_resize_cmd')
        exec g:split_term_resize_cmd
    endif
    exec 'term ' . a:command
    exec 'setlocal nornu nonu'
    exec 'startinsert'
endfunction

command! -nargs=0 Compile call TermWrapper(printf('g++ -std=c++17 -O2 -Wall %s -o %s.out', expand('%'), expand('%:r')))
autocmd FileType cpp nnoremap <F9> <Esc>:w <bar> Compile<CR>

command! -nargs=0 Run call TermWrapper(printf('./%s.out', expand('%:r')))
autocmd FileType cpp nnoremap <F10> :Run<CR>

command! -nargs=0 CompileAndRun call TermWrapper(printf('g++ -std=c++17 -O2 -Wall %s -o %s.out && ./%s.out', expand('%'), expand('%:r'), expand('%:r')))
autocmd FileType cpp nnoremap <F12> <Esc>:w <bar> CompileAndRun<CR>

let g:split_term_style = 'horizontal'
let g:split_term_resize_cmd = 'resize 30'
set splitbelow

This block is solved in https://vi.stackexchange.com/a/43287/36876

11
  • 1
    I"m not sure I understand your problem. If you are using init.vim you are probably using Neovim that do not support vim9script. Could tell us why you want to migrate? Commented Oct 7, 2023 at 21:45
  • 1
    Sorry, My bad. I'll go with Lua, then.
    – Mega Bang
    Commented Oct 8, 2023 at 8:14
  • 1
    I suppose you have to narrow your question. I propose you to split it into sub questions to ask support for the translation of group of command of your init.vim. These individual questions answer will be more generic and have more chance to help others. Commented Oct 8, 2023 at 13:31
  • 1
    Let's do it bit by bit. Could you answer my questions on the other question? Such large question have no chance to help others. If you cut it into chunk we will help you :-) Commented Oct 10, 2023 at 12:57
  • 3
    The problem with this question as it stands is that it is extremely unlikely to help others who find it: it's highly specific to your (entire) vimrc. I would encourage you to look at the wealth of vim->lua questions on this site and try to make as many conversions as you can. Where you can't, ask targeted questions about those translations.
    – D. Ben Knoble
    Commented Oct 10, 2023 at 16:40

1 Answer 1

1
+50

Here is the aggregated solution:

if vim.fn.exists('g:os') == 0 then
    local is_windows = vim.fn.has("win64") == 1 or vim.fn.has("win32") == 1 or vim.fn.has("win16") == 1
    if is_windows then
        vim.g.os = "Windows"
    else
        local uname_output = vim.fn.system('uname')
        vim.g.os = string.gsub(uname_output, '\n', '')
    end
end

function TabLcd()
    local current_tab = vim.fn.tabpagenr()
    vim.cmd("tabdo <commands>")
    vim.cmd("execute 'tabnext' " .. current_tab)
end

vim.api.nvim_set_keymap('n', '<leader>lcd', ':lua TabLcd()<CR>', { noremap = true, silent = true })

vim.api.nvim_set_keymap('t', '<Esc>', '<C-\\><C-n>', { noremap = true })

if vim.fn.has('nvim') == 1 then
    vim.cmd[[
        augroup terminal_setup
            autocmd!
            autocmd TermOpen * nnoremap <buffer><LeftRelease> <LeftRelease>i
        augroup end
    ]]
end

function TermWrapper(command)
    if not vim.g.split_term_style then
        vim.g.split_term_style = 'vertical'
    end
    local buffercmd
    if vim.g.split_term_style == 'vertical' then
        buffercmd = 'vnew'
    elseif vim.g.split_term_style == 'horizontal' then
        buffercmd = 'new'
    else
        vim.api.nvim_err_writeln("ERROR! g:split_term_style is not a valid value (must be 'horizontal' or 'vertical' but is currently set to '" .. vim.g.split_term_style .. "')")
        error("ERROR! g:split_term_style is not a valid value (must be 'horizontal' or 'vertical')")
    end
    vim.cmd(buffercmd)
    if vim.g.split_term_resize_cmd then
        vim.cmd(vim.g.split_term_resize_cmd)
    end
    vim.cmd('term ' .. command)
    vim.cmd('setlocal nornu nonu')
    vim.cmd('startinsert')
end

vim.cmd([[command! -nargs=0 Compile lua TermWrapper(string.format('g++ -std=c++17 -O2 -Wall %s -o %s.out', vim.fn.expand("%"), vim.fn.expand("%:r")))]])
vim.cmd('autocmd FileType cpp nnoremap <F9> <Esc>:w <bar> Compile<CR>')

vim.cmd([[command! -nargs=0 Run lua TermWrapper(string.format("./%s.out", vim.fn.expand("%:r")))]])
vim.cmd('autocmd FileType cpp nnoremap <F10> :Run<CR>')

vim.cmd([[command! -nargs=0 CompileAndRun lua TermWrapper(string.format('g++ -std=c++17 -O2 -Wall %s -o %s.out && ./%s.out', vim.fn.expand("%"), vim.fn.expand("%:r"), vim.fn.expand("%:r")))]])
vim.cmd('autocmd FileType cpp nnoremap <F12> <Esc>:w <bar> CompileAndRun<CR>')

vim.g.split_term_style = 'horizontal'
vim.g.split_term_resize_cmd = 'resize 30'
vim.opt.splitbelow = true

vim.api.nvim_set_keymap('n', '<Plug>(StopHL)', "execute('nohlsearch')[-1]", { noremap = true, expr = true })
vim.api.nvim_set_keymap('i', '<Plug>(StopHL)', "execute('nohlsearch')[-1]", { noremap = true, expr = true })

function HlSearch()
    local pos = vim.fn.match(vim.fn.getline('.'), vim.fn.getreg('/'), vim.fn.col('.') - 1) + 1
    if pos ~= vim.fn.col('.') then
        StopHL()
    end
end

function StopHL()
    if not vim.v.hlsearch or vim.fn.mode() ~= 'n' then
        return
    else
        vim.cmd[[silent! call feedkeys("\<Plug>(StopHL)", 'm')]]
    end
end

local searchHighlightGrp = vim.api.nvim_create_augroup('SearchHighlight', { clear = true })
vim.api.nvim_create_autocmd({"CursorMoved"}, {group = searchHighlightGrp, pattern = '*', callback = HlSearch})
vim.api.nvim_create_autocmd({"InsertEnter"}, {group = searchHighlightGrp, pattern = '*', callback = StopHL})

vim.api.nvim_create_autocmd({'TextYankPost'}, { callback = function() vim.highlight.on_yank {higroup="IncSearch", timeout=300} end })

vim.api.nvim_create_autocmd({'BufReadPost'}, { callback = function()
    local mark = vim.api.nvim_buf_get_mark(0, '"')[1]
    if mark > 1 and mark < vim.api.nvim_buf_line_count(0) then
        vim.api.nvim_command([[exe "normal! g'\""]])
    end
end
})

vim.o.autoread = 1

vim.api.nvim_create_autocmd({'FocusGained', 'BufEnter', 'CursorHold', 'CursorHoldI'}, { callback = function()
    if not string.match(vim.fn.mode(), '^(c|r.?|!|t)') and vim.api.nvim_eval('getcmdwintype()') == '' then
        vim.cmd([[checktime]])
    end
end
})

vim.api.nvim_create_autocmd({'FileChangedShellPost'}, { callback = function()
    vim.api.nvim_command([[
        echohl WarningMsg
        echom "File " . expand('<afile>') . " changed on disk. Buffer reloaded."
        echohl None
        ]])
end
})
5
  • Three chunks of code are left now.
    – Mega Bang
    Commented Oct 11, 2023 at 14:03
  • Could you add this feature? Your answer from this thread vi.stackexchange.com/a/43270/36876
    – Mega Bang
    Commented Oct 11, 2023 at 18:15
  • 1
    In order to make the answer reusable let's make the question small. I propose you ask another question about this. It allow also others to propose something different. The mega question are not reusable and only very few people will consider answering them reducing the average quality of the answer by lowering the 'competition' :-) Commented Oct 11, 2023 at 18:18
  • 1
    Done. vi.stackexchange.com/q/43293/36876
    – Mega Bang
    Commented Oct 11, 2023 at 18:21
  • 1
    I have complete the conversion :-) Commented Oct 11, 2023 at 18:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.