Vim: pass a char or word to your function

I know that when you define a function in vim, you can use the range keyword so that users can say:

 :-5,+5call MyFunction() 

And then your function will receive: firstline and a: lastline.

What I want is something similar, but more like a traditional vi way of combining a command with movement, so that β€œd” removes the space, β€œdw” removes the word, β€œd2w” removes two words: β€œd2j 'removes three strings, etc. Assuming that my function maps to a sequence of characters in input mode, is there a way to get it to accept similar variable-length inputs, and then change that text?

To be a little more understandable, suppose I want to define a function for wrap <b> tags around existing text. We say that the function maps to: b. I want users to be able to say "; bw" for the boldness of a single word, or "; bf". for boldness, all the way to the end of the sentence or whatever, with all the flexibility that vim provides to built-in commands.

+4
source share
1 answer

If I understand what you are asking, then all you do is include the char argument in your mapping. For instance:

 map d :call MyFunction('d')<cr> map dw :call MyFunction('dw')<cr> map d2w :call MyFunction('d2w')<cr> " Of course these would be terrible mappings because they " are already mapped to important Vim functions 

The way mappings work is that if you β€œexceeded” char as β€œd” above to use it either on your own or as a prefix for a longer command, Vim will wait shortly (for timeoutlen ) after you press' d 'to see if you are going to click another character. (This depends on the timeout parameter set to true, which is the default.) If you do not press another character, Vim will display 'd'. If you do this, it will cause a more complex display. See :h map-commands and :h map-typing more details.

Note. After your clarification, I think that you want to create a user-defined function "operator" that you can use to work in the buffer zones defined by Vim movements. See :h map-operator for information on how to do this.

+2
source

Source: https://habr.com/ru/post/1332235/


All Articles