0

Take for example,

" This is a line

How do I check if my cursor is after the first " character or before it, if I'm in insert mode?

The reason I need this is because I have a insert-mode keymapping that depends on the :h virtcol() position of the cursor. If I use <C-O>, the cursor goes to normal mode and in position after the character ", when if I use <Esc>, the cursor goes to normal mode and in position before the character ". I could use <C-o> to distinguish if the insert mode cursor was before or after the character ". But the problem remains if the line has only one character, i.e. ". And I have some other reasons I want to use <Esc>.

My if-else blocks has mainly two cases:

  • If the insert-mode cursor is before any other character, insert a <Tab>
  • Otherwise, insert spaces.

1 Answer 1

0

In order to get the column number in :h Insert-mode, :h i_CTRL-R_= needs to be used.

For example, the following function returns a <TAB> if the cursor has no text before it and required number of spaces otherwise.

function! SpecialTab() abort
    if (col('.') == 1) || (matchstr(getline('.'), '\%'.(col('.') - 1).'c.') =~ '\t')
        return "\<Tab>"
    else
        return repeat("\<Space>", (&tabstop - (virtcol('.') % &tabstop)) + 1)
    endif
endfunction
inoremap <Tab> <C-R>=SpecialTab()<CR>
4
  • 1
    You could also use a map-expr inoremap <expr> <tab> SpecialTab().
    – Ralf
    Apr 6, 2019 at 6:41
  • @Ralf, both are basically same thing, AFAIK. <expr> uses the result of the function in {rhs}. :h i_CTRL-R= uses the expression register, but does the same thing, i.e. evaluates the function to get an expression. Is that right?
    – 3N4N
    Apr 6, 2019 at 6:55
  • 1
    You are right, it's just an alternative. I don't know whether one is "better" than the other.
    – Ralf
    Apr 6, 2019 at 7:20
  • 1
    I find expr more readable because i am used to it, and it means you dont have to worry about the semantics of <C-r> having different meanings in different modes (ie in normal mode you must use expr)
    – D. Ben Knoble
    Apr 6, 2019 at 14:34

Your Answer

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

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