0

How can I write a function that can be invoked in normal mode with regular keystrokes like {myNumber}<Leader>p, and prints {myNumber} into the current buffer.


For example: here's a command to format highlighted text to a variable width (dubiously useful, but an effective POC)

vnoremap 80w <ESC>:set textwidth=80<CR>'<gq'>, which turns the visual mode keystroke 80w to a command: wrap the visually selected text to 80 columns.

I want to make this a function that takes user input instead of the hard-coded value of 80. Furthermore, as a function I wouldn't have to clobber the value of textwidth.

So I ask: how do I read the number that comes before a keystroke as a argument to a function?


edit: here's the setup that I'm now using:

function! SetTabs(num)
  let myCommand = printf("set tabstop=%d softtabstop=%d shiftwidth=%d",
\   a:num, a:num, a:num)
  execute l:myCommand
  echo "Changed tabs to be worth " . a:num
endfunction

noremap <Leader>tab :<C-u>call SetTabs(v:count1)<CR>
2

You can use v:count/v:count1 to get the current count. Use execute/let to accomplish these type of mappings:

xnoremap <leader>w :<c-u>execute 'set textwidth='.v:count<cr>gvgq
xnoremap <leader>w :<c-u>let &textwidth=v:count<cr>gvgq

For more information see:

:h v:count
:h v:count1
:h :execute
:h c_CTRL-U
:h :let-&
:h gv

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.