help-gnu-emacs
[Top][All Lists]
Advanced

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: auto indenting code blocks


From: Yuri Khan
Subject: Re: auto indenting code blocks
Date: Sat, 13 Jun 2015 17:25:22 +0600

On Sat, Jun 13, 2015 at 4:40 PM, Sam Halliday <sam.halliday@gmail.com> wrote:

> I find it extremely convenient when writing Scala code (and this may be 
> relevant in all c-mode derivations) to be able to have my code blocks 
> automatically expanded.
>
> I have smart-parens installed, so when I type `{' the closing brace is placed 
> after point.
>
> But often I intend to write a multi-line block of code (this may well be the 
> norm in C and C++) and when I type newline I expect the second brace to be 
> moved down a line, indented, and the point placed, indented, in the middle.

I am solving this for C++ with the following ugly hack (BTW thanks for
pointing out “looking-back”):

===
(defun yk-electric-ret ()
  (interactive)
  (if (and (looking-at "\}") (looking-back "\{")))
      (progn
        (newline-and-indent)
        (save-excursion
          (newline-and-indent))
        (indent-according-to-mode))
    (newline-and-indent)))

(defun yk-braces-keys ()
  (local-set-key (kbd "RET") 'yk-electric-ret))
(add-hook 'c-mode-common-hook 'yk-braces-keys)
===

It is essentially equivalent to yours except that I prefer rebinding a
single key to watching for all buffer changes.

> I have cooked up a little post-self-insert-hook (see bottom of mail) but it 
> feels like I'm inventing some form of wheel.
>
>   1. is there an existing preferred way to do what my scala-block-indent is 
> trying to do?
>   2. is there an easier way (perhaps via smart-parens) to achieve what my 
> scala-block-pad is doing, but at the point when the closing brace is inserted?

I am also interested in answers to the above.

Additionally, it would be nice to be able to select a multi-line
region (def: a region that contains at least one line break), press
“{” and have it automatically enclose the region in a pair of braces,
add a line break immediately after the opening brace and another one
before the closing brace, and re-indent all affected lines according
to mode and style. (I could probably compose a function to that effect
and bind it to “{” instead of c-electric-brace or self-insert-command,
but that looks boring :])



reply via email to

[Prev in Thread] Current Thread [Next in Thread]