How do I automatically create matching braces in vim?
This problem is non-trivial, as you will see. The simple answer is: Use a plugin, like autoclose or smartinput. Just naively remapping the ( [ .. keys will present you with edgecases in a couple of lines, that is why these plugins are made, and why they usually are quite complex (if they are any good).
So I used UltiSnips to insert the closing brace
You could try this instead (which is different from my original suggestion):
inoremap ( ()<CR>=UltiSnips_Anon('$1)$0', ')')<CR>
Where UltiSnips will split the line on (
instead of including main
in the match. The problem with using a snippet plugin for this is that they (usually) don't support nesting, so they will forget any jump positions when the next (nested) snippet is inserted.
To jump out of the brace pair the combination Ctrl-j is used.
You can remap Ctrl-j for either UltiSnips or the conflicting plugin. If the mappings are not listed in the documentation, you can use :map/imap/nmap <key>
to show the mapping. If you want Ctrl-j to pick and choose and do the work of both plugins, you are asking for:
- something a lot more advanced than I suspect you might think
- something I suspect you do not really want
Consider this bash loop:
while (( ${arr1[i]} < ${arr2[i<CURSOR>]} )); do
[next_snippet_position_marker]
done
In this case, you'll need to press Ctrl-j 5 times to get to the loop body. Using the closing braces to jump out of a corresponding pair gives you much more control of where you actually want the cursor to move. You could implement a stack to keep track of inserted pairs and use Ctrl-j to pop and move, but then you'll run into problems if you start manually deleting braces without removing them from the stack. So you'll start solving problems which the brace-plugins are trying to solve. This is a hard wheel to reinvent.
Expanding on this, you can get what you initially asked for, using Ctrl-j to jump out of braces and snippets. If you use some dummy value to represent snippets positions and push them onto the stack in addition to the closing braces, with dynamic remapping of Ctrl-j to correspond to handing of snippets or braces. But then you'll need to implement some fairly advanced heuristics to figure out what magic should happen, since you are essentially taking on two problems at once, which is currently being solved by the creators of snippet insertion plugins and brace matching plugins separately, and re-solving these problems again, on top of their solutions, to achieve convenience and, well, magic.
It comes down to control vs convenience. I think control will serve you better in this case, meaning you should keep these problems and their associated plugins and keysmappings separate. If you still want convenience, it's doable, but it's hard.
)
, remappingc-j
to that might work.