0

My problem is that Emacs incorrectly indents the braces for C# methods, like this:

static string LOL()
    {

    }

then I have to manually correct it to

static string LOL()
{

}

I have read similar questions where the indentation is incorrect for if-statements and co. In my case the indentation works correctly. In spirit of those answers I have added these entries to my init.el

(defun my/c-mode-common-hook ()
  "Correct the expression indentation for c-style methods"
  (setq c-basic-offset 4)
  (c-set-offset 'substatement-open 0))

(use-package csharp-mode
  :mode "\\.cs\\'"
  :ensure t
  :defer t
  :init 
  (use-package omnisharp)
  (add-hook 'c-mode-common-hook #'my/c-mode-common-hook)
  :config
  (add-hook 'csharp-mode-hook 'omnisharp-mode)
  (add-hook 'after-init-hook 'global-company-mode)
  (company-omnisharp t))

How can I make Emacs use correct indentation for these braces?

Drew
  • 75,699
  • 9
  • 109
  • 225

1 Answers1

1

This is not an auto-indentation problem, but rather one of electric indentation. To understand why, you must break down user input for this case into more steps, I'll demonstrate with an if example and | denoting the cursor:

if (42)| // RET
if (42)
| // auto-indent
if (42)
    | // {
if (42)
    {| // indent
if (42)
{|

To automatically get from the second-to-last to the last, you must have some way to trigger a reindent of the current from typing {. This is provided by cc-derived modes, provided you have electric-indent-mode active. To find out whether it will work, do F1 k { and make sure it's not bound to self-insert-command. This has been broken in csharp-mode for some time, but should no longer be. More discussion can be found on https://github.com/josteink/csharp-mode/issues/115 and the linked issues.

wasamasa
  • 21,803
  • 1
  • 65
  • 97
  • For class, if, for etc structures this works like you explained, electric-indent-mode is active. Still only for methods this fails... The F1 k { gives out { runs the command c-electric-brace, which is an interactive compiled Lisp function in ‘cc-cmds.el’. It is bound to }, {. (c-electric-brace ARG) Insert a brace. This strange behaviour applies also if I C-x h TAB. – Divus Metaphysica Jul 28 '17 at 05:29
  • EDIT: I might also add that on my home computer with spacemacs I don't have this problem. – Divus Metaphysica Jul 28 '17 at 05:50
  • Time for you to make sure both are using the latest version of csharp-mode and if they do, delete and reinstall to make sure. – wasamasa Jul 28 '17 at 17:18