0

in my plugin, i am joining XML tags together depending on a mapping a use. It also uses so i can make XML snippets repetitive. After inserting the text into a buffer, i would like the cursor to return to the initial position from which I started the 'pasting', but somehow i cannot leave the insert mode.

The function looks like this:

function s:DocbkPrintTag(tag)
  "mark the initial position
  execute "normal! mq"
  let result = repeat(s:DocbkRenderTag(a:tag), v:count1)
  if !empty(result)
    call feedkeys('a' . result, 'n')
  endif
  "stop insert mode and resore the cursor position
  execute "normal! `q"
endfunction
0
  1. Instead of marking in normal mode, you can use :mark q
  2. Instead of entering insert mode to paste your data, try using either put =result (results on a new line), save the result into a register (let @a=result) and paste inline (normal! "ap), or match a part of the line to insert (e.g., at the beginning: substitute/^/\=result)
  3. You only need :execute with :normal if the command contains special characters or is computed. So the last line can be normal! `q

All of that said, it is easiest to use getcurpos and setpos (example at :help getcurpos()) for cursor saving and restoration.

  • Thank you. The register method works fine, but <CR> does not get translated and instead prints <listitem>^M<para>^M</para>^M</listitem>. Any idea how to get this fixed? – Tomáš Bažant Jul 3 at 8:47
  • Got it, need to use "\n" instead of "\<CR>" – Tomáš Bažant Jul 3 at 8:56
  • Got additional question: if i use register and paste the text, can i then format it as if i put the whole new block into a visual mode and ran '='? – Tomáš Bažant Jul 3 at 11:51
  • @TomášBažant = reindents, but yes you could – D. Ben Knoble Jul 3 at 12:17
1

DBK already show you how to fix it, so i explain only why your approach doesn't work here.

From :h feedkeys() :

The function does not wait for processing of keys contained in {string}.

To show you that:

nnoremap ,t :call <sid>foo()<cr>:echom 2<cr>
function! s:foo()
  echom 1
  call feedkeys(":echom 3\<cr>")
  echom 4
endfunction

Execute ,t, check message with :mes, you should see:

1
4
2
3

If you use i mode:

call feedkeys(":echom 3\<cr>", 'i')

You will see:

1
4
3
2

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.