0

Can anyone help me transform this into nvim.lua?

inoremap <silent><expr> <TAB>
    \ pumvisible() ? "<C-n>" :
        \ <SID>check_back_space() ? "<TAB>" : coc#refresh()

function! s:check_back_space() abort
    let cpos = col('.') - 1
    return !cpos || getline('.')[cpos - 1]  =~# '\s'
endfunction

What I've done:

local EXPR_NOREF_NOERR_TRUNC = { expr = true, noremap = true, silent = true, nowait = true }

vim.api.nvim_set_keymap('i', '<Tab>', 'check_back_space() ? "<C-n>" : "<Tab>"', EXPR_NOREF_NOERR_TRUNC)

But I don't know what's the function in lua to get the char at left of the currnet cursor pos.

2

:h nvim_win_get_cursor() will return a tuple containing the current cursor position, which you'll have to unpack to use. It takes an argument {window}, and you can use 0 to specify the current window.

:h nvim_get_current_line() is the Neovim Lua analog to getline('.').

Here is an example:

function check_back_space()
    -- get row and column
    local row, col = unpack(vim.api.nvim_win_get_cursor(0))
  
    -- get current line of text
    local linetext = vim.api.nvim_get_current_line()

    return col == 0 or string.match(linetext:sub(col, col), '%s') ~= nil
end

It's important to note the the column returned from nvim_win_get_cursor() is 0-based, while Lua arrays and col() are 1-based. So, in the following line

return col == 0 or string.match(linetext:sub(col, col), '%s') ~= nil

the first condition tests if col is the first column, and the second tests that the character in the previous column is white space, even though both use col.


See also:

5
  • I will study your well-organized answer after work!
    – job_start
    Oct 7 at 2:58
  • How to check the entire line is composed of white-spaces?
    – job_start
    Oct 9 at 5:30
  • wouldn't that require using lua's pattern matching? lua.org/pil/20.1.html
    – alec
    Oct 9 at 13:16
  • lua.org/pil/20.2.html (the next page) shows %s for space characters
    – alec
    Oct 9 at 13:27
  • 2
    @job_start linetext:sub(col, col) takes a substring of line text. If you want to match the whole line use just linetext Oct 9 at 14:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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