Auto Indenting for OCaml Code in Vim with ocp-indent

Posted on In Linux, Programming, Software

The built-in indenting in Vim for OCaml seems not very good. How to set up auto indenting for OCaml code in Vim? ocp-indent works very well for me. This posts introduces how to configure Vim to use ocp-indent to automatically indent/format OCaml code.

First, install ocp-indent after installing opam:

$ opam install ocp-indent

Second, configure vim by adding these lines to your ~/.vimrc:

au BufEnter *.ml setf ocaml
au BufEnter *.mli setf ocaml
au FileType ocaml call FT_ocaml()
function FT_ocaml()
    set textwidth=80
    set colorcolumn=80
    set shiftwidth=2
    set tabstop=2
    " ocp-indent with ocp-indent-vim
    let opamshare=system("opam config var share | tr -d '\n'")
    execute "autocmd FileType ocaml source".opamshare."/vim/syntax/ocp-indent.vim"
    filetype indent on
    filetype plugin indent on
endfunction

You can use == to format the code selected or the current line now.

Third, to make ocp-indent be automatically invoked by autoindent, add the ocp-indent-vim script. This ensures that ocp-indent will indent the current line after you input Enter, “if”, “else”, etc. You can use tools like pathogen to manage the installed plugins in Vim.

Last, configuring the ocp-indent by adding these lines to ~/.ocp/ocp-indent.conf":

# These are `normal`, `apprentice` and `JaneStreet` and set different defaults.
JaneStreet

You may choose the other defaults. The JaneStreet mode works great for me.

Eric Ma

Eric is a systems guy. Eric is interested in building high-performance and scalable distributed systems and related technologies. The views or opinions expressed here are solely Eric's own and do not necessarily represent those of any third parties.

3 comments

  1. Update: newer version of `ocp-indent` changes the location of the ocp-indent.vim script. Updated the .vimrc config to reflect this change.

  2. Hello, Could you explain the third part in more detail? Specifically:

    (* I’m not clear on what the significance of this instruction is *)
    “You can use == to format the code selected or the current line now.”

    (* how do you “add” the script? *)
    “Third, to make ocp-indent be automatically invoked by autoindent, add the ocp-indent-vim script. This ensures that ocp-indent will indent the current line after you input Enter, “if”, “else”, etc. You can use tools like pathogen to manage the installed plugins in Vim.”

    Kindly,
    John

    1. > About “You can use == to format the code selected or the current line now.”

      Pressing `=` twice in command mode will make Vim help us indent the code (if it was not indented correctly).

      > About “add”ing the script:

      Pathogen is a Vim plugin manager. Now with latest Vim, I suggest to use Vim’s built-in package management instead: `:help packages`.

Leave a Reply

Your email address will not be published. Required fields are marked *