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?

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.

  • 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 5: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 5: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

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.