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

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

auto indenting code blocks


From: Sam Halliday
Subject: auto indenting code blocks
Date: Sat, 13 Jun 2015 03:40:16 -0700 (PDT)
User-agent: G2/1.0

Hi all,

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.

For example, let's say we start with this (point denoted by pipe)

  blah |

Type `{' and smart-parens will insert the closing brace

  blah {|}

I'd actually prefer it to be, so if anybody knows how to do that I'd be greatly 
appreciative of their advice.

  blah { | }

Then I hit newline and this happens

  blah {
  |}

But I *actually* want

  blah {
    |
  }


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?



(defun scala-block-indent ()
  "It is convenient for newlines that follow a curly bracket to be indented."
  (when (and (eq major-mode 'scala-mode)
             ;; ordered for performance
             (looking-at "}") (looking-back "{[[:space:]]*\n"))
    (indent-according-to-mode)
    (forward-line -1)
    (move-end-of-line nil)
    (newline-and-indent)))
(add-hook 'post-self-insert-hook 'scala-block-indent)

(defun scala-block-pad ()
  "It is convenient for spaces following a brace to be space padded."
  (when (and (eq major-mode 'scala-mode)
             ;; ordered for performance
             (looking-at "}") (looking-back "{[[:space:]]"))
    (insert-char ?\s)
    (backward-char)))
(add-hook 'post-self-insert-hook 'scala-block-pad)

Best regards,
Sam


reply via email to

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