Reputation: 843
I'm using Emacs. I want that when I write this (| is the point):
for (int i=0; i<n; i++) {|
And I press Enter (or a different key, whatever), I get this:
for (int i=0; i<n; i++) {
|
}
So I can start typing right away the content of the block, and the block is automatically closed.
How can I do this?
Upvotes: 3
Views: 1572
Reputation: 4501
If you want to close character automatically, M-x electric-pair-mode
may be useful(Emacs version 24 or later required). Just try it and see it matches your need.
And I think below also may be helpful.
Set Emacs to smart auto-line after a parentheses pair?
Upvotes: 1
Reputation: 20342
Here's my C/C++ setup that solves your problem:
(defun ins-c++-curly ()
"Insert {}.
Threat is as function body when from endline before )"
(interactive)
(if (looking-back "\\()\\|try\\|else\\|const\\|:\\)$")
(progn
(insert " {\n\n}")
(indent-according-to-mode)
(forward-line -1)
(indent-according-to-mode))
(insert "{}")
(backward-char)))
(add-hook 'c-mode-common-hook 'my-c-common-hook)
(defun my-c-common-hook ()
(define-key c-mode-base-map "{" 'ins-c++-curly))
And here's the yasnippet for for
:
# -*- mode: snippet -*-
#name : for (...; ...; ...) { ... }
# --
for (unsigned int ${1:i}=0; $1<${2:N}; ++$1)$0
Note that the snippet doesn't do curly braces, so I can decide if I want them or just a single statement.
And just to show you the sequence of keys that leads me from zero to the code
in your question: for
C-o C-o C-o {.
Upvotes: 3