I'm trying to create a function to make editing TSV files easier. The function changes spacing settings, turns off wrapping, and creates a 1 row tall split at the top so that the column headers are always visible.

However I'm having trouble getting the two windows to bind on horizontal scroll. I can get them to bind when executing the commands manually but it doesn't work when I call the function.

fun! TSV()
  execute "setlocal nowrap"
  execute "setlocal noexpandtab"
  execute "setlocal shiftwidth=20"
  execute "setlocal softtabstop=20"
  execute "setlocal tabstop=20"
  " always visible header
  execute "sp"
  execute "0"
  call feedkeys("\<C-W>K")
  call feedkeys("1\<C-W>_")
  call feedkeys("\<C-W>j")
  " bind horizontal scrolling
  execute "set scrollopt=hor"
  execute "set scrollbind"
  call feedkeys("\<C-W>k")
  execute "set scrollbind"
  call feedkeys("\<C-W>j")
endfun
  • 1
    You probably don’t need many of those execute statements. – D. Ben Knoble Oct 10 at 18:40
up vote 2 down vote accepted

I think that your feedkeys() invocations write keys in the typeahead buffer, but they're not pressed immediately. Vim probably waits for the whole mapping and the function it calls to be processed.
You can tell feedkeys() to make Vim press the keys immediately by passing it the x flag (see :h feedkeys()). You may also want to pass the n flag to prevent custom mapping from interfering:

So, instead of writing:

call feedkeys("\<C-W>K")

You would write:

call feedkeys("\<C-W>K", 'nx')

But usually, to execute commands which affect windows, you use :wincmd:

call feedkeys("\<C-W>K", 'nx')
→
wincmd K

call feedkeys("1\<C-W>_", 'nx')
→
1wincmd _

call feedkeys("\<C-W>j", 'nx')
→
wincmd j

call feedkeys("\<C-W>k", 'nx')
→
wincmd k

So, you could try this function:

fun! TSV()
    setlocal nowrap
    setlocal noexpandtab
    setlocal shiftwidth=20
    setlocal softtabstop=20
    setlocal tabstop=20
    " always visible header
    sp
    0
    wincmd K
    1wincmd _
    wincmd j
    " bind horizontal scrolling
    set scrollopt=hor
    set scrollbind
    wincmd k
    set scrollbind
    wincmd j
endfun

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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