5

I have some 30 characters in a line. When I press 80|, it should move 50 character to the right, thus move the cursor to 80th character. (30, 50, 80 are for examples)

How to achieve this using mapping or commands? I tried

   :nmap <Bar> a<Space>

It doesn't work.

  • 2
    You could try with a function that compute the difference between the current column and the 80th one – nobe4 May 18 '16 at 9:37
  • How to access the "no of times" count? If I give 80|, it has to do something that many times. How to get that 80 number in mapping? I would prefer to use map – SibiCoder May 18 '16 at 9:41
  • 1
    I edited the question to make clear what you want. – nobe4 May 18 '16 at 13:27
  • 1
    I am new to Vim, hence, I couldnot express what I wanted clearly. Thanks for making it clear. – SibiCoder May 18 '16 at 13:35
  • I should have tried :nmap <bar> $a . that might work but that's no exactly what I wanted. – SibiCoder May 18 '16 at 13:38
10

You can use 'virtualedit' to allow moving to columns that don't contain text. If you set virtualedit=all, then 80| will place the cursor on column 80.

No spaces will be inserted until you actually perform some text editing there, though. If your sole goal is to just extend the line to an arbitrary column, then a simple mapping taking advantage of 'virtualedit' can do that.

nnoremap <Bar> <Bar>i <Esc>

Or if you only want 'virtualedit' active for the mapping, something like:

fun! ExpandLine(col)
    let ve = &ve
    set virtualedit=all
    exe 'normal! '.a:col.'|i '
    let &ve = ve
endfun
nnoremap <silent> <Bar> :<C-u>call ExpandLine(v:count)<CR>
  • 1
    //goal is to just extend the line to an arbitrary column// This is what I wanted. My intention is not to insert spaces. Now only I was reading about this. But didn't have idea how to use it :) – SibiCoder May 18 '16 at 13:20
6

There you go, a neat one-liner:

inoremap <bar> <esc>:execute "normal!".(input('Fill > ') - col('.'))."a "<CR>i

Decomposing:

inoremap <bar> <esc>:execute  " leave insert mode and execute
"normal!".                    " a normal command
(
  input('Fill > ')            " ask for the column to fill to
  - col('.')                  " subtract to the current column
)
."a "                         " append spaces
<CR>i                         " leave in insert mode

You can use it like this ([] is the cursor position):

 this is some text [|]

 Fill > 40
 this is some text         ... 40 spaces ...      []

Note: this has to be tested and improved, to handle the edge cases, and probably use this in a function, but you can start with that.

PS: Answer made when OP said he wanted to append space to move the cursor.

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.