Indentation of “if” in Ocaml under Emacs

2019-07-25 11:24发布

问题:

I am coding Ocaml with Emacs, at the moment the setting of the indentation of if gives the following:

if cond1 then e1 else
  if cond2 then e2 else
    if cond3 then e3 else
      e4

I would like to realize the same format as Caml programming guidelines:

if cond1 then e1 else
if cond2 then e2 else
if cond3 then e3 else
e4

Could anyone tell me which parameter is related to that? Thank you

Edit1: here is my .emacs

回答1:

Something seems to be wrong. Are you using the caml-mode from the OCaml distribution ? Because I do and it indents according to the programming guidelines without setting any parameter. That's what I have in my .emacs (the mode is installed in ~/.emacs.d/caml-mode):

;; Caml mode
(setq load-path (cons "~/.emacs.d/caml-mode" load-path))
(setq auto-mode-alist (cons '("\\.ml[iylp]?" . caml-mode) auto-mode-alist))
(autoload 'caml-mode "caml" "Major mode for editing Caml code." t)
(autoload 'run-caml "inf-caml" "Run an inferior Caml process." t)
(autoload 'camldebug "camldebug" "Run the Caml debugger." t)
(if window-system (require 'caml-font))

If you are using tuareg-mode I cannot help you. Note however that, contrary to popular belief, the caml-mode from the distribution is perfectly fine and is still maintained by OCaml's authors.



回答2:

You can now use ocp-indent which will (almost always) respect the Caml programming guidelines. The only difference is that it will indent the last expression, to avoid confusing scoping errors:

if cond1 then e1 else
if cond2 then e2 else
if cond3 then e3 else
  e4;
e5


回答3:

You can set the variable tuareg-if-then-else-indent to 0 which will then indent your example as

if cond1 then e1 else
if cond2 then e2 else
if cond3 then e3 else
e4

I don't know if that causes other undesirable indentation in case you don't have nested if's though. You can also M-x customize-group RET tuareg RET to see all the indentation (and other) options.



回答4:

Are you not satisfied with the following?

if c1 then e1
else if c2 then e2
else if c3 then e3
else e4