solyd
solyd

Reputation: 792

Emacs auto compelete paren, indent and new line - how to?

In C - I want that when I type a { and then } emacs will insert a new line between them and then set the cursor in between them. For example:

int main() {

now I type } and the following happens:

int main() 
{
    //cursor is here
}

Edit: forgot to mention - I want emacs to know that when defining a function that it should do what was described above but when doing a for loop, or if statement for example I want it to do the following:

if (bla bla) {

type } and... :

if (bla bla) {
     //cursor here
}

Upvotes: 4

Views: 1762

Answers (2)

Rörd
Rörd

Reputation: 6681

If you don't mind that the behaviour will be only almost, but not exactly the way you described it, there is a built-in way to do that. It's the auto-newline feature, that can be activated with the key combination C-c C-a or this line your .emacs:

(c-toggle-auto-newline 1)

The difference is that it will do the reformatting right after entering the opening brace {. When you finally enter the closing brace, it will indent it the right way, too.

You also need to set the right CC Mode style. The style "cc-mode" seems to define things the way you described it. You can activate it with the key combination C-c . and then choosing cc-mode, or the .emacs line

(c-set-style "cc-mode")

The c-mode functions are autoloaded and will therefore usually not be available while loading the .emacs file. Therefore you should wrap them in a hook for c-mode, like this

(add-hook 'c-mode-hook
          (lambda ()
            (c-toggle-auto-newline 1)
            (c-set-style "cc-mode")))

Upvotes: 4

phimuemue
phimuemue

Reputation: 35983

As for the { stuff:

(define-minor-mode c-helpers-minor-mode
  "This mode contains little helpers for C developement"
  nil
  ""
  '(((kbd "{") . insert-c-block-parentheses))
)

(defun insert-c-block-parentheses ()
  (interactive)
  (insert "{")
  (newline)
  (newline)
  (insert "}")
  (indent-for-tab-command)
  (previous-line)
  (indent-for-tab-command)
  )

Paste the above into your .emacs. You can activate it with c-helpers-minor-mode.

Edit: The above inserts everything by just pressing {. The script below should do it if you type {}:

(defun insert-latex-brackets (opening closing)                      ; prototype function for all enclosing things
  (interactive)
  (insert opening)
  (insert "  ")
  (insert closing)
  (backward-char (+ 1 (length closing )))
  )

(defun check-char-and-insert (char opening closing)
  (interactive)
  (if (equal char (char-to-string (char-before (point))))
      (progn (delete-backward-char 1)
         (insert-latex-brackets opening closing))
    (insert char)
  )
)

(local-set-key (kbd "}") 'check-char-and-insert)

One last note: You could try using yasnippet, which can be a real time saver used properly.

Upvotes: 3

Related Questions