Reputation: 345
I'm new to using emacs as I've been using Visual Studio before. Is there a way to have the same kind of autocompletion for curly brackets in emacs ?
What I mean is, in Visual Studio if type this ("|" being the cursor) :
int foo()
{|
I get this :
int foo()
{
|
}
I tried using electric-pair-mode but it just closes the curly bracket. I hope I've been clear, english is not my native language.
EDIT :
@Rupert Swarbrick the electric-pair-open-newline-between-pairs
doesn't seem to be set to true in my emacs. When I have electric-pair-mode
enabled and that I press return
after the bracket I get this :
int foo()
{
|}
The cursor is on the same line as the closing bracket and I have to manually go to the line above to write the code which is a bit annoying.
Where can I modify electric-pair-mode
to check if it's set to true ? I haven't found it.
EDIT 2:
Thanks to @Rupert Swarbrick for his help, I'm using autopair.el
for now since I'm using emacs 24.3, it does what I wanted. For people using emacs 24.4 or higher electric-pair-mode
has been upgraded and you can use what Rupert said.
Upvotes: 1
Views: 346
Reputation: 2803
Looking at the guts of electric-pair-mode
, it doesn't appear that you can do so by customising any variables, but all is not lost! If electric-pair-open-newline-between-pairs
is true (the default) then you'll find that typing {
then the return key should give you the
{
<- cursor here
}
that you want.
To avoid having to type the extra newline, we want to pretend that the user typed it immediately after typing the opening {
. To do so, we can write the function below. This checks that electric-pair-mode
is enabled, that we are expecting to open new lines between pairs (that if
block is copied from the logic in elec-pair.el
), that the user just typed a {
and that we're sitting in a {}
pair (the closing }
will have been added by electric pair mode already. If these things are all true, it calls the newline
function. The second argument specifies that it should behave as if the user actually typed the newline (rather than just inserting \n
and stopping). At that point, the normal electric-pair-mode
code runs and reindents everything as we want.
Finally, we need to make sure that this runs at the right time. One way to do so is to add it as "advice" to electric-pair-post-self-insert-function
. That way, it will run at the right time whenever electric pair mode is enabled.
Stick the following elisp code in your .emacs
and try it out:
(defun electric-pair-brace-fixup ()
(when (and electric-pair-mode
(if (functionp electric-pair-open-newline-between-pairs)
(funcall electric-pair-open-newline-between-pairs)
electric-pair-open-newline-between-pairs)
(eq last-command-event ?\{)
(= ?\{ (char-before)) (= ?\} (char-after)))
(newline nil t)))
(advice-add 'electric-pair-post-self-insert-function :after
#'electric-pair-brace-fixup)
Upvotes: 0