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

In C - I want emacs to insert a new line between them when entering {and then}, and then set the cursor between them. For instance:

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, it should do what was described above, but when executing a for loop, or if an operator, for example, I want it to do the following:

 if (bla bla) { 

type} and ...:

 if (bla bla) { //cursor here } 
+4
source share
2 answers

If you don't mind that the behavior will only be almost, but not quite the way you described it, there is a built-in way to do this. This is an automatic printing feature that can be activated using the Cc Ca key combination or on this .emacs line:

 (c-toggle-auto-newline 1) 

The difference is that it will do reformatting right after entering the opening bracket {. When you finally enter the closing piece, it will also retreat correctly.

You also need to set the correct CC mode style. The cc-mode style seems to define things the way you described it. You can activate it using the Cc . key combination Cc . and then select cc-mode or the .emacs line

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

The c-mode functions are automatically loaded and therefore usually will not be available when loading the .emacs file. So you have to 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"))) 
+4
source

As for the material { :

 (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 .emacs . You can activate it with c-helpers-minor-mode .

Edit: The above inserts everything just by pressing { . The script below should do this 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 can try using yasnippet , which can be used in real time correctly.

+3
source

Source: https://habr.com/ru/post/1342309/


All Articles