0

Consider the following function

function! AbbreviationsOpen()
   "go to the first word of the last line
   normal G 

   "store the word in the register named a
   let @a = expand('<cword>') 

   "display the word in the command line
   execute "normal :<C-R>a" 
endfunction`

The last line of the above function (execute ...) is not taking any effect. However, if I use the following function

function! AbbreviationsOpen()
    "go to the first word of the last line
    normal G 

    "store the word in the register named a
    let @a = expand('<cword>') 
endfunction`

and then press the following keys :<ctrl>ra then I do get the word appearing on the command line.

So can somebody help me as to why the above function does not work?

Also, I do not want to use a register. I'd like to achieve this using a variable. So the the function I want to write should look like.

function! AbbreviationsOpen()
    "go to the first word of the last line
    normal G 

    "store the word in the register named a
    let var = expand('<cword>') 

    SOMETHING
endfunction`
  • How is your function called? Depending of the context, you may not be able to move the cursor. It's best to work with things like matchstr(getline('$'), '^\S\+') to avoid side effects – Luc Hermitte Jul 10 '18 at 10:25
  • This isn't your main issue, but you didn't mention how you entered <C-R> in the last line of your function. Unless you entered it by pressing Ctrl-V followed by Ctrl-R then that won't work, either. An easier way to use control characters in a string is to use Vim's special escapes: "\<C-R>" evaluates to a single Ctrl-R character. See :help string. – Rich Jul 10 '18 at 10:36
1

The problem is that you can't use :normal to enter command-line mode, because it expects a "complete" command. (Try a simple :normal : to test this.)

I think you're looking for :help feedkeys():

" Start command-line mode populated with contents of the "a register
call feedkeys(':' . @a)

" Start command-line mode populated with contents of the var variable
call feedkeys(':' . var)

Alternatively, presuming you're invoking your function from a mapping, you could also use an expression mapping to enter text into the command line. However, note that you cannot move the cursor in an expression mapping, so you would need to alter the rest of your function slightly:

function! AbbreviationsOpen()
  let var = split(getline('$'), ' ')[0]
  return ':'.var
endfunction

nnoremap <expr> <leader>a AbbreviationsOpen()

See :help map-expression for more details.

  • The feedkeys works great. Your answer really helped. I'll accept in some time. – caffeinemachine Jul 10 '18 at 11:29

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.