Reputation: 1027
I'm trying to duplicate the functionality in vim of IDEs like IntelliJ that do the following, letting | be the cursor:
I have the following set of remappings that duplicate the functionality of 1-3 and when I just type ():
inoremap ( ()<Esc>i
inoremap () ()<Esc>i
It seems I need a way to detect if the character after my cursor is a ) in order to make a function to do what I want in 4. Does vim support this?
Upvotes: 1
Views: 180
Reputation: 172778
There are many pitfalls to implement this functionality properly; several plugins have attempted to do this. At least you should check them out to learn what they did; maybe one of them already fulfills all of your requirements! You'll find a complete discussion of implementation details, and a list of plugins at Automatically append closing characters.
Upvotes: 3
Reputation: 177
Try this code
inoremap <expr> ) getline('.')[col('.') -1] == ')' ? "\<Right>" : ')'
But I recommend to use plugin, because such settings make your vimrc in confusion.
I like vim-smartchr and vim-smartinput
Upvotes: 1
Reputation: 736
I don't believe you can do this through a simple map since you would need to incorporate some conditional logic to decide when and when not to add the closing parenthesis. Instead, you would have to define a function to do the heavy lifting and then map the closing parenthesis to call the function. Vim's help has some information about functions, but I've found this page to be an invaluable resource: http://learnvimscriptthehardway.stevelosh.com/
That said, there are number of vim plugins out there that already perform this type of functionality. The one that I use is called "auto-pairs" and can be found here: https://github.com/jiangmiao/auto-pairs. As a bonus, you can see the code if you're actually interested in how it works as opposed to just being interested in having the functionality itself.
Upvotes: 1