OCAMLFORMAT(1)
π ocamlformat(1) β from the Ocamlformat Manual π
π NAME
ocamlformat β A tool to format OCaml code.
β¨ SYNOPSIS
ocamlformat [OPTION]β¦ [SRC]β¦
π DESCRIPTION
okay bestie, ocamlformat automatically formats OCaml code. That's the whole vibe. β¨
π OPTIONS (CODE FORMATTING STYLE)
Unless otherwise noted, any option --option=VAL detailed in this section can be set in many ways, its value is determined in the following order (of increasing priority): the default value is used if no other value is specified. The value of a boolean option --foo or --no-foo can be modified in an .ocamlformat configuration file with 'foo = {true,false}', it can be done for any other option with an 'option = VAL' line (*), or using the OCAMLFORMAT environment variable: OCAMLFORMAT=option=VAL,...,option=VAL, or as an optional parameter on the command line, or with a global [@@@ocamlformat "option=VAL"] attribute in the processed file, or with an [@@ocamlformat "option=VAL"] attribute on expression in the processed file.
(*) .ocamlformat files in current and all ancestor directories for each input file are used, applied from top to bottom, overriding the settings each time a file is applied, stopping at the project root. If no project root and no ocamlformat file has been found, and if the option enable-outside-detected-project is set, the global ocamlformat file defined in $XDG_CONFIG_HOME (or in $HOME/.config if $XDG_CONFIG_HOME is undefined) is used.
If the disable option is not set, an .ocamlformat-ignore file specifies files that OCamlFormat should ignore. Each line in an .ocamlformat-ignore file specifies a filename relative to the directory containing the .ocamlformat-ignore file. Shell-style regular expressions are supported. Lines starting with # are ignored and can be used as comments.
If the disable option is set, an .ocamlformat-enable file specifies files that OCamlFormat should format even when the disable option is set. Each line in an .ocamlformat-enable file specifies a filename relative to the directory containing the .ocamlformat-enable file. Shell-style regular expressions are supported. Lines starting with # are ignored and can be used as comments.
--assignment-operator={end-line|begin-line}β Position of the assignment operator.end-linepositions assignment operators (:=and<-) at the end of the line and breaks after it if the whole assignment expression does not fit on a single line.begin-linepositions assignment operators (:=and<-) at the beginning of the line and breaks before it if the whole assignment expression does not fit on a single line. The default value isend-line.--break-before-in={fit-or-vertical|auto}β Whether the line should break before theinkeyword of aletbinding.fit-or-verticalwill always break the line before theinkeyword if the wholeletbinding does not fit on a single line.autowill only break the line if theinkeyword does not fit on the previous line. The default value isfit-or-vertical.--break-cases={fit|nested|toplevel|fit-or-vertical|vertical|all}β Break pattern match cases. Specifyingfitlets pattern matches break at the margin naturally.nestedforces a break after nested or-patterns to highlight the case body. Note that withnested, theindicate-nested-or-patternsoption is not needed, and so ignored.toplevelforces top-level cases (i.e. not nested or-patterns) to break across lines, otherwise break naturally at the margin.fit-or-verticaltries to fit all or-patterns on the same line, otherwise breaks.verticalvertically breaks branches.allforces all pattern matches to break across lines. The default value isfit.--break-collection-expressions={fit-or-vertical|wrap}β Break collection expressions (lists and arrays) elements by elements.fit-or-verticalvertically breaks expressions if they do not fit on a single line.wrapwill group simple expressions and try to format them in a single line. The default value isfit-or-vertical.--break-colon={after|before}β Break before or after colon in value binding declarations and type constraints.afterbreaks after the colon.beforebreaks before the colon. The default value isafter.--break-fun-decl={wrap|fit-or-vertical|smart}β Style for function declarations and types.wrapbreaks only if necessary.fit-or-verticalvertically breaks arguments if they do not fit on a single line.smartis likefit-or-verticalbut try to fit arguments on their line if they fit. The default value iswrap.--break-fun-sig={wrap|fit-or-vertical|smart}β Style for function signatures.wrapbreaks only if necessary.fit-or-verticalvertically breaks arguments if they do not fit on a single line.smartis likefit-or-verticalbut try to fit arguments on their line if they fit. The default value iswrap.--break-infix={wrap|fit-or-vertical|wrap-or-vertical}β Break sequence of infix operators.wrapwill group simple expressions and try to format them in a single line.fit-or-verticalvertically breaks expressions if they do not fit on a single line.wrap-or-verticalbehaves likewrapfor high precedence operators and behaves likefit-or-verticalfor low precedence operators. The default value iswrap.--break-infix-before-funcβ Break infix operators whose right arguments are anonymous functions specially: do not break after the operator so that the first line of the function appears docked at the end of line after the operator. The flag is unset by default.--break-separators={after|before}β Break before or after separators such as;in list or record expressions.afterbreaks the expressions after the separator.beforebreaks the expressions before the separator. The default value isafter.--break-sequencesβ Force sequence expressions to break irrespective of margin. The flag is set by default.--break-string-literals={auto|never}β Break string literals.automode breaks lines at newlines and wraps string literals at the margin.nevermode formats string literals as they are parsed, in particular, with escape sequences expanded. The default value isauto.--break-struct={force|natural}β Breakstruct-end andsig-end items.forcewill break items unconditionally.naturalwill break items naturally at the margin. The default value isforce.--cases-exp-indent=COLSβ Indentation of cases expressions (COLScolumns). See also thecases-matching-exp-indentandnested-matchoptions. The default value is4. Cannot be set in attributes.--cases-matching-exp-indent={normal|compact}β Indentation of cases right-hand sides which arematchortryexpressions.normalindents as it would any other expression.compactforces an indentation of2, unlessnested-matchis set toalignand we're on the last case. The default value isnormal.--disambiguate-non-breaking-matchβ Add parentheses around matching constructs that fit on a single line. The flag is unset by default.--doc-comments={after-when-possible|before-except-val|before}β Doc comments position.after-when-possibleputs doc comments after the corresponding code. This option has no effect on variant declarations because that would change their meaning and on structures, signatures and objects for readability.before-except-valputs doc comments before the corresponding code, but puts doc comments ofvalandexternaldeclarations after the corresponding declarations.beforeputs comments before the corresponding code. The default value isafter-when-possible.--doc-comments-padding=PADDINGβ AddPADDINGspaces before doc comments in type declarations. The default value is2.--doc-comments-tag-only={default|fit}β Position of doc comments with only tags.defaultmeans no special treatment.fitputs doc comments on the same line. The default value isdefault.--dock-collection-bracketsβ Dock the brackets of lists, arrays and records, so that when the collection does not fit on a single line the brackets are opened on the preceding line and closed on the following line. The flag is set by default.--exp-grouping={preserve|parens}β Style of expression grouping.preservepreserves the original grouping syntax (parentheses orbegin/end).parensgroups expressions using parentheses. The default value ispreserve. Cannot be set in attributes.--extension-indent=COLSβ Indentation of items inside extension nodes (COLScolumns). The default value is2.--field-space={loose|tight|tight-decl}β Whether or not to use a space between a field name and the punctuation symbol (:or=) preceding the rhs. This option affects records and objects.looseuses a space.tightdoes not use a space.tight-declis tight for declarations and loose for instantiations. The default value isloose.--function-indent=COLSβ Indentation of function cases (COLScolumns). The default value is2.--function-indent-nested={never|always|auto}β Whether thefunction-indentparameter should be applied even when in a sub-block.neveronly appliesfunction-indentif the function block starts a line.alwaysalways applyfunction-indent.autoappliesfunction-indentwhen seen fit. The default value isnever.--if-then-else={compact|fit-or-vertical|vertical|keyword-first|k-r}β If-then-else formatting.compacttries to format an if-then-else expression on a single line.fit-or-verticalvertically breaks branches if they do not fit on a single line.verticalalways vertically breaks branches.keyword-firstformats if-then-else expressions such that the if-then-else keywords are the first on the line.k-rformats if-then-else expressions with parentheses that match the K&R style. The default value iscompact.--indent-after-in=COLSβ Indentation (COLScolumns) afterlet ... in, unless followed by anotherlet. The default value is0. Cannot be set in attributes.--indicate-multiline-delimiters={no|space|closing-on-separate-line}β How to indicate that two matching delimiters live on different lines.nodoesn't do anything special to indicate the closing delimiter.spaceprints a space inside the delimiter to indicate the matching one is on a different line.closing-on-separate-linemakes sure that the closing delimiter is on its own line. The default value isno.--indicate-nested-or-patterns={unsafe-no|space}β¨ β do we flag nested or-patterns with indentation or nah?unsafe-noliterally does not indicate nested or-patterns at all. Warning incoming bestie: this can produce confusing code where a short body of a match case is visually hidden by surrounding long patterns, leading to misassociation between patterns and body expressions π.spacestarts lines of nested or-patterns with" |"rather than"| ". Default?unsafe-no, iykyk.--infix-precedence={indent|parens}π β disambiguate precedences of infix operators, but how?indentuses indentation to explicitly disambiguate precedences of infix operators.parensuses parentheses to explicitly disambiguate precedences of infix operators. Default isindent.--leading-nested-match-parensπ β nested match parens formatting, periodt. The flag is unset by default. Cannot be set in attributes.--let-and={compact|sparse}β style oflet_and.compactwill try to format`let p = e and p = e`in a single line.sparsewill always break between them. Default iscompact.--let-binding-deindent-funπ¦ β deindent a line beginning withfun. Set by default (so yes babe, it's on).--let-binding-indent=COLSβ indentation of let binding expressions (COLScolumns) if they don't fit on a single line. Default is2. Cannot be set in attributes.--let-binding-spacing={compact|sparse|double-semicolon}πΈ β spacing between let bindings.compactspacing separates adjacent let bindings in a module according tomodule-item-spacing.sparseplaces two open lines between a multi-line module-level let binding and the next.double-semicolonplaces double semicolons and an open line between a multi-line module-level let binding and the next. Default iscompact.--let-module={compact|sparse}β module binding formatting.compactdoes not break a line after thelet module ... =and before theinif the module declaration does not fit on a single line.sparsebreaks a line afterlet module ... =and before theinif the module declaration does not fit on a single line. Default iscompact.--letop-punning={preserve|always|never}π β name punning in bindings using extended let operators andlet%extbindings.preserveuses let-punning only when it exists in the source; the code"let* foo and* z = z in ..."will be left unchanged.alwaysuses let-punning whenever possible; the code"let* foo and* z = z in ..."will be rewritten to"let* foo and* z in ...".nevernever uses let-punning (yes, never means never bestie); the code"let* foo and* z = z in ..."will be rewritten to"let* foo = foo and* z = z in ...". Default ispreserve.--line-endings={lf|crlf}π β line endings used.lfuses Unix line endings.crlfuses Windows line endings. Default islf. Cannot be set in attributes.-m COLS,--margin=COLSβ format code to fit withinCOLScolumns. Default is80. Cannot be set in attributes.--match-indent=COLSβ indentation of match/try cases (COLScolumns). Default is0.--match-indent-nested={never|always|auto}β¨ β should thematch-indentparameter be applied even when we're in a sub-block?neveronly appliesmatch-indentif the match block starts a line.alwaysalways appliesmatch-indent(shocking, I know).autoappliesmatch-indentwhen seen fit. Default isnever.--max-indent=COLSβ maximum offset (COLScolumns) added to a new line in addition to the offset of the previous line. Default is68. Cannot be set in attributes.--module-indent=COLSβ indentation of items withinstruct ... endandsig ... end(COLScolumns). Default is2.--module-item-spacing={compact|sparse|preserve}π«Ά β spacing between items of structures and signatures.compactwill not leave open lines between one-liners of similar sorts.sparsewill always break a line between two items.preservewill not leave open lines between one-liners of similar sorts unless there is an open line in the input. Default iscompact.--nested-match={wrap|align}π β style of a pattern-matching nested in the last case of another pattern-matching.wrapwraps the nested pattern-matching with parentheses and adds indentation.alignvertically aligns the nested pattern-matching under the encompassing pattern-matching. Default iswrap.--no-break-infix-before-funcβ unsetbreak-infix-before-func.--no-break-sequencesβ unsetbreak-sequences.--no-disambiguate-non-breaking-matchβ unsetdisambiguate-non-breaking-match.--no-dock-collection-bracketsβ unsetdock-collection-brackets.--no-leading-nested-match-parensβ unsetleading-nested-match-parens.--no-let-binding-deindent-funβ unsetlet-binding-deindent-fun.--no-ocp-indent-compatβ unsetocp-indent-compat.--no-parens-iteβ unsetparens-ite.--no-parse-docstringsβ unsetparse-docstrings.--no-parse-toplevel-phrasesβ unsetparse-toplevel-phrases.--no-space-around-arraysβ unsetspace-around-arrays.--no-space-around-listsβ unsetspace-around-lists.--no-space-around-recordsβ unsetspace-around-records.--no-space-around-variantsβ unsetspace-around-variants.--no-wrap-commentsβ unsetwrap-comments.--no-wrap-fun-argsβ unsetwrap-fun-args.--ocp-indent-compatπ¦ β attempt to generate output which does not change (much) when post-processing withocp-indent. The flag is unset by default.-p {default|conventional|ocamlformat|janestreet},--profile={default|conventional|ocamlformat|janestreet}π β select a preset profile which sets all options, overriding lower priority configuration.defaultis an alias for theconventionalprofile. Theconventionalprofile aims to be as familiar and"conventional"appearing as the available options allow. Theocamlformatprofile aims to take advantage of the strengths of a parsetree-based auto-formatter, and to limit the consequences of the weaknesses imposed by the current implementation. This is a style which optimizes for what the formatter can do best, rather than to match the style of any existing code. General guidelines that have directed the design include: Legibility, in the sense of making it as hard as possible for quick visual parsing to give the wrong interpretation, is of highest priority; Whenever possible the high-level structure of the code should be obvious by looking only at the left margin, in particular, it should not be necessary to visually jump from left to right hunting for critical keywords, tokens, etc; All else equal compact code is preferred as reading without scrolling is easier, so indentation or white space is avoided unless it helps legibility; Attention has been given to making some syntactic gotchas visually obvious. Thejanestreetprofile is used at Jane Street. Default value isdefault.--parens-iteβ¨ β uses parentheses around if-then-else branches that spread across multiple lines. The flag is unset by default.--parens-tuple={always|multi-line-only}β parens tuple expressions.alwaysalways uses parentheses around tuples.multi-line-onlymode will try to skip parens for single-line tuples. Default isalways.--parens-tuple-patterns={multi-line-only|always}β parens tuple patterns.multi-line-onlymode will try to skip parens for single-line tuple patterns.alwaysalways uses parentheses around tuples patterns. Default ismulti-line-only.--parse-docstringsπΈ β parse and format docstrings. The flag is set by default.--parse-toplevel-phrasesβ parse and format toplevel phrases and their output. The flag is unset by default.--sequence-blank-line={preserve-one|compact}π β blank line between expressions of a sequence.preservewill keep a blank line between two expressions of a sequence if the input contains at least one.compactwill not keep any blank line between expressions of a sequence. Default ispreserve-one.--sequence-style={terminator|separator|before}β style of sequence.terminatoronly puts spaces after semicolons.separatorputs spaces before and after semicolons.beforebreaks the sequence before semicolons. Default isterminator.--single-case={compact|sparse}π β style of pattern matching expressions with only a single case.compactwill try to format a single case on a single line.sparsewill always break the line before a single case. Default iscompact.--space-around-arraysβ add a space inside the delimiters of arrays. The flag is set by default.--space-around-listsπ β add a space inside the delimiters of lists. The flag is set by default.--space-around-recordsβ add a space inside the delimiters of records. The flag is set by default.--space-around-variantsπ β add a space inside the delimiters of variants. The flag is set by default.--stritem-extension-indent=COLSβ indentation of structure items inside extension nodes (COLScolumns). Default is0.--type-decl={compact|sparse}β¨ β style of type declaration.compactwill try to format constructors and records definition in a single line.sparsewill always break between constructors and record fields. Default iscompact.--type-decl-indent=COLSβ indentation of type declarations (COLScolumns) if they do not fit on a single line. Default is2. Cannot be set in attributes.--wrap-commentsπ«Ά β comments are divided into paragraphs by open lines (two or more consecutive newlines), and each paragraph is wrapped at the margin. Multi-line comments with vertically-aligned asterisks on the left margin are not wrapped. Consecutive comments with both left and right margin aligned are not wrapped either. The flag is unset by default β so this one's off unless you turn it on, bestie.--wrap-fun-argsβ style for function call. The flag is set by default.
π OPTIONS (REMOVED) π
okay bestie, buckle up, because this is the graveyard section πͺ¦β¨ these options literally do not exist anymore. if you're copying a config from 2019 off some blog, this is why it's screaming at you.
--align-cases=VALUEβ this option has been removed in version 0.22. gone. bye. π«Ά--align-constructors-decl=VALUEβ this option has been removed in version 0.22. no cap.--align-variants-decl=VALUEβ this option has been removed in version 0.22. it's giving deleted.--doc-comments-val=VALUEβ this option has been removed in version 0.16. and here's the migration lore, bestie, because it's a whole flowchart π:- if you were using
doc-comments-val=beforetogether withdoc-comments=before, then now you only needdoc-comments=beforeto achieve the same behavior. - if you were using
doc-comments-val=beforetogether withdoc-comments=after, that behavior is not available anymore. periodt. - if you were using
doc-comments-val=aftertogether withdoc-comments=before, please now usedoc-comments=before-except-val. - if you were using
doc-comments-val=aftertogether withdoc-comments=after, then now you only needdoc-comments=after-when-possibleto achieve the same behavior. - if you were using
doc-comments-val=unset, the same behavior can now be achieved by settingdoc-commentsonly.
- if you were using
--escape-chars=VALUEβ this option has been removed in version 0.16. concrete syntax will now always be preserved. so you literally never have to think about it again π--escape-strings=VALUEβ this option has been removed in version 0.16. concrete syntax will now always be preserved.--extension-sugar=VALUEβ this option has been removed in version 0.17. concrete syntax will now always be preserved.--let-open=VALUEβ this option has been removed in version 0.17. concrete syntax will now always be preserved.
β¨ OPTIONS β¨
heads up bestie: unless the docs say otherwise, non-formatting options cannot be set in attributes or in .ocamlformat files. iykyk.
-c =[,β¦],--config==[,β¦](absentOCAMLFORMATenv) β the aggregate option, the group-chat of options π«Ά. you pass a comma-separated list of pairs like this:option=VAL,...,option=VAL.--checkβ checks whether the input files are already formatted. mutually exclusive with--inplaceand--output(pick a lane, bestie π€).--comment-checkβ controls whether comments and documentation comments get checked. unsafe to turn off. may be set in.ocamlformat. the flag is set by default.--disableβ disablesocamlformat. this is the one you drop into attributes to locally turn off automatic code formatting. you can also use[@@@ocamlformat "enable"]instead of[@@@ocamlformat "disable=false"]. the flag is unset by default.--disable-conf-attrsβ disables configuration in attributes. the flag is unset by default.--disable-conf-filesβ disables.ocamlformatconfiguration files. no config files, no notes π--disable-outside-detected-projectβ if no.ocamlformatconfig files have been detected, disable the formatting. OCamlFormat is disabled outside of a detected project by default, so if you want the opposite behavior, use--enable-outside-detected-project.--docβ parse input as an odoc documentation.--enable-outside-detected-projectβ read.ocamlformatconfig files outside the current project when no project root has been detected for the input file. so like, the project root of an input file is taken to be the nearest ancestor directory that contains a.gitor.hgordune-projectfile. if.ocamlformatconfig files are located in the same directory or in parents, they get applied; and if no.ocamlformatfile is found, then the global configuration defined in$XDG_CONFIG_HOME/.ocamlformat(or in$HOME/.config/.ocamlformatif$XDG_CONFIG_HOMEis undefined) is applied. the whole ancestry chain, iconic π-g,--debugβ generate debugging output. the flag is unset by default.-i,--inplaceβ format in-place, overwriting your input file(s). yes it really does just write over them, bestie π--ignore-invalid-optionβ ignore invalid options (e.g. in.ocamlformat). forgiveness era ποΈ--implβ parse input as an implementation.--intfβ parse input as an interface.--margin-checkβ emit a warning if the formatted output exceeds the margin. the flag is unset by default.-n N,--max-iters=Nβ fail if the output of formatting does not stabilize withinNiterations. may be set in.ocamlformat. the default value is10.--name=NAMEβ the name of the input file, used for error reporting and as the starting point when searching for.ocamlformatfiles. defaults to the input file name. some options can be specified in configuration files named.ocamlformatin the same or a parent directory ofNAMEβ see the documentation of the other options for details.--no-comment-checkβ unsetcomment-check.--no-debugβ unsetdebug.--no-disableβ unsetdisable.--no-disable-conf-attrsβ unsetdisable-conf-attrs.--no-margin-checkβ unsetmargin-check.--no-quietβ unsetquiet.--no-version-checkβ unsetversion-check.-o DST,--output=DSTβ output file. mutually exclusive with--inplace. writes to stdout if omitted (the default girlie behavior β¨).--ocaml-version=Vβ the version of OCaml syntax of the output. the default value is5.4.0.--ocp-indent-configβ read.ocp-indentconfiguration files. here's the translation table, study it bestie, there's a quiz later π:baseis an alias forlet-binding-indent.typeis an alias fortype-decl-indent.inis an alias forindent-after-in.withsetsfunction-indentandmatch-indent.match_clauseis an alias forcases-exp-indent.ppx_stritem_extis an alias forstritem-extension-indent.max_indentis an alias formax-indent.strict_withsetsfunction-indent-nestedandmatch-indent-nested.
--print-configβ print the configuration determined by the environment variable, the configuration files, preset profiles and the command line. attributes are not considered. if many input files are specified, it only prints the configuration for the first file. and if no input file is specified, it prints the configuration for the root directory if specified, or for the current working directory otherwise.-q,--quietβ quiet. may be set in.ocamlformat. the flag is unset by default.--repl-fileβ parse input as toplevel phrases with their output.--root=DIRβ the root of the project. if specified, only.ocamlformatconfiguration files insideDIRand its subdirectories are taken into account.--use-fileβ deprecated. same asimpl.--version-checkβ check that the version matches the one specified in.ocamlformat. the flag is set by default.SRCβ the input files. at least one is required, and exactly one is required without--inplace. if-is passed, it will read from stdin π«Ά
πΈ COMMON OPTIONS πΈ
--help[=FMT](default=auto) β show this help in formatFMT. the valueFMTmust be one ofauto,pager,grofforplain. withauto, the format ispagerorplainwhenever theTERMenv var isdumbor undefined.--versionβ show version information.
π EXIT STATUS π
ocamlformat exits with:
0β on success. we love a win β¨123β on indiscriminate errors reported on standard error.124β on command line parsing errors.125β on unexpected internal errors (bugs).
π¦ ENVIRONMENT π¦
these environment variables affect the execution of ocamlformat:
OCAMLFORMATβ see option--config.
and that's a wrap on the whole page, bestie!! you now know ocamlformat better than it knows itself π this was Ocamlformat 0.29.0, and you just read the OCAMLFORMAT(1) manual page. go forth and format, you absolute icon ππ
π«Ά
π¦ where this page comes from
- nixos 26.05: ocaml5.4.1-ocamlformat 0.29.0
- nixpkgs unstable: ocaml5.5.1-ocamlformat 0.29.0
- ubuntu stonking: ocamlformat 0.29.0-2build2 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms