Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

New line and autoindent braces in ccmode in Emacs

Tags:

emacs

cc-mode

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?

like image 227
Juan Herrero Diaz Avatar asked Dec 06 '25 02:12

Juan Herrero Diaz


1 Answers

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 {.

like image 180
abo-abo Avatar answered Dec 09 '25 00:12

abo-abo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!