Language server for Odin. This project is still in early development.
Note: This project is made to be up to date with the master branch of Odin.
cd ols
# for windows
./build.bat
# To install the odinfmt formatter
./odinfmt.bat
# for linux and macos
./build.sh
# To install the odinfmt formatter
./odinfmt.shIn order for ols to find symbols for builtin types and procedures, the builtin folder in the repo needs to be located next to the ols binary. Alternatively you can specify the path to this folder using the OLS_BUILTIN_FOLDER environment variable.
In order for the language server to index your files, it must know about your collections.
To do that you can either configure ols via an ols.json file (it should be located at the root of your workspace).
Or you can provide the configuration via your editor of choice.
Example of ols.json:
{
"$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/ols.schema.json",
"collections": [
{ "name": "custom_collection", "path": "c:/path/to/collection" }
],
"enable_semantic_tokens": false,
"enable_document_symbols": true,
"enable_hover": true,
"enable_snippets": true,
"profile": "default",
"profiles": [
{ "name": "default", "checker_path": ["src"], "defines": { "ODIN_DEBUG": "false" }},
{ "name": "linux_profile", "os": "linux", "checker_path": ["src/main.odin"], "defines": { "ODIN_DEBUG": "false" }},
{ "name": "mac_profile", "os": "darwin", "arch": "arm64", "defines": { "ODIN_DEBUG": "false" }},
{ "name": "windows_profile", "os": "windows", "checker_path": ["src"], "defines": { "ODIN_DEBUG": "false" }}
]
}Options:
-
enable_format: Turns on formatting withodinfmt. (Enabled by default) -
enable_range_format: Format only the declarations that the selection touches. Defaults to true. -
enable_hover: Enables hover feature. (Enabled by default) -
enable_hover_layout: Show the memory layout (size, alignment, field offsets and padding) of types on hover. Computed by ols from the resolved types, for the configuredprofilearch. This feature is experimental and the reported layout may not always match the compiler. (Disabled by default) -
enable_document_symbols: Turns on outline of all your global declarations in your document. (Enabled by default) -
enable_fake_methods: Turn on fake methods completion. This is currently highly experimental and requires client snippet support. -
enable_postfix_completions: After a dot on a value, offer postfix templates and builtin orcoreprocedures that take the value, each replacing the expression. Templates:if,ifnot,noton bools;foron integers;forion arrays, slices, strings and maps;switchwith every case on enums;nilandnotnilon nilable values;^andfreeon pointers;orr(or_return),ore(or_else) anddeferon calls; and&,cast,transmute,paren,return,var,print,printf,logd,logi,logw,logeon any value. Procedures:delete,copyandraw_data, andstrings,strconvandslicehelpers such ass.containsforstrings.contains(s, …)andxs.sortforslice.sort(xs[:]), adding the import when the file lacks it. Statement templates appear only when the value starts its line. Every item appears only where the code it writes compiles:orrneeds a callee whose last result is a bool or nilable and an enclosing procedure whose last result takes it,oreneeds two results,deferskips@(require_results)procedures,&and slicing a fixed array need an addressable value,returnneeds an enclosing procedure with one result of that type,slice.sortandslice.containsneed ordered and comparable elements, the string procedures skip distinct strings, and acontextlessprocedure gets no item that needscontext. Requires client snippet support. Defaults to true. -
enable_overload_resolution: Enable go-to-definition to resolve overloaded procedures from procedure groups based on call arguments. -
enable_references: Turns on finding references for a symbol. (Enabled by default) -
enable_document_highlights: Turns on highlighting of symbol references in file. (Enabled by default) -
enable_document_links: Follow links when opening documentation. This is usually done via<ctrl+click>and will open the documentation in a browser (or similar). (Enabled by default) -
enable_completions: Enables completion results. (Enabled by default) -
enable_completion_matching: Attempt to match types and pointers when passing arguments to procedures. (Enabled by default) -
enable_unused_imports_reporting: Turn on reporting of unused imported packages. (Enabled by default) An import named only in awhenbranch that the host does not build counts as used, so organize-imports on save keeps an import that another target needs, whileodin checkreports it on the host. -
enable_unused_imports_on_change: Report unused imported packages after each document change. This can slow editing in large files. (Disabled by default) -
enable_inlay_hints_params: Turn on inlay hints for (non-default) parameters. -
enable_inlay_hints_default_params: Turn on inlay hints for default parameters. -
enable_inlay_hints_implicit_return: Turn on inlay hints for implicit return values. -
enable_inlay_hints_variable_types: Turn on inlay hints for inferred variable types. Defaults to true. -
enable_inlay_hints_comp_lit_fields: Turn on inlay hints for struct field names in positional composite literals. Defaults to true. -
enable_inlay_hints_range_types: Turn on inlay hints for the types of range loop variables. Defaults to true. -
enable_inlay_hints_constant_values: Turn on inlay hints for the folded value of constant expressions. Defaults to false. -
enable_inlay_hints_optional_result: Adds inlay hints for unhandled optional result value. (#optional_ok and #optional_allocator_error) -
enable_semantic_tokens: Turns on syntax highlighting. -
enable_snippets: Turns on builtin snippets -
enable_procedure_snippet: Use snippets when completing procedures—adds parenthesis after the name. This requires client snippet support. (Enabled by default) -
enable_checker_only_saved: Turns on only calling the checker on the package being saved. (Enabled by default) -
enable_compiler_semantics: Enables compiler semantics for reporting type information. This is currently experimental and under active development. Needs anodinwith-export-semantics.-
enable_checker_on_change: Turns on calling the checker on the package being edited once typing pauses forchecker_on_change_delay, with the unsaved text of the open documents. Needs anodinwith-overlay. -
checker_on_change_delay: How long typing must pause, in milliseconds, beforeenable_checker_on_changecalls the checker. (Defaults to 400) -
enable_fade_untaken_when_branches: Fades the branches ofwhenstatements that the checker did not take. Needs anodinwith-export-semantics. (Enabled by default)
-
-
enable_checker_workspace_diagnostics: Turns on running all workspace diagnostics using odin check. This is currently experimental and may cause problems. A better option is using thechecker_pathfeature to explicity tellolsthe projects that it should check. (experimental). -
enable_auto_import: Automatically import packages that aren't in your import on completion. Completing aftermem.also lists the members of an unimportedcore:mem, and accepting one adds the import. -
enable_auto_import_skip_hidden_paths: Skip hidden directories when discovering packages for auto-import. (Enabled by default) -
enable_comp_lit_signature_help: Provide signature help for comp lits such as when instantiating structs. Will not display correctly on some editors such as vscode. Inside a comp literal passed to a call, the comp literal signature comes before the procedure signature. (Enabled by default in rols) -
enable_comp_lit_signature_help_use_docs: Put signature help for comp lits in the documentation. This will allow it to be rendered nicely using markdown in editors that render the label without colour on one line. -
enable_code_action_invert_if: Enables the code actions to invert if statements and to rewrite them as early returns. Defaults to true. -
enable_code_action_extract_variable: Enables the code action to extract an expression into a local variable. It also offers "Extract variable (replace all N)" when the expression occurs at least twice in the enclosing block with identical text and every occurrence reads the same value. With only a cursor, it offers one action for each enclosing expression. Defaults to true. -
enable_code_action_inline_variable: Enables the code action to inline a local variable into its uses, with the cursor on the declaration's name or on any use. With the cursor on one of several uses, a second action inlines only that use and keeps the declaration. A typed declaration keeps its type at each use:x: f32 = 1inlines asf32(1). Defaults to true. -
enable_code_action_extract_procedure: Enables the code action to extract selected statements into a new procedure. Defaults to true. -
enable_code_action_add_explicit_type: Enables the code action to add the inferred type to a:=declaration. Defaults to true. -
enable_code_action_ternary: Enables the code actions converting between an if/else and a ternary expression. Defaults to true. -
enable_code_action_unwrap: Enables the code actions to unwrap a bare block or an if body, to turnelse if c {…}intoelse {…}, and to remove a redundant else. Loops are never unwrapped, since that runs the body once. Defaults to true. -
enable_code_action_do_block: Enables the code actions converting a one-statement block to adobody and back. Defaults to true. -
enable_code_action_fill_struct: Enables the code action filling the missing fields of a struct literal with zero values. Defaults to true. -
enable_code_action_if_to_switch: Enables the code action converting an if/else-if chain of equality tests to a switch. Defaults to true. -
enable_code_action_result_handling: Enables the code actions addingor_return,or_else, anifon the ok/error result, or discarding the results of a call. Defaults to true. -
enable_code_action_generate_proc: Enables the code action generating a stub for a called procedure that does not exist. Defaults to true. -
enable_code_action_named_results: Enables the code action naming the results of a procedure. Defaults to true. -
enable_code_action_add_ok_result: Enables the code action adding aboolresult to a procedure, with, _added at each caller. It is not offered when the last result is already abool,b8,b16,b32orb64, or when the procedure has platform variants, asrenamefinds them. Defaults to true. -
enable_code_action_result_union: Enables the quick fix changing the last result type of a procedure to a union of the types itsreturnstatements andor_returncalls produce. With several results, it also names the unnamed ones, sinceor_returnneeds named results. Defaults to true. -
enable_code_action_defer_delete: Enables the code action adding adeferthat frees an allocation. Defaults to true. -
enable_code_action_extract_constant: Enables the code action extracting a constant expression into a file-scope constant. With only a cursor, it offers one action for each enclosing expression. Defaults to true. -
enable_code_action_inline_proc: Enables the code action inlining a procedure call. Defaults to true. -
enable_code_action_introduce_param: Enables the code action turning a constant expression into a parameter passed by every caller. With only a cursor, it offers one action for each enclosing expression. It is not offered when the procedure has platform variants. Defaults to true. -
enable_code_action_remove_param: Enables the code action removing an unused parameter from a procedure and its callers. A procedure with platform variants, asrenamefinds them, loses the parameter in every variant; the action is not offered when a variant cannot take the change (as forreorder-params) or reads that parameter. Defaults to true. -
enable_code_action_move_decl: Enables the code action moving a top-level declaration to another file of the package, or to a new file when the client can create files. Defaults to true. -
enable_code_action_generate_test: Enables the code action generating a@(test)stub for the procedure at the cursor in<file>_test.odinof the same package, created when the client can create files with the#+tag lines of the source file. Odin builds a_test.odinfile in every build, andcore:testingdoes not compile forjs,wasi,orcaandfreestanding, so a created file also gets one line per OS, such as#+build !js, for each of those that the source builds on. A source that builds only on those gets no stub, and neither does a file-private procedure, by@(private="file")or#+private file. The stub checks a result against its zero value, spelledpkg.T{}for a type of another package, with that import added to the test file. It is not offered when such an import would be shadowed byt,testingor a result name, or when the test file imports that package under another name or another package under that name. A result thattesting.expect_valuecannot compare, such as a struct holding a slice, is bound to_with a comment saying it is not checked. Defaults to true. -
enable_code_action_expand: Expand an array scalar,or_else,or_returnor a range loop back to the long form. Defaults to true. -
enable_code_action_checker_fix: Enables quick fixes forodin checkerrors: dropping an unused variable and removing a cast to the same type. Defaults to true. -
enable_code_action_comment: Enables the code actions adding a doc comment above the top-level declaration at the cursor, and converting the selected comments between//lines and a/* */block. Defaults to true. -
enable_code_action_literal: Enables the code actions on the literal at the cursor: converting a string to and from a raw string, converting an integer between hexadecimal, decimal and binary, and adding or removing digit separators. Defaults to true. -
enable_code_action_lift_using: Enables the code action lifting a selector path such asa.binto ausing a.bstatement before its first use in the block at the cursor, removing the path from every use in that block and its nested blocks. It adds#+feature using-stmtwhen the file lacks that tag. Defaults to true. -
enable_code_action_attr: Enables the code actions adding and removing@(require_results),@(private)and@(test)on the top-level declaration at the cursor, where the result compiles. Defaults to true. -
enable_code_action_add_allocator: Enables "Add allocator parameter" and "Add caller location" on the name of a top-level procedure. They addallocator := context.allocatororloc := #caller_location, passallocator = allocatororloc = locto each call in the body whose callee takes that parameter and gets none, such asmakeornew(andappendfor the location), and make each caller that has a parameter of that kind pass it. They refuse a contextless or foreign procedure, a variadic one, one that has the parameter or reads the name already, one with platform variants, one used other than as a callee, and one whose body has no call to pass it to. Defaults to true. -
enable_code_action_param_pointer: Enables "Pass by pointer" and "Pass by value" on a parameter of a top-level procedure. "Pass by pointer" turnsx: Tintox: ^T, readsx^in the body, orx.ffor a struct, and passes&arg, refusing an argument without an address. "Pass by value" does the reverse and refuses when the body writes through the pointer, compares it withnil, or stores or passes it on. Defaults to true. -
enable_code_action_param_object: Enables "Introduce parameter object" on a selection of two or more adjacent parameters of a top-level procedurefoo. It declaresFoo_Params :: struct {...}after the procedure, takesparams: Foo_Paramsin their place, readsparams.ain the body and passesFoo_Params{a = ..., b = ...}at each call. It refuses a default value,using, a parametric parameter, and a taken name. Defaults to true. -
enable_code_action_proc_group: Enables "Make group foo" and "Add to group foo" on the name of a top-level procedurefoo_a. "Make group foo" declaresfoo :: proc{foo_a, foo_b}over the procedures of the file named with the prefix before the last_, and refuses a taken name. "Add to group foo" adds the procedure to a groupfooof the package that lacks it, and refuses when a call of the group could pick the new member. Defaults to true. -
enable_code_action_extract_type: Enables "Extract type" on an inlinestruct,union,enum,bit_set, procedure type or long array type (one that nests another array or a map, or spans 16 characters) written as the type of a parameter, field or declaration. It declares a top-level type named after the field, such asOptsforopts, after the enclosing declaration, and writes its name in place. It refuses a type that names a poly parameter, a local or a local type, and an inline struct, union or enum spelled the same elsewhere in the workspace, since a named type would no longer match it. It also enables "Inline type alias" on the name of a top-levelX :: Y, which writesYat each use across the workspace and deletes the alias. It refusesdistinct, a struct, union or enum declaration, a parametric alias, an alias that another package reaches unlessYis a plain name, and an exported alias whose name appears in a file the workspace filter leaves out. Defaults to true. -
enable_code_action_reorder_fields: Enables "Reorder fields to reduce padding (A to B bytes)" on the name of a top-level struct. It sorts the fields by descending alignment, keeping the order of fields with the same alignment and the comments of each field, and is offered only when the struct shrinks on a 64-bit target. It refuses#packed,#raw_union,#alignand the field alignment tags, a parametric struct,using,#subtype, a_field, a field whose size it does not compute, and a struct that a positional literal, atransmuteor a foreign block of the workspace uses. A binary layout read through a memory cast, such as a pointer cast of bytes from a file, is outside what the search can see, so check such code before applying it. Defaults to true. -
enable_code_action_proc_tags: Enables the code actions on the name of a top-level procedure with a body that add or remove#force_inline,#force_no_inlineand"contextless". "Add #force_inline" refuses a procedure that calls itself. "Add "contextless"" requires a body that never namescontextand calls only type conversions, builtins such aslen, and procedures whose calling convention passes no context, and every use of the procedure must be a call. "Remove "contextless"" refuses when a call lies in a contextless procedure or the procedure is used other than as a callee. Both refuse an@(export)or@(link_name)procedure and one with platform variants. Defaults to true. -
enable_code_action_swap_param: Enables the code actions moving the parameter at the cursor one place left or right in a top-level procedure, updating its platform variants and every call. Defaults to true. -
enable_code_action_init_move: Enables the code actions moving a declaration into the init of theif,switchorforthat follows it, and moving an init out above its statement. Defaults to true. -
enable_code_action_split_decl: Enables the code actions splitting a local declaration into a declaration and an assignment, joining them back, and splitting a multi-name declaration into one declaration per name. Defaults to true. -
enable_code_action_const_var: Enables the code actions converting a localx := vtox :: vand back, where every use keeps its meaning. Defaults to true. -
enable_code_action_range_loop: Enables the code actions on the header of a range loop: adding an index, iterating by reference or by value, toggling#reverse, and converting betweena..<10anda..=9. Defaults to true. -
enable_code_action_surround: Enables the code actions surrounding the statement at the cursor, or the statements a selection touches, with a block,if true,for true,when true,deferor#no_bounds_check. Defaults to true. -
enable_code_action_expand_using: Enables the code actions removing ausing. On ausingstatement, "Expand using" writes the path before each name the statement promotes in the rest of its block and deletes the statement, so it is the inverse of "Lift using". It leaves a#+feature using-stmttag in place. On ausingstruct field, "Convert using to #subtype" keeps the implicit conversion to the embedded type and drops the promotion, and applies only when a search of the workspace finds no use of a member through the promotion.core:reflectand what reads it, such ascore:encoding/json, stop treating that field asusing. Defaults to true. -
enable_code_action_named_form: Enables the code actions converting a struct literal betweenFoo{1, 2}andFoo{x = 1, y = 2}, and a call betweenf(1, 2)andf(a = 1, b = 2). A call with named arguments no longer qualifies for "Move parameter", "Remove parameter", "Introduce parameter" andols query reorder-params, which refuse a call site that names its arguments. Defaults to true. -
enable_code_action_type_switch: Enables the code actions on type assertions and type switches. "Convert to type switch" turnsif v, ok := u.(T); ok {...}and itselse ifchain over one subject intoswitch v in u, with theelseascase:. "Convert to if chain" turns a type switch of at most eight cases back. "Add #partial" and "Remove #partial" change the switch, and removal needs a case for every variant. "Add default case" addscase:. Defaults to true. -
enable_code_action_cast: Enables the code actions on casts. "Convert to T(x)" and "Convert to cast(T)x" switch between the two forms, with parentheses around a type such as^Tor[]u8. "Convert to auto_cast" and its reverse apply where the place of the expression expectsT. "Convert to transmute" and its reverse apply only between pointer types, where both keep the value. Defaults to true. -
enable_code_action_bit_set: Enables the code actions converting.A in flagstoflags & {.A} != {}and.A not_in flagstoflags & {.A} == {}, and back, for one member and aflagsthat resolves to abit_set. Defaults to true. -
enable_code_action_evaluate: Enables the "Evaluate constant" code action, which replaces an expression of integer literals and+ - * / % << >> & |with its value. It refuses a float, a name, a zero divisor and a value outsidei64. Defaults to true. -
enable_code_action_create_member: Enables "Create field foo" onx.foowhenxis a struct of the workspace, also in another file, with the type from an assignment, an operand or the parameter that receives it, and "Create enum member Foo" on.Foowhen the expected enum is in the workspace. They refuse an unknown type, a parametric struct and a member that would leave a positional literal, a switch without#partialor an enumerated array literal incomplete. Defaults to true. -
enable_code_action_create_decl: Enables "Create local variable x", "Create global variable x" and "Create constant x" on an unresolved name whose use gives a type, and "Create struct Foo" on an unresolvedFoo{a = 1}, where an untyped integer givesint.x = vbecomesx := vfor the local form, and the constant form takesx = 1to file scope. They refuse when no use gives a type, and "Create struct" refuses a positional literal. Defaults to true. -
enable_code_action_generate_lifetime: Enables "Generate destroy_foo" and "Generate init_foo" on the name of a top-level structFoothat is not parametric or a#raw_union.destroy_foo :: proc(foo: ^Foo)callsdeleteon each[dynamic]and map field and names the slice, string and pointer fields in a comment, since they can be borrowed. It refuses a struct with none of these fields.init_foo :: proc(foo: ^Foo, allocator := context.allocator)callsmakefor each[dynamic]and map field, and refuses a struct with neither. Both refuse a name the package already declares. Defaults to true. -
enable_code_action_generate_enum: Enables "Generate bit_set" and "Generate name table" on the name of a top-level enum whose member values are constants. "Generate bit_set" declaresFlags :: bit_set[Flag]for an enumFlag, elseEnum_Set :: b 10BC8 it_set[Enum], and refuses a negative value or a value over 127. "Generate name table" declaresENUM_NAMES := [Enum]string {...}with one entry per value,#sparsewhen the values have gaps. Both refuse a name the package already declares. Defaults to true. -
enable_code_action_qualify: Enables the code actions converting between.AandEnum.A, and adding or dropping the type of a composite literal, where a declared type, an assignment, a return, a parameter, a field or an element supplies the type. A comparison and acasealso supply the type of an enum member. Defaults to true. -
enable_code_action_loop_label: Enables the code action adding a label to the loop at the cursor, so nestedbreakandcontinuecan target it. Defaults to true. -
enable_code_action_merge_cases: Enables the code actions to merge a switch case with the next one when their bodies match, and to split a multi-value case into one case per value. Defaults to true. -
enable_code_action_split_merge_if: Enables the code actions to split an if on&&, to merge nested ifs, and to split an if at the||under the cursor with a copy of the body in each branch, as an else-if chain or as separate ifs. Separate ifs run the body twice when both conditions hold. Defaults to true. -
enable_code_action_rewrite_expression: Enables the code actions to flip a comparison, apply De Morgan's law and convert between compound and plain assignment. Defaults to true. -
enable_organize_imports_on_save: Removes unused imports and adds missing ones on save throughworkspace/applyEdit. A new import goes among the kept imports of its collection when the file keeps one. Otherwise it goes after the first import, or at the top of the import block when that import is removed. Defaults to true. -
struct_fields_underscore_visibility: Controls visibility of struct fields starting with_:""(default): no hiding, all fields are visible"file": hide fields when accessed from outside the declaring file"package": hide fields when accessed from outside the declaring package
-
enable_parser_errors: Enable real-time diagnostics fromcore:odin/parser. (Enabled by default) -
enable_diagnostics: Enable real-time diagnostics from the lsp. (Enabled by default) -
odin_command: Specify the location to your Odin executable, rather than relying on the environment path. -
odin_root_override: Allows you to specify a customODIN_ROOTthatolswill use to look forodincore libraries when implementing custom runtimes. -
checker_args: Pass custom arguments toodin check, split like a shell does for the simple cases: whitespace separates arguments, a double or single quote at the start of an argument or right after=or:groups the text up to its closing quote. Quotes around text with whitespace are removed (-collection:x="/my path"), while quotes around text without whitespace stay as written (-define:NAME="text"reaches odin with its quotes, as before). Any other quote, such as the apostrophe in-define:MSG=it's, and every backslash is an ordinary character, so a string without such a group splits as before. Tabs and line breaks separate arguments too. A backslash is an ordinary character, so a Windows path such asC:\libs\xkeeps it. An unterminated quote keeps the rest of the text in its argument. Odin rejects a repeated flag, so a flag here replaces the same flag that rols adds itself:-no-entry-point,-json-errors, a-vet-*flag that itsenable_checker_vet_*key turns on, and a-collection:NAME=or-define:NAME=of the same NAME.-custom-attributeand-sanitizemay repeat in Odin, so they are never dropped. -
enable_checker_vet_shadowing: Pass-vet-shadowingtoodin checkand report shadowed declarations as warnings. Defaults to true. -
enable_checker_vet_unused_variables: Pass-vet-unused-variablestoodin check. Report variables that are declared but never used, as warnings. Odin rejects a variable without this flag when it is the only statement of anif,elseorforbody, for exampleif c { x := 1 }; that one stays an error. Defaults to true. -
enable_checker_vet_cast: Pass-vet-casttoodin check. Report casts and transmutes to a type the value already has. Defaults to true. -
enable_checker_vet_style: Pass-vet-styletoodin check. Report style violations, such as a missing trailing comma before a closing brace on its own line. Defaults to true. Odin reports such a violation as a Syntax Error that stops checking the package, and so do-vet-semicolonand-strict-style. Odin reports a-vet-tabsfinding on its own as well. When a check with any of these flags reports a Syntax Error or a-vet-tabsfinding, rols runs the package a second time without those flags. The errors of the first run that the second run does not report show as warnings, and the rest of the diagnostics come from the second run, so a type error shows next to a missing trailing comma. The second run happens only after such an error, and not when a file that a Syntax Error names fails rols' own parser too, since the second run would stop at that syntax error as well. It doubles the time limit of the whole check from 20 to 40 seconds, shared by all second runs. Theols querycommands with--applycheck without these flags, but a style flag inchecker_argsstays and can start the second run. -
enable_checker_vet_semicolon: Pass-vet-semicolontoodin check. Report unneeded semicolons. Defaults to true. -
enable_checker_vet_tabs: Pass-vet-tabstoodin check. Report source lines that are not indented with tabs. Defaults to true. -
enable_checker_strict_style: Pass-strict-styletoodin check. Report style violations as hard errors; subsumes-vet-styleand-vet-semicolon. Defaults to false. -
enable_workspace_gitignore: Skip paths that git reports as ignored when walking the workspace. Does nothing outside a git repository or whengitis not on PATH. Defaults to true. Workspace walks feed workspace symbols; references, rename, change signature, incoming calls and code lens; the CLIfind,refs,renameandcallersqueries; and the package list for workspace diagnostics fromodin check. Workspace symbols filter directories only and index whole packages, so a file glob such as*_gen.odinhas no effect there. Imported packages and collections are never filtered. Rename and change signature do not edit git-ignored files either, so list ignored code that still compiles inworkspace_include. -
enable_excluded_file_targets: In a file that the host does not build, such assocket_linux.odinon macOS, resolve names against the files of a target that builds it, so hover, go to definition and completion reacherrors_linux.odinand not the host'serrors_posix.odin. The server keeps one extra symbol index per such target and fills each package of it on the first lookup from such a file. Turn it off to save that memory and the time of that first lookup; names in those files then resolve through the host index, as in upstream OLS, and can point at the host's declaration or at nothing. Defaults to true. -
workspace_exclude: Globs relative to each workspace root. Workspace walks skip matching files and directories, and everything below a matching directory.*,?and[...]match within one path segment,**spans any number of segments, a glob without/matches a name at any depth, and a leading/anchors a glob to the root. Defaults to empty. -
workspace_include: Globs relative to each workspace root, with the same syntax. Workspace walks keep matching paths even when git ignores them.workspace_excludewins overworkspace_include. Defaults to empty. -
modernize_recipes: Your own rewrite rules forols query modernize. Each recipe becomes the rulerecipe/<name>of familyrecipe, which is in the default set. Editors never show them. Defaults to empty. Example:"modernize_recipes": [ {"name": "sort-slice", "match": "sort.quick_sort($s)", "replace": "slice.sort($s)", "imports": ["core:slice"], "where": [{"var": "s", "kind": "slice"}]} ]
name: letters, digits,-,_and.; unique.match: Odin code.$nameis a metavariable that matches any expression; a second$namematches only the same text, spaces ignored. One expression matches any expression in the code. Anything else, such as several statements, matches that many consecutive statements of a block. Parentheses never matter. Other names must be the same in the code. A plainpkg.namemeans a package: it matches only code whosepkgpart names an import, under any alias, with an import path that ends inpkg, and only where no local declaration shadows that import. Use$x.namefor a field of any value. A metavariable cannot stand for a field name, as in$x.$for.$f, and a lone name or metavariable is not a validmatch. Amatchthat uses a construct the matcher does not handle, such as a procedure literal, aswitchor a typed declaration, is reported and skipped.replace: Odin code with the$namemetavariables ofmatch. Each one becomes the code it matched, in parentheses when it is a compound expression used as an operand. Whenmatchis one expression,replacemust be one expression too. Lines after the first take the indentation of the matched code, so a string literal inreplacemust not span lines.$in strings, runes and comments stays as is.imports: import paths the replacement needs. A missing one is added. When the file imports the path under an alias, apkg.qualifier ofreplaceis written with the alias, and a qualifier ofmatchkeeps the name the code used. A fix whose package name means something else in the file is skipped.where:{"var": "s", "kind": "slice"}entries.kindisslice,dynamic_array,fixed_array,map,stringorpointer. Only a metavariable that matched a name or a selector such asa.bhas a resolved type; any other match, such asxs[:]or a call, fails the constraint.
A metavariable that matched an expression with a call,
or_return,or_breakoror_continueis rewritten only whenmatchandreplaceeach use it once, and only one metavariable of a match may contain one. Any other case could change how often or in which order the calls run or the control flow happens. A match is also skipped when a comment inside the matched code lies outside every metavariable thatreplacewrites, because the rewrite would delete it. A recipe with a parse error, an unknownwherekind, a$nameinreplaceorwherethatmatchdoes not bind, or a repeated name is printed on stderr asrecipe <name>: <problem>; skipped. The other rules still run. The match is syntactic apart fromwhere, so check the result withodin check, which--applydoes. -
enable_lint_self_assignment: Warn when a variable is assigned to itself. Defaults to true. -
enable_lint_identical_branches: Warn when the if and else branches, or both ternary branches, are identical. Defaults to true. -
enable_lint_unreachable_code: Mark statements afterreturn,break,continue,fallthrough,panicorunreachableas unnecessary. Defaults to true. -
enable_lint_simplify: Mark code that has a shorter equivalent (array literal with identical elements,x == true,if c { return true } else { return false }, redundant parentheses,s[0:len(s)], C-style counting loops, nested ifs, manualor_else/or_return/or_break/or_continuepatterns) as unnecessary and offer the rewrite as a quick fix. Defaults to true. -
enable_lint_float_equality: Report==and!=comparisons on floats. A comparison with the literal0,0.0,1or1.0is not reported. Defaults to true. -
enable_lint_printf: Checkfmtandlogformat strings: unknown verbs, argument count, argument type, and format directives passed to the non-formattingprintprocedures. Defaults to true. -
enable_lint_ignored_result: Warn when a call statement discards the result of a procedure marked@(require_results), the calls the compiler rejects. Defaults to true. -
enable_lint_unused_parameter: Mark procedure parameters that are never used in the body as unnecessary. A procedure that its package uses as a value (an argument, an assignment, a composite literal element or a parameter default) is skipped, and so is a procedure literal passed to a call, stored in a composite literal, assigned, or declared with an explicit type. Other files of the package are matched by name, and a workspace package that imports the package counts a value use through its import alias (register(a.handler)). A package outside the workspace is not read. Defaults to true. -
enable_lint_unused_variable: Mark local variables and constants that are declared but never used as unnecessary. Defaults to true. -
enable_lint_naming: Report names that do not follow Odin conventions: snake_case procedures and variables, Ada_Case types and enum members, SCREAMING_SNAKE_CASE constants. Atrueorfalseconstant may be snake_case or SCREAMING_SNAKE_CASE. Constants inside a procedure, declarations inforeignblocks and with@(link_name)or@(export), struct fields with a tag string, and parameters of a procedure type with a calling convention other than"odin"or"contextless"are not checked. In a package with aforeign importor an import ofcore:dynlib, type, field, enum member and constant names are not checked either, because they may mirror C names. Defaults to true. -
enable_lint_bool_logic: Report boolean and comparison mistakes: identical operands, conditions that are always true or false, andiforswitchbranches that repeat an earlier one. Defaults to true. -
enable_lint_no_op: Report code that does nothing: arithmetic with an identity operand (x + 0,x * 1), integer division of literals that is always 0, comparing an address tonil, emptyifor loop bodies, andappendwith no values. Defaults to true. -
enable_lint_loops: Report loop mistakes: a body that always exits on the first iteration, a condition nothing in the body changes, an empty infinite loop (for {}), a range that runs one past the end (0 ..= len(x)), and a range over a map lookup whose value is a dynamic array, map or fixed array (for x in m[k]), which reads through a nil slot for a missing key. Defaults to true. -
enable_lint_dead_store: Report a value stored in a variable that is overwritten before anything reads it, and writes to fields of a struct copy taken from an index, selector or range value. Defaults to true. -
enable_lint_allocator: Report a value allocated with an explicit allocator and then freed with the context allocator, andmake([dynamic]T, n), ormake(Array, n)for a named dynamic array type, whose elementsappendadds after. Defaults to true. -
enable_lint_sync: Report synchronisation mistakes: a lock released on the next line, a deferred lock, an atomic result assigned back to its own target, a lock struct passed or copied by value, and cleanup deferred before the error is checked. Defaults to true. -
enable_lint_deprecated: Report uses of a declaration marked with the@(deprecated)attribute. Defaults to true. -
enable_lint_core_misuse: Report misuses of core procedures:time.sleepwith a bare integer,strings.replacewithn = 0orn = -1, amathrounding procedure on a converted integer, and an invalidregexpattern literal. Defaults to true. -
enable_lint_integer_range: Report integer range mistakes: a shift by at least the operand's bit width, an unsigned value compared against a negative literal or zero, and an integer division converted to a float afterwards. Defaults to true. -
enable_lint_recursion: Report a procedure whose body calls itself before any branch, loop or early return. Defaults to true. -
enable_lint_test_attribute: Report a procedure taking^testing.Twithout an@(test)attribute, and an@(test)procedure whose signature is notproc(t: ^testing.T). The signature is checked only in a file that importscore:testing, under any alias, because another test runner may define its ownT. Defaults to true. -
enable_lint_unused_declaration: On save, mark private declarations that nothing in their package references as unnecessary. Defaults to true. -
enable_lint_imports: Report an import repeated in the same file, and an import whose package directory does not exist. Defaults to true. -
enable_lint_invisible_characters: Report a string literal containing a literal zero-width, bidirectional or control character. Defaults to true. -
enable_lint_triple_quote: Report a multiline raw string (`…`with a newline) that can use triple quotes (```…```), with a quick fix that keeps its value. Defaults to true. -
enable_lint_result_order: Report a procedure whose error-like result is followed by another result, soor_returncannot be used. Aboolcounts as an error result only when unnamed or namedok. An enum with aNonemember counts as an error only when its name containsError another member name containserr,fail,invalidorbad. Defaults to true. -
enable_lint_switch: Report a#partialswitch that already lists every case, and abreakat the end of a case. Defaults to true. -
enable_lint_redundant_type_assertion: Reports.(T)insidecase T:ofswitch _ in s, wheresis a name or a chain of.selectors such asx.shape, which repeats the assertion the switch already made. The quick fix "Bind the switch variant" binds the variant in the switch (switch &v in s), replaces each assertion with the binding and removes local aliases such asc := &s.(T). Defaults to true. -
enable_lint_call_arity: Report a call that passes too few or too many arguments to a resolved procedure. Defaults to true. -
enable_lint_struct_literal: Report a struct literal that sets the same field twice or names a field the struct does not have. Defaults to true. -
enable_lint_pure_call: Report a call to a core package procedure, such asstrings.to_upper, whose result is discarded. A procedure with a pointer parameter is skipped, because it may write its output through it, except known accessors such asbytes.buffer_to_string. Defaults to true. -
enable_lint_use_stdlib: Mark hand-written loops and comparisons that a core library procedure or builtin already does (slice.contains,slice.linear_search,strings.contains,strings.has_prefix/has_suffix,min/max/abs/clamp,copy,slice.fill,math.sum) as unnecessary and offer the rewrite as a quick fix. A fill of a fixed array becomes an array assignment (arr = v) where Odin broadcasts the value, and an untyped{…}or.Namevalue is written with its element type. Defaults to true. -
enable_code_lens_references: Show a reference count above every top-level declaration. Defaults to true. -
enable_selection_range: Expand the selection outwards through the syntax tree. Defaults to true. -
checker_targets: Odin targets that the compile gate ofols query … --applyalways checks besides the current one, such as["windows_amd64", "js_wasm32"], or a bare OS name such as"windows"for its default architecture. A name that is not one of the gate's known targets is skipped with awarning:. The gate also adds the targets that the touched files need. See "Command line queries". -
checker_variants: Extraodin checkarguments for the compile gate ofols query … --apply, one string per extra check on the current target, such as["-define:SIM=true"]for code that only builds with that define. Each string is split likechecker_argsand added after it. A string with a-target:value, such as"-define:SIM=true -target:linux_amd64", checks on that target instead and is named as written. Defaults to empty. See "Command line queries". -
checker_skip_packages: Paths to packages that should not be checked byodin checkwhen usingenable_checker_workspace_diagnostics. -
completion_exclude_attributes: Filter procedures that include the provided attributes from completions. For example@(test). -
verbose: Logs warnings instead of just errors. -
profile: What profile to currently use. -
profiles: List of different profiles that describe the environment ols is running under. This allows you to define different operating systems, architectures and defines forolsto use during development, easily switching between them using theprofileconfiguration.
Odinfmt reads configuration through odinfmt.json.
Example:
{
"$schema": "https://raw.githubusercontent.com/DanielGavin/ols/master/misc/odinfmt.schema.json",
"character_width": 80,
"tabs": true,
"tabs_width": 4
}Options:
-
character_width: How many characters it takes before it line breaks it. -
spaces: How many spaces is in one indentation. -
newline_limit: The limit of newlines between statements and declarations. -
tabs: Tabs or spaces. -
tabs_width: How many characters one tab represents. -
convert_do: Convert all do statements to brace blocks. -
brace_style: Style of braces. One of_1TBS,Allman,Stroustrup,K_And_R. -
indent_cases: Indent case statements within a switch. -
newline_style: Line endings to use. One ofCRLF,LF. -
sort_imports: A boolean that defaults to true, which can be set to false to disable sorting imports. -
inline_single_stmt_case: When statement in the clause contains one simple statement, it will inline the case and statement in one line. -
spaces_around_colons: Put a space on both sides of a single colon during variable/field declaration, such asfoo : bar -
space_single_line_blocks: Put spaces around braces of single-line blocks:{return 0}=>{ return 0 } -
align_struct_fields: Align the types of struct fields so they all start at the same column. -
align_struct_values: Align the values of struct fields when assigning a struct value to a variable so they all start at the same column. -
align_comments: Align trailing line comments on consecutive lines so they all start at the same column. The alignment resets on a blank line, a line without a trailing comment, or a change in indentation. Standalone comment lines and/* */block comments are not aligned. -
multiline_composite_literals: When enabled, composite literals that were written across multiple lines are kept multiline. -
preserve_struct_blank_lines: Preserve blank lines between struct fields, up tonewline_limit.
Support Language server features:
- Completion
- Go to definition
- Semantic tokens
- Document symbols
- Rename. On an import alias, or on the
xof a qualifierx.yoralias :: xthat resolves to an import, rename renames that import in the current file only: the alias, or a new alias before the path of an import without one, and every qualifier of the file that resolves to it. It is refused when the new name is not a valid identifier, is a keyword or a builtin name, names another import of the file, is declared at file scope or elsewhere in the package, or is a local visible at a qualifier, which would capture it. On the name of apackageclause, rename renames the package asols query rename-packagedoes: everypackageclause of the directory, the import paths and unaliased qualifiers of its importers, and the directory itself, since Odin names an unaliased import after its directory. It needs a client that can rename files (resourceOperationswithrename) and sendsworkspaceFolders, since the search for importers walks those folders. Without either, and for each cause thatrename-packagelists below, the rename is refused. The editor rename does not show the warnings thatrename-packageprints, such as a qualifier it could not resolve, so run the command line to see them. - References
- Signature help
- Hover
ols query <command> prints one line per result as file:line:col: text; --json prints the LSP objects instead. Positions are file:line:col, 1-based, columns in bytes, in both input and output. --root DIR sets the workspace, default: the nearest directory with an ols.json above the file, else the cwd. Every path argument, --root and move --to included, is relative to the cwd; the symlinks of the existing part of a path are resolved. --help or -h, alone or with any command, prints the usage text on stdout and exits 0.
def,refs,hover,implFILE:LINE:COLcallers,calleesFILE:LINE:COL: the call hierarchy of the procedure at the position, as[{name, uri, range, fromRanges}]symbols FILE: the outline of the file, onefile:line:col: Kind nameline per symbol, by position, with the members of a struct, enum or bit_field indented by two spaces below it. The order is the same on every run, and--jsonlists the same order. A file without declarations prints nothing ([]with--json) and exits0actions FILE:LINE:COL[-LINE:COL] [--apply TITLE [--no-check]]: a range of one character on one line counts as a cursor, and a cursor in a line's indentation counts as a cursor on its first token. An inexact selection means the smallest expression around it, or for Extract procedure the whole statements it touches.--applypicks one action by its exact title; a file that cannot be read is a refusal like forrename, with theactions: refused, nothing writtensummary. Two actions at one position that share a title get the first line of the code they change in parentheses, such asMerge nested if (if a {), and a numeric suffix like#2when that does not tell them apart. Titles that occur once stay unchanged.rename TARGET NEW [--apply [--no-check]]: refused, before any edit is computed, whenNEWis not a valid identifier, is a keyword, or a builtin name such aslenorint(fields and enum members may use builtin names, which Odin allows); whenNEWis already declared in the declaring scope (the package, the type, or the local scope; a package declaration in awhenbranch counts, and its cause says so); when a reference would resolve to another declaration namedNEW, or a use ofNEWwould resolve to the renamed local, each with itsfile:line:col; when the declaration is incore:,vendor:,base:or outside the workspace folders; and on an import path or the name of apackageclause, whichrename-packagerenames. On an import alias or a package qualifier that resolves to an import,renamerenames that import in the target's file only, with the refusals that the Rename entry under Features lists.NEWequal to the old name exits3. Awarning:line names up to 10 workspace files, then a count, that the gitignore,workspace_excludeorworkspace_includefilter skipped but that contain the old name as a whole word, since the rename does not change them. A package-level declaration is renamed together with its platform variants, and so are their references, in the files that the current target does not build too. A variant is another declaration of the same name at file scope (underwhenand in foreign blocks included) in a file of the same directory with the samepackageclause, except a#+build ignorefile. Two declarations that every build includes together are duplicates, not variants: both outside anywhenin files that the current target builds, or both in the samewhenbranch of one file.whenconditions are not evaluated, so two declarations in differentwhenstatements count as variants.NEWdeclared in the file of the declaration, in the file of a variant, or in another file of the package is refused only when some OS, architecture and#+build-project-nameproject builds it and takes itswhenbranch together with the renamed declaration or a variant.NEWin another file is also not refused when it is private to that file. Two arms of onewhenstatement never build together, whatever their condition. Otherwise only comparisons ofODIN_OSorODIN_ARCHwith a value such as.Linux,true,false,!,&&,||and parentheses are evaluated there; any other condition can go either way.refson such a declaration lists the references of its variants too. A field or member of a struct, enum or bit_field type with platform variants is renamed in each variant that has a member of that name, andNEWalready a member of any of them is refused. The field rename is also refused when a variant of the type is an alias or another type that is no struct, enum or bit_field, or lacks the member but has ausingfield.reorder-params TARGET --order 2,0,1 [--apply [--no-check]]: position on a procedure name;--orderlists the new parameter order by old index. Callers are updated. Refused with the one cause that applies: the position is not on the name of a top-level procedure; the procedure has no body, is polymorphic or has awhereclause, has an attribute that fixes its signature (export,link_name,deferred_*), has a parameter without a name, with flags such as#any_intorusing, with a default value, or is variadic;--orderdoes not list each parameter index once; the procedure is used as a value; or a caller names, spreads or omits arguments. The platform variants of the procedure, asrenamefinds them, are reordered too, with the calls in the files of other targets. The reorder is refused when a variant is not a single procedure declaration, cannot change for one of the causes above, or has other parameter names or types, with the error "the variant offat FILE:LINE:COL has different parameters"move TARGET --to FILE.odin [--apply [--no-check]]: position on a top-level declaration name;--tonames a file of the same directory, created when missing. A relative--tois relative to the cwd, like every other path (before, it was relative to the directory of the declaration, so--to b.odinfrom another directory now names./b.odinand is refused unless the cwd is the declaration's directory). The directories compare with symlinks resolved, so an absolute path through a symlink such as macOS/tmpworks. The target gains the imports the declaration needs, each sorted among the target's imports of the same collection, or in a new group after the last import when the target has none of that collection; the source loses each import that only the declaration used; an import that was already unused stays. Refused when the target imports one of those packages under another name, or another package under the same name. A created target starts with the#+tag lines of the source file, such as#+buildand#+private. Refused for a created target whose name lacks the OS and architecture suffix of the source file's name, or adds one, as in--to helper.odinfrommain_windows.odin. Also refused for file-private declarations and those using file-private symbols, and for an existing target whose#+privatetag differs from the source file's, such as a public target for a declaration in a#+privatefile, with the error "b.odin is public but the file of the declaration is #+private"rename-package DIR NEW [--apply [--no-check]]: renames the package inDIR, a directory or a collection path likeshared:util, toNEW. It rewrites thepackageclause of every.odinfile inDIR, for every platform, withpackage old_testbecomingpackage NEW_test; every import path in the workspace that steps intoDIRor a package below it, keeping its collection prefix or relative form and each/or\separator (a relative path insideDIRthat leaves it with..stays as it is); theold.xqualifiers,alias :: oldvalues and#defined(old)arguments that resolve to the package in each importer that imports it without an alias (an aliased import,import old "…"included, only changes its path); and finally renamesDIRto the sibling directoryNEW. Odin names an unaliased import after its directory, not itspackageclause. Refused, with oneerror:line per cause, whenDIRis not a directory of.odinfiles, is the workspace root, lies outside the workspace folders or incore:,vendor:orbase:, or holds the root of a collection; when a file'spackageclause, ignoring_test, differs from the directory name; whenNEWis not a valid identifier, is a keyword or a builtin name; when the siblingNEWexists; when an importer already bindsNEW, through another import, a declaration in its package, or a local visible at a rewritten qualifier, each asfile:line:col; and when an import resolves intoDIR, symlinks resolved, but no segment of its path namesDIR, such as a path through a symlink, which it cannot rewrite; a relative path from a file inDIRis exempt only when its segments, followed without resolving symlinks, stay inDIR.NEWequal to the current name exits3.warning:lines name the files the workspace filter skipped that mention the old import path or qualifier, up to 10 comments, foreign import paths (inwhenblocks too) and#load,#load_hash,#load_directoryor#configstrings that mention the old name, then a count, and eachold.xin an unaliased importer that does not resolve, since the rename does not change them. The dry-run diff ofrename-packageis a git-style preview for reading: it is not guaranteed to work withgit apply. The check after the write matches an existing error whose message names the old package against the same message with the new name, so such an error does not roll the rename backattr add TARGET KEY[=VALUE],attr remove TARGET KEY,attr remove --all KEY [DIR]andattr rename OLD NEW [DIR], each with[--apply [--no-check]]: edit@(…)attributes where the source writes them. A declaration is a value declaration, a foreign block, a foreign import or an import, at any depth: inwhenblocks, foreign blocks and procedure bodies too.TARGETnames the declaration by a position in its attributes, names or type, or by a symbol path; a struct field, enum member or bit_field field is refused, since attributes go on declarations.addappendsKEY[=VALUE]to the last group (@(a)becomes@(a, KEY), and@abecomes@(a, KEY)), or inserts@(KEY)on its own line above a declaration without attributes, at its indentation. It is refused whenKEYis not an identifier, when the declaration already hasKEYin any group, and whenVALUEdoes not parse as one Odin expression.removedrops eachKEYelement with its comma, keeping the comments of the elements that stay; an emptied group goes, with its line when the line holds nothing else; a missingKEYexits3.remove --allremovesKEYfrom every declaration inDIR, a directory or a collection path, or in the workspace, which is walked with the workspace filter;renamerenames the key and keeps its value across the same scope, and is refused at each declaration that already hasNEW, asfile:line:col.DIRincore:,vendor:orbase:, or outside the workspace folders, is refused, and so is aTARGETthere. A file that mentionsKEYbut does not parse is skipped with awarning:, as are the files belowDIR, or in the workspace, that the workspace filter skipped and that mention it.--allon any other command is a usage error. The compile gate of--applyrolls back an attribute thatodin checkrejects, such as an unknown keyapi PKG [NAME]: the exported symbols of a package, one per line with the first line of the doc comment, sorted by name.PKGis a directory or a collection path likecore:strings. WithNAME, the full signature and doc comment of one symbolfind QUERY: fuzzy symbol search over the workspace, asfile:line:col: Kind name. It reads every.odinfile that the workspace filter keeps, outside hidden directories, so it also finds private declarations (@(private),#+private), marked(private), and the declarations of files that another target builds, marked(other platform). A file that no target builds (#+build ignore) or that does not parse is left out. With--jsoneach match is the LSPWorkspaceSymbolplus the booleansprivateandotherPlatformcheck [DIR…]:odin checkerrors and the lints below, without building or running, of eachDIRtogether. WithoutDIRit checks the package in the cwd when the cwd holds.odinfiles, else every package below the workspace root (the directories with.odinfiles that the workspace filter keeps, hidden directories such as.snapshotsleft out), but only when anols.jsonor--rootdefines that root. ADIR, cwd or root without a package is anerror: no package in DIRand exits1. It exits1when any reported diagnostic has the error severity,0otherwise, warnings included. Whenodindoes not start, times out, exits with an error and no output, or prints something other than its JSON error list, it printserror: …on stderr and exits1, so a check that did not run is not a clean check. When there is no package to check (the directory is inchecker_skip_packages, which also matches the path with symlinks resolved, such as/private/var/…for/var/…on macOS), odin does not start, andcheckprints the lints and exits0lint FILE|DIR… [--fail-on CODE,…]: per-file lints, unused imports and unused private declarations, without running the compiler. ADIRcovers itself and every package directory below it thatcheckwould walk: the workspace filter,.gitignoreincluded, and theexclude_pathprofile select the directories, hidden directories such as.gitor.claudeare skipped, and within a kept directory the same filter selects the files, so a gitignored file is not linted. ADIRorFILEnamed on the command line is never filtered itself, and aDIRthat the filter skips, such as a gitignoredbuild/, covers every package directory below it, hidden ones andexclude_pathaside;checkfilters the files it lints the same way; aDIRwithout a package below it is anerror: no package in DIRand exits1, as forcheck. Several paths print their results in the order given, and a file that two paths share is reported once.--fail-onexits 1 when any listed code is reported for any path, for CI gates. A file that does not parse is still linted on what the parser recovered, as the editor does:FILE: the file does not parse, its lints may be incompletegoes to stderr, its lints are reported and count for--fail-on, and the parse error itself does not change the exit codetests [DIR|FILE…]: the@(test)procedures, asfile:line:col: name, thatodin testwould run on this target: a file with#+build ignore, or one that its name or#+buildtags exclude from the target (the host, or the-target:ofchecker_args), is left out. AFILEnamed on the command line is read asodin test FILE -filebuilds it: its name does not exclude it, only its#+buildtags. Without an argument it covers the same packages ascheck.--jsonlistsname,file,line,coland the package namepkgtest DIR [NAME,…]: runsodin test DIRwith the collections, defines andchecker_argsofols.jsonand plain output; names select tests as-define:ODIN_TEST_NAMESdoes,pkg.nameorname; a name that no test ofDIRhas is anerror: no test NAME in DIRand exits1, sinceodin testitself exits0after "No tests to run"modernize [PATH…] [--rule ID,…] [--list] [--diff] [--apply [--no-check]]: rewrites each file with the quick fixes of the simplify, use_stdlib and lint rules, pass after pass until nothing changes (at most 8 passes). WithoutPATHit walks the workspace with the workspace filter,.gitignoreincluded; a directoryPATHis walked with the same filter. Hidden directories below the walked directory, such as.gitor.snapshots, are skipped, as forlint. The default rules are the exact, behavior-preserving ones (familiesidiomandmigration) and your ownrecipe/<name>rules from themodernize_recipesconfig key. Themigrationrules rewrite deprecated or removed Odin forms into the current ones with the same meaning:base-imports(core:runtime,core:intrinsicsandcore:builtintobase:),os2-import(core:os/os2toos2 "core:os", skipped when the file already importscore:os),field-align(#field_alignto#min_field_align),align-parens(#align N,#min_field_align Nand#max_field_align Nto#align(N)and so on),for-blank(for in xtofor _ in x),switch-blank(switch in utoswitch _ in u),partial-dup(#partial #partial switchto one#partial),optimization-mode("minimal"to"none","size"and"speed"to"favor_size", as the compiler messages name them),proc-do-body(proc() do stmtto a braced body),strconv-itoaandstrconv-ftoa(deprecatedstrconv.itoa(buf, i)tostrconv.write_int(buf, i64(i), 10)andftoatowrite_float, through any import alias), andfeature-tags(adds#+feature using-stmtfor ausingstatement or parameter, and#+feature dynamic-literalsfor a typedmapor[dynamic]literal with elements).file-tagsturns//+build,//+privateand the other old tag comments into#+tags; it is areviewrule because the compiler ignores the comment form, so the rewrite brings back the build filter and changes which files build.triple-quoteis anidiomrule: it turns a multiline raw string into a triple-quoted raw string (```…```) and indents the content to the line where the literal starts, so a leading or trailing newline stays as a blank line and the value is unchanged. Rules that delete code or can change behavior (familyreview, such asunused-variable/remove,use-stdlib/copy-loop,use-stdlib/clamp-ifand themax,minandabsrules, which differ on floats) run only when--rulenames them or their family.redundant-elseis anidiomrule because it fires only when the if-branch ends inreturn,breakorcontinue, theifhas no label, is not part of anelse ifchain, and is a statement of a block that is not awhenbody. The else must also declare no name that another statement of that block mentions, except as a field name after a selector or an enum member after a dot. When statements follow theif, the else must not end inreturn,break,continue,fallthrough,panicorunreachableand must hold nodeferof its own.--listprints every rule with its family and whether it is a default. The default output isfile:line:col: [rule] titleper fix; a fix from a later pass is marked(pass N)and its position is in the text the previous pass left.--diffand--applytreat every changed file as one edit and behave as forrenamebelow, except that the summary line counts the fixes the list prints, such asmodernize: 14 edits in 7 files:--diffprints the unified diff and summary line,--applywrites every file or none afterodin check, and--jsonprints the same object. All modes use the refactor exit codes below:0when there are fixes (listed, previewed or applied),3when nothing changes,2for an unknown rule, and1refused, with nothing written, when a file cannot be read or a pass was undone because its result did not parse; each cause is anerror:line. A file still changing after 8 passes, or one whose remaining fixes all span the place where imports go, is reported on stderr without changing the exit code. A file that does not parse is skipped with a note on stderr. A rule runs only while its lint is enabled in the config; themigrationrules have no lint and always run. Imports the fixes need are added, sorted among the imports of the same collection; nothing is reformatted
TARGET is FILE:LINE:COL or a symbol path PKG.Name or PKG.Name.Member. PKG is a directory, relative to the cwd, or a collection path like core:strings: the longest prefix before a . that is a directory of .odin files, so core:path/slashpath.join and directories with dots work. .Name and ./Name name a symbol of the package in the cwd. Member is a struct field, an enum member or a bit_field field. A symbol path that is not found, is declared more than once (in when branches, say) or names a member of a type without members is refused, for example ols query rename src/game.Player.hp health.
Without --apply, rename, reorder-params, move, rename-package and attr print a dry run: a unified diff of every changed file (--- a/PATH, +++ b/PATH, paths relative to the root, a created file diffed from /dev/null) and a summary line such as rename: 7 edits in 3 files. A renamed directory gets a git-style header first (diff --git a/OLD b/NEW, rename from OLD, rename to NEW), and the files in it are diffed from their old path to their new one. --apply, there and on actions, writes every file or none:
- Every new file text is computed in memory first. An invalid or overlapping edit range refuses the edit.
odin checkruns on each package directory the edit touches and on each workspace package that imports one, directly or through other importers, found with the workspace filter. The check passes the collections, defines,-fileor-no-entry-point,-json-errorsand yourchecker_args, but none of theenable_checker_vet_*andenable_checker_strict_styleflags:-vet-styleturns a missing trailing comma into a Syntax Error that stops checking, which would blind the gate. It also passes-max-error-count:100000, unlesschecker_argshas its own-max-error-count, because Odin otherwise stops at 36 errors and reports a different subset on each run. Then the files are written, andodin checkruns again. The summary line ends with the number of packages checked, such asrename: 7 edits in 3 files written, 4 packages checked, and, when the gate also checked other targets (see below), with those targets, such as, also on windows_amd64; a target on which every package was dropped as not building there is not named. The JSONsummaryreads the same. Eachodin checkrun of the gate has 20 seconds for each batch of packages as large as the core count (the editor check keeps one 20-second budget), capped at 10 minutes, and a run that exceeds it refuses the edit;--no-checkskips the check. The gate also checks other build targets. A touched file that#+buildor a file name suffix such as_windows.odinor_js.odinexcludes from the current target adds one-target:value on which it builds, chosen fromwindows_amd64,linux_amd64,darwin_arm64,freebsd_amd64,openbsd_amd64,netbsd_amd64,js_wasm32,wasi_wasm32,orca_wasm32,freestanding_wasm32,freestanding_amd64_sysvand then the other architectures. The same goes for every other file in the directory of a touched file, such aslib_windows.odinnext to an editedlib.odin, and for every file of an importer directory. Such a target checks the directories of the files that need it and their importers, directly or through other importers, not every package. Awhencondition adds no target: a branch underwhen ODIN_OS == .Windowsin a file the current target builds is checked onwindows_amd64only when another file needs that target orchecker_targetsnames it. A touched file that builds on none of the candidate targets and is not#+build ignoregets awarning:and is not checked. The current target is the host, or the-target:ofchecker_args. The targets inchecker_targetsinols.json(windows_amd64, or a bare OS name such aswindowsfor its default architecture) are always added to those and check every package, and a name outside the gate's known targets is skipped with awarning:. Each entry ofchecker_variants, such as-define:SIM=true, adds one more check of every package on the current target with those arguments afterchecker_args, and the summary names it afteralso on, such as, also on -define:SIM=true. An entry with a-target:value, such as-define:SIM=true -target:linux_amd64, runs on that target and is named as written. The packages are checked for every target before and after the write. On a target other than the current one, and in achecker_variantscheck, a package whose check before the write reports an error in a file outside the workspace does not build there, such as a package that importscore:os, which panics onjs_wasm32: awarning:names it, and the gate runs that check without it, before and after the write. A package whose errors on that target are all in workspace files stays checked there. A target-only file needs no SDK:odin checkdoes not link. Since Odin dev-2026-10,odin checkrefuses a Windows target on another host: it asks for-windows-sdk-root, which onlyodin buildaccepts. The gate then skips that Windows check with awarning:and keeps checking the other targets. A Windows-target:inchecker_argsmakes every check fail, with a hint to drop it; the gate refuses the edit, and the editor shows the failure once in a message.- A file that changed on disk between the edit's computation and the write refuses the edit.
- An error that was not there before restores every file byte for byte and deletes the files the edit created. Errors are matched by the first line of their message, in any of the checked packages, and a
Different package name, expected …error is keyed by its two names in sorted order, since Odin swaps the names by parse order: a swap is the same error and a third name is a new one. Forrenameandrename-package, an existing error that is not matched as it is also matches with the old name replaced by the new one as a whole word, but only when it lies on a line that the edit changes, so an error that names the renamed symbol or package is not new and an error about another symbol of the same name stays as it is. Odin can report a different set of errors on each run, so before the edit counts as failed, the gate restores the files and checks the original code once more, only in the checks and packages whose errors after the write name the file of a new error. An error that this check of the original code reports as often as the check after the write is not new: the first check missed it. Then the edit is written again, after the same check that no file changed on disk, and when new errors remain, every check runs once more on the written code; the second check covers every package, as the first one did. An error is new only when both checks after the write report it, so an error that one run after the write reports by chance is not new. When no new error remains, awarning:says so and the edit stays written. A check of the original code or a second check after the write that cannot run keeps the new errors, with awarning:. The summary still counts the packages of the first check. - A check that cannot run (no
odin, a timeout, output that is not its JSON, a failing exit with no output) refuses the edit. A package check that a signal kills before it prints anything is logged and runs once more within the same time limit, and only a second such crash refuses the edit. A failed write restores the files it wrote, including the one that failed. - A directory rename (an LSP
RenameFile) runs after every file is written, and the check after it runs on the new path. A directory that disappeared, or a target that appeared, since the edit was computed refuses the edit. A rollback renames the directory back first, then restores the files; a rename that fails restores every file F6B7 .
When every package to check is missing or listed in checker_skip_packages, a warning: line on stderr (a reasons entry in JSON) says so and the edit is written without a check. When the check before the write already reports errors in a directory, a warning: line names it: a parse error stops odin check there, and so does a -max-error-count in checker_args, so the check cannot see new errors that hide behind them. --no-check skips both checks. With --json these commands print one object, {"status", "edit", "summary", "reasons"}, where status is applied, dry_run, refused, noop or check_failed and edit is the LSP WorkspaceEdit. In text mode each refusal cause is an error: … line on stderr.
Exit codes of the refactor commands: 0 applied or previewed, 1 refused with nothing written, 2 usage error, 3 nothing to change, 4 rolled back after odin check reported new errors. When a rollback cannot restore a file or rename a directory back, the command exits 1 with status refused, and each file that remains modified or directory that remains renamed gets its own error: line. Read-only queries keep their own codes. Every command exits 2 with the usage text when it gets more positional arguments than it takes: check, lint, tests and modernize take several paths, test takes several names after DIR, and every other command takes the arguments it lists.
Install the extension https://marketplace.visualstudio.com/items?itemName=DanielGavin.ols
Install the package https://github.com/sublimelsp/LSP
Configuration of the LSP:
Install Coc.
Configuration of the LSP:
{
"languageserver": {
"odin": {
"command": "ols",
"filetypes": ["odin"],
"rootPatterns": ["ols.json"]
}
}
}Neovim has a builtin support for LSP.
There is a plugin that makes the setup easier, called nvim-lspconfig. You can install it with your preferred package manager.
A simple configuration that uses the default ols settings would be like this:
require'lspconfig'.ols.setup {}And here is an example of a configuration with a couple of settings applied:
require'lspconfig'.ols.setup {
init_options = {
checker_args = "-strict-style",
collections = {
{ name = "shared", path = vim.fn.expand('$HOME/odin-lib') }
},
},
}- use an explicit
cmdforolswhen using a custom build
Neovim can run Odinfmt on save using the conform plugin. Here is a sample configuration using the lazy.nvim package manager:
local M = {
"stevearc/conform.nvim",
opts = {
notify_on_error = false,
-- Odinfmt gets its configuration from odinfmt.json. It defaults
-- writing to stdout but needs to be told to read from stdin.
formatters = {
odinfmt = {
-- Change where to find the command if it isn't in your path.
command = "odinfmt",
args = { "-stdin" },
stdin = true,
},
},
-- and instruct conform to use odinfmt.
formatters_by_ft = {
odin = { "odinfmt" },
},
},
}
return MIf you use LazyVim with Mason, cmd = { "ols" } may resolve to Mason's shim instead of your custom ols binary. OLS already documents editor-provided configuration and odin_command, so when using a custom OLS build it is safer to disable Mason only for OLS and set explicit paths.
return {
{
"neovim/nvim-lspconfig",
opts = {
servers = {
ols = {
mason = false,
cmd = { "/path/to/ols" },
settings = {
odin_command = "/path/to/odin",
},
},
},
},
},
}Notes:
- put
olsinsideopts.servers - keep Mason enabled for other language servers if you want
For Emacs, there are two packages available for LSP; lsp-mode and eglot.
The latter is built-in, spec-compliant and favours built-in Emacs functionality and the former offers richer UI elements and automatic installation for some of the servers.
In either case, you'll also need an associated major mode.
Pick either of the below, the former is likely to be more stable but the latter will allow you to take advantage of tree-sitter and other packages that integrate with it.
The use-package statements below assume you're using a package manager like Straight or Elpaca and as such should be taken as references rather than guaranteed copy/pasteable. If you're using package.el or another package manager then you'll have to look into instructions for that yourself.
;; Enable odin-mode and configure OLS as the language server
(use-package odin-mode
:ensure (:host github :repo "mattt-b/odin-mode")
:mode ("\\.odin\\'" . odin-mode))
;; Or use the WIP tree-sitter mode
(use-package odin-ts-mode
:ensure (:host github :repo "Sampie159/odin-ts-mode")
:mode ("\\.odin\\'" . odin-ts-mode))If you are using Emacs 29 or above you can use package-vc-install.
(package-vc-install
'(odin-mode :url "https://github.com/mattt-b/odin-mode.git"))
(package-vc-install
'(odin-ts-mode :url "https://github.com/Sampie159/odin-ts-mode.git"))And then choose either the built-in eglot or lsp-mode packages below. Both should work very similarly.
As of lsp-mode pull request 4818 ols is included as a pre-configured client. You will need to install lsp-mode from source until version 9.1 has been released. Just M-x lsp-install-server and select ols. This will download and install the latest version of ols from the releases. Then start lsp-mode with M-x lsp or add hook on the below package
;; Pull the lsp-mode package from elpa
(use-package lsp-mode
:commands (lsp lsp-deferred))
;; OR Pull lsp-mode from source using Straight this snippet has the install instructions for installing straight.el
(defvar straight-use-package-by-default t)
(defvar straight-recipes-repo-clone-depth 1)
(defvar straight-enable-github-repos t)
(defvar bootstrap-version)
(let ((bootstrap-file
(expand-file-name
"straight/repos/straight.el/bootstrap.el"
(or (bound-and-true-p straight-base-dir)
user-emacs-directory)))
(bootstrap-version 7))
(unless (file-exists-p bootstrap-file)
(with-current-buffer
(url-retrieve-synchronously
"https://raw.githubusercontent.com/radian-software/straight.el/develop/install.el"
'silent 'inhibit-cookies)
(goto-char (point-max))
(eval-print-last-sexp)))
(load bootstrap-file nil 'nomessage))
;; Configure straight.el
(straight-use-package 'use-package)
(use-package lsp-mode
:straight (lsp-mode :host github :repo "emacs-lsp/lsp-mode")
:commands (lsp lsp-deferred))
;; Add a hook to autostart OLS
(add-hook 'odin-mode-hook #'lsp-deferred)
(add-hook 'odin-ts-mode-hook #'lsp-deferred) ;; If you're using the TS mode;; Add OLS to the list of available programs
;; NOTE: As of Emacs 30, this is not needed.
(with-eval-after-load 'eglot
(add-to-list 'eglot-server-programs '((odin-mode odin-ts-mode) . ("ols"))))
;; Add a hook to autostart OLS
(add-hook 'odin-mode-hook #'eglot-ensure)
(add-hook 'odin-ts-mode-hook #'eglot-ensure) ;; If you're using the TS modeHelix supports Odin and OLS by default. It is already enabled in the default languages.toml.
If ols or odinfmt are not on your PATH environment variable, you can enable them like this:
# Optional. The default configration requires OLS in PATH env. variable. If not,
# you can set path to the executable like so:
# [language-server.ols]
# command = "path/to/executable"Install the LSP plugin
Configure the plugin in micro's settings.json:
{
"lsp.server": "c=clangd,go=gopls,odin=ols"
}misc/claude-plugin is a Claude Code plugin: it registers ols as the LSP server for .odin files and ships the ols skill, which tells the agent to find code through the LSP tool, learn packages with ols query api, run ols query check after edits and apply refactorings and tests with ols query. Add the directory holding it as a local marketplace, or copy it to ~/.claude/local-plugins/odin-lsp as install.sh does.
First, make sure you have the LSP plugin enabled. Then, you can find LSP settings for Kate in Settings -> Configure Kate -> LSP Client -> User Server Settings.
You may have to set the folders for your Odin home path directly, like in the following example:
{
"servers": {
"odin": {
"command": [
"ols"
],
"filetypes": [
"odin"
],
"url": "https://github.com/DanielGavin/ols",
"root": "%{Project:NativePath}",
"highlightingModeRegex": "^Odin$",
"initializationOptions": {
"collections": [
{
"name": "core",
"path": "/path/to/Odin/core"
},
{
"name": "vendor",
"path": "/path/to/Odin/vendor"
},
{
"name": "shared",
"path": "/path/to/Odin/shared"
},
{
"name": "src", // If your project has src-collection in root folder,
"path": "src" // this will add it as a collection
},
{
"name": "collection_a",
"path": "/path/to/collection_a"
}
],
"odin_command": "path/to/Odin",
"verbose": true,
"enable_document_symbols": true,
"enable_hover": true
}
}
}
}Kate can infer inlay hints on its own when enabled in LSP settings, so enabling it separately in the server config can cause some weird behavior.
{ "clients": { "odin": { "command": [ "/path/to/ols" ], "enabled": false, // true for globally-enabled, but not required due to 'Enable In Project' command "selector": "source.odin", "initializationOptions": { "collections": [ { "name": "collection_a", "path": "/path/to/collection_a" } ], "enable_semantic_tokens": true, "enable_document_symbols": true, "enable_hover": true, "enable_snippets": true, "enable_format": true, } } } }