You can use an expression mapping that looks at the character after the cursor. Let's build that up.
Getting the character after your cursor
Using Vim's functions getline()
and getpos()
, we can figure out what character follows the cursor in Insert mode. getline('.')
returns the current line as a string, which we can index using []
notation.
To get the position of your cursor, you can use getpos('.')
. It returns an array including the buffer number, line number, column, and virtual offset of the cursor. Here, we're interested in the column, which we'll use as the index of the current line: getpos('.')[2]
.
Since the column number returned by getpos()
is 1-indexed and strings are 0-indexed, we have to subtract 1 from the column to get the index of character after our cursor in Insert mode. So all together, the expression getline('.')[getpos('.')[2] - 1]
represents the character after our cursor.
Building the mapping
With expression mappings, an expression is evaluated as a string to be used as the right-hand-side. We'll make an expression mapping that evaluates to <Right>
if the next character is )
, or the actual )
character otherwise.
inoremap <expr> ) getline('.')[getpos('.')[2] - 1] == ')' ? '<Right>' : ')'
Relevant documentation: