Home

Awesome

ElixirLS - Elixir Language Server and Debug Adapter

Actions Status Slack

ElixirLS is provides two components: a language server driving code intelligence and a debug adapter that allows step through debugging of Elixir projects. Language server adheres to the Language Server Protocol. Debug adapter implements Debug Adapter Protocol.

This is the main elixir-ls repo

This repo is a community maintained fork. The original repository JakeBecker/elixir-ls has now been deprecated in favor of this one.

Features

Screenshot

Note: On its first run, Dialyzer will build a PLT cache. This will take a considerable amount of CPU time (usually 10+ minutes). After that is complete, the CPU usage will go back to normal. Alternatively, instead of waiting you can disable Dialyzer in the settings.

IDE plugins

IDEPluginSupport
BBEditbbpackage
Emacseglot
Emacslsp-modeSupports debug adapter via dap-mode
Kakounekak-lspLimitations
Katebuilt-in LSP Client pluginDoes not support debug adapter
Neovimcoc.nvimDoes not support debug adapter
Neovimnvim-dapSupports debug adapter only
Neovimnvim-lspconfigDoes not support debug adapter
Novanova-elixir-ls
Sublime TextLSP-elixirDoes not support debug adapter
Vim/NeovimALEDoes not support debug adapter or @spec suggestions
Vim/Neovimelixir-lsp/coc-elixirDoes not support debug adapter
Vim/Neovimvim-lspDoes not support debug adapter
VS Codeelixir-lsp/vscode-elixir-lsSupports all ElixirLS features
Helixelixir-lspSupports all ElixirLS features
Zedelixir language supportSupports all ElixirLS features

Please feel free to create and publish your own client packages and add them to this list!

Detailed Installation Instructions

The installation process for ElixirLS depends on your editor.

<details> <summary>VSCode</summary>

Please install the extension via the following link: https://marketplace.visualstudio.com/items?itemName=JakeBecker.elixir-ls

</details> <details> <summary>Emacs Installation Instructions</summary>

Download the latest release and unzip it into a directory. (This is the directory referred to as the "path-to-elixir-ls/release", below.)

If you will be using lsp-mode, add this configuration:

  (use-package lsp-mode
    :commands lsp
    :ensure t
    :diminish lsp-mode
    :hook
    (elixir-mode . lsp)
    :init
    (add-to-list 'exec-path "path-to-elixir-ls/release"))

For eglot, use:

(require 'eglot)

;; This is optional. It automatically runs `M-x eglot` for you whenever you are in `elixir-mode`:
(add-hook 'elixir-mode-hook 'eglot-ensure)

;; Be sure to edit the path appropriately; use the `.bat` script instead for Windows:
(add-to-list 'eglot-server-programs '(elixir-mode "path-to-elixir-ls/release/language_server.sh"))
</details>

Supported Elixir and OTP versions

Elixir itself supports five versions with security updates: https://hexdocs.pm/elixir/compatibility-and-deprecations.html#content

OTP supports the last three versions: http://erlang.2086793.n4.nabble.com/OTP-Versions-and-Maint-Branches-td4722416.html

ElixirLS generally aims to support the last three released versions of Elixir and the last three versions of OTP. However this is not a hard and fast rule and may change in the future.

Support matrix

OTP VersionsElixir VersionsSupports ElixirLSIssue(s)
any<= 1.13NoNo support for required APIs
221.13YesErlang docs not working (requires EIP 48)
231.13 - 1.14YesNone
241.13 - 1.16YesNone
251.13.4 - 1.17YesNone
26.0.0 - 26.0.1anyNo#886
26.0.2 - 26.1.21.14.5 - 1.17*nix only#927, #1023
>= 26.2.01.14.5 - 1.17YesNone
any1.15.5YesBroken formatter #975
271.17YesNone

Version management

It is generally recommended to install Elixir and Erlang via ASDF so that you can have different projects using different versions of Elixir without having to change your system-installed version. ElixirLS can detect and use the versions of Elixir and Erlang that you have configured in ASDF.

Debugger support

ElixirLS provides debug adapter support adhering to the Debug Adapter Protocol, which is closely related to the Language Server Protocol.

When debugging in Elixir or Erlang, only modules that have been "interpreted" (using :int.ni/1 or :int.i/1) will accept breakpoints or show up in stack traces. The debugger in ElixirLS automatically interprets all modules in the Mix project and its dependencies before launching the Mix task. Therefore, you can set breakpoints anywhere in your project or dependency modules.

Please note that there is currently a limit of 100 breakpoints.

To debug modules in .exs files (such as tests), they must be specified under requireFiles in your launch configuration so that they can be loaded and interpreted before running the task. For example, the default launch configuration for mix test in the VSCode plugin is shown below:

{
  "type": "mix_task",
  "name": "mix test",
  "request": "launch",
  "task": "test",
  "taskArgs": ["--trace"],
  "startApps": true,
  "projectDir": "${workspaceRoot}",
  "requireFiles": ["test/**/test_helper.exs", "test/**/*_test.exs"]
}

Currently, to debug a single test or a single test file, it is necessary to modify taskArgs and ensure that no other tests are required in requireFiles.

{
  "type": "mix_task",
  "name": "mix test",
  "request": "launch",
  "task": "test",
  "taskArgs": ["tests/some_test.exs:123"],
  "startApps": true,
  "projectDir": "${workspaceRoot}",
  "requireFiles": ["test/**/test_helper.exs", "test/some_test.exs"]
}

Debugging Phoenix apps

To debug Phoenix applications using ElixirLS, you can use the following launch configuration:

{
  "type": "mix_task",
  "name": "phx.server",
  "request": "launch",
  "task": "phx.server",
  "projectDir": "${workspaceRoot}"
}

Please make sure that startApps is not set to true. To clarify, startApps is a configuration option in the ElixirLS debug adapter. It controls whether or not to start the applications in the Mix project before running the task. In the case of Phoenix applications, setting startApps to true can interfere with the application's normal startup process and cause issues.

If you are running tests in the Phoenix application, you may need to set startApps to true. This will ensure that the necessary applications are started before the tests run.

NIF modules limitation

It's important to note that NIF (Native Implemented Function) modules cannot be interpreted due to limitations in :int. Therefore, these modules need to be excluded, using the excludeModules option. This option can also be used to disable interpretation for specific modules when it's not desirable, such as when performance is unsatisfactory.

{
  "type": "mix_task",
  "name": "mix test",
  "request": "launch",
  "task": "test",
  "taskArgs": ["--trace"],
  "projectDir": "${workspaceRoot}",
  "requireFiles": ["test/**/test_helper.exs", "test/**/*_test.exs"],
  "excludeModules": [":some_nif", "Some.SlowModule"]
}

Function breakpoints

Function breakpoints in ElixirLS allow you to break on the first line of every clause of a specific function. In order to set a function breakpoint, you need to specify the function in the format of MFA (module, function, arity).

For example, to set a function breakpoint on the foo function in the MyModule module that takes one argument, you would specify it as MyModule.foo/1.

Please note that function breakpoints only work for public functions and do not support breaking on private functions.

Conditional breakpoints

Break conditions allow you to specify an expression that, when evaluated, determines whether the breakpoint should be triggered or not. The expression is evaluated within the context of the breakpoint, which includes all bound variables.

For example, you could set a breakpoint on a line of code that sets a variable x, adding a break condition of x > 10. This would cause the breakpoint to trigger when that line of code is executed, but only if the value of x is greater than 10 when that line of code is executed.

However, it's important to note that the expression evaluator used by ElixirLS has some limitations. For example, it doesn't support some Elixir language features, such as macros and some built-in functions. In addition, the expression evaluator is not as powerful as the one used by the Elixir interpreter, so some expressions that work in the interpreter may not work in ElixirLS.

Hit conditions

A "hit condition" is an optional parameter that can be set on a breakpoint to control how many times a breakpoint should be hit before stopping the process. It is expressed as an integer and can be used to filter out uninteresting hits, allowing the process to continue until a certain condition is met.

For example, if you have a loop that runs 10 times and you want to stop the process only when the loop reaches the 5th iteration, you can set a breakpoint with a hit condition of five. This will cause the breakpoint to be hit only on the 5th iteration of the loop; the process will continue to run until then.

Log points

"Log points" are a type of breakpoint that logs a message to the standard output without stopping program execution. When a log point is hit, the message is evaluated and printed to the console. The message can include interpolated expressions enclosed in curly braces {}, e.g. my_var is {inspect(my_var)}. These expressions will be evaluated in the context of the breakpoint. To escape the curly braces, you can use the escape sequence \{ and \}.

It's important to note that as of version 1.51 of the Debug Adapter Protocol specification, log messages are not supported on function breakpoints.

Expression evaluator

The debugger's expression evaluator has some limitations due to how the Erlang VM works. Specifically, the evaluator is implemented using :int, which works at the level of individual BEAM instructions. As a result, it returns multiple versions of variables in Static Single Assignment form, without indicating which one is valid in the current Elixir scope.

To work around this, the evaluator uses a heuristic to select the highest versions of variables. However this doesn't always behave correctly in all cases. For example, in the following code snippet:

a = 4
if true do
  a = 5
end
some

If a breakpoint is set on the line with some_function(), the last bound value for a seen by the expression breakpoint evaluator will be 5, even though it should be 4.

Additionally, although all bound variables are accessible in the expression evaluator, the evaluator doesn't support accessing module attributes (because these are determined at compile time).

Connecting to debug adapter

It may be useful to connect to a running debug adapter node via OTP distribution. This enables inspecting the running application and remotely triggering debugged functions. In order to do so, set ELS_ELIXIR_OPTS environment variable in the launch configuration (VSCode only) or Local setup script and pass in the appropriate node name/sname and cookie.

{
  "env": {
    "ELS_ELIXIR_OPTS": "--name mynode@localhost --cookie secret"
  }
}

Attaching to remote nodes

ElixirLS debug adapter is capable of remote debugging OTP cluster nodes. This functionality relies on OTP debugger. In order to attach to a remote node some@host a special launch config with request attach is needed. The launch config must specify remoteNode. Remember to provide ELS_ELIXIR_OPTS environment variable in the launch configuration (VSCode only) or Local setup script with cookie and name or sname for local DAP node.

{
  "type": "mix_task",
  "name": "attach",
  "request": "attach",
  "projectDir": "${workspaceRoot}",
  "remoteNode": "some@host",
  "debugAutoInterpretAllModules": false,
  "debugInterpretModulesPatterns": ["MyApp.*"],
  "env": {
    "ELS_ELIXIR_OPTS": "--sname elixir_ls_dap --cookie mysecret"
  }
}

Troubleshooting

Limitations

Remote debugger has several limitations compared to local debugger:

Warning

ElixirLS debug adapter interprets modules with :int.ni/1 on all connected nodes. It attempts to uninterpret all modules on debug session end but that may not be possible due to loss of connectivity. This may affect production workloads. Use remote debugging with caution.

Automatic builds and error reporting

ElixirLS provides automatic builds and error reporting. By default, builds are triggered automatically when files are saved, but you can also enable "autosave" in your IDE to trigger builds as you type. If you prefer to disable automatic builds, you can set the elixirLS.autoBuild configuration option to false.

Internally, ElixirLS uses the mix compile task to compile Elixir code. When errors or warnings are encountered during compilation, they are returned as LSP diagnostics. Your IDE may display them inline in your code as well as in the "Problems" pane. This allows you to quickly identify and fix errors in your code as you work.

Dialyzer integration

Dialyzer is a static analysis tool used to identify type discrepancies, unused code, unreachable code, and other warnings in Erlang and Elixir code. ElixirLS provides automatic integration with Dialyzer to help catch issues early on in the development process.

After each successful build, ElixirLS automatically analyzes the project with Dialyzer and maintains a "manifest" file in .elixir_ls/dialyzer_manifest to store the results of the analysis. The initial analysis of a project can take a few minutes, but subsequent analyses are usually very fast, often taking less than a second. ElixirLS also looks at your modules' abstract code to determine whether they reference any modules that haven't been analyzed and includes them automatically.

You can control which warnings are shown by using the elixirLS.dialyzerWarnOpts setting in your project or IDE's settings.json. You can find available options in dialyzer documentation, under the section "Warning options".

To disable Dialyzer completely, set elixirLS.dialyzerEnabled to false.

If Dialyzer gets stuck and emits incorrect or outdated warnings, it's best to restart the language server.

Code completion

ElixirLS provides an advanced code completion provider. This provider uses two main mechanisms to provide suggestions to the user.

The first mechanism is reflection, which involves getting information about compiled modules from the Erlang and Elixir APIs. This mechanism provides precise results, but it is not well suited for on-demand completion of symbols from the currently edited file. The compiled version of the code may be outdated or the file may not even compile, which can lead to inaccurate results.

The second mechanism used by the code completion provider is AST analysis of the current text buffer. This mechanism helps in cases where reflection is not accurate enough (e.g., completing symbols from the currently edited file). However, it also has its limitations. Due to the metaprogramming-heavy nature of Elixir, it is infeasible to be 100% accurate with AST analysis.

The completions include:

Workspace Symbols

With Dialyzer integration enabled, ElixirLS will build an index of symbols (modules, functions, types, and callbacks). The symbols are taken from the current workspace, all dependencies, and stdlib (Elixir and Erlang). This feature enables quick navigation to symbol definitions.

ElixirLS configuration settings

Below is a list of configuration options supported by the ElixirLS language server. Please refer to your editor's documentation to determine how to configure language servers.

<dl> <dt>elixirLS.autoBuild</dt><dd>Trigger ElixirLS build when code is saved</dd> <dt>elixirLS.dialyzerEnabled</dt><dd>Run ElixirLS's rapid Dialyzer when code is saved</dd> <dt>elixirLS.incrementalDialyzer</dt><dd>Use OTP incremental dialyzer (available on OTP 26+)</dd> <dt>elixirLS.dialyzerWarnOpts</dt><dd>Dialyzer options to enable or disable warnings - See Dialyzer's documentation for options. Note that the <code>race_conditions</code> option is unsupported.</dd> <dt>elixirLS.dialyzerFormat</dt><dd>Formatter to use for Dialyzer warnings</dd> <dt>elixirLS.envVariables</dt><dd>Environment variables to use for compilation</dd> <dt>elixirLS.mixEnv</dt><dd>Mix environment to use for compilation</dd> <dt>elixirLS.mixTarget</dt><dd>Mix target to use for compilation</dd> <dt>elixirLS.projectDir</dt><dd>Subdirectory containing the Mix project, if it is not in the project root</dd> <dt>elixirLS.fetchDeps</dt><dd>Automatically fetch project dependencies when compiling.</dd> <dt>elixirLS.suggestSpecs</dt><dd>Suggest <code>@spec</code> annotations inline, using Dialyzer's inferred success typings (Requires Dialyzer).</dd> <dt>elixirLS.trace.server</dt><dd>Traces communication between VS Code and the Elixir language server.</dd> <dt>elixirLS.autoInsertRequiredAlias</dt><dd>Enable auto-insert required alias - By default, this option is <code>true</code> (enabled).</dd> <dt>elixirLS.signatureAfterComplete</dt><dd>Show signature help after confirming autocomplete.</dd> <dt>elixirLS.enableTestLenses</dt><dd>Show code lenses to run tests in terminal.</dd> <dt>elixirLS.additionalWatchedExtensions</dt><dd>Additional file types capable of triggering a build on change</dd> <dt>elixirLS.languageServerOverridePath</dt><dd>Absolute path to an alternative ElixirLS release that will override the packaged release</dd> </dl>

Debug Adapter configuration options

Below is a list of configuration options supported by the ElixirLS Debug Adapter. Configuration options can be supplied via launch configuration. Please refer to your editor's documentation on how to configure debug adapters.

<dl> <dt>startApps</dt><dd>Run <code>mix app.start</code> before launching the debugger. Some tasks (such as Phoenix tests) expect apps to already be running before the test files are required. Defaults to <code>false</code>.</dd> <dt>task</dt><dd>Mix task to run with debugger - Defaults to task set under <code>:default_task</code> key in mixfile.</dd> <dt>taskArgs</dt><dd>A list of arguments to mix task</dd> <dt>debugAutoInterpretAllModules</dt><dd>Auto interpret all modules from project build path. Defaults to <code>true</code>.</dd> <dt>env</dt><dd>An object with environment variables - To set Object keys, specify environment variables; values should be strings.</dd> <dt>stackTraceMode</dt><dd>Option passed to <code>:int.stack_trace/1</code>. See <a href='https://www.erlang.org/doc/man/int#stack_trace-1'>:int.stack_trace/1</a> for details. Allowed values are <code>all</code>, <code>no_tail</code>, and <code>false</code>.</dd> <dt>requireFiles</dt><dd>A list of additional files that should be required and interpreted - This is especially useful for debugging tests.</dd> <dt>debugInterpretModulesPatterns</dt><dd>A list of globs specifying modules that should be interpreted</dd> <dt>projectDir</dt><dd>An absolute path to the directory where `mix.exs` is located - In VSCode, <code>${workspaceRoot}</code> can be used.</dd> <dt>excludeModules</dt><dd>A list of modules that should not be interpreted</dd> <dt>exitAfterTaskReturns</dt><dd>Should the debug session stop when mix task returns. Tasks that return early while the code continues running asynchronously require <code>false</code> setting. Defaults to <code>true</code>.</dd> <dt>noDebug</dt><dd>Run mix task without debugging. Defaults to <code>false</code>.</dd> <dt>breakOnDbg</dt><dd>Should the debugger break on Kernel.dbg/2 macro. Defaults to <code>true</code>.</dd> </dl>

Troubleshooting

Basic troubleshooting steps:

You may need to set elixirLS.mixEnv, elixirLS.mixTarget, and elixirLS.projectDir if your project requires this. By default, ElixirLS compiles code with MIX_ENV=test and MIX_TARGET=host; it assumes that mix.exs is located in the workspace root directory.

If you get an error like the following immediately on startup:

[Warn  - 1:56:04 PM] ** (exit) exited in: GenServer.call(ElixirLS.LanguageServer.JsonRpc, {:packet, %{...snip...}}, 5000)
    ** (EXIT) no process: the process is not alive or there's no process currently associated with the given name, possibly because its application isn't started

and you installed Elixir and Erlang from the Erlang Solutions repository, you may not have a full installation of Erlang. This can be solved with sudo apt-get install esl-erlang. (This was originally reported in #208).

On Fedora Linux, if you only install the Elixir package you will not have a full Erlang installation. This can be fixed by running sudo dnf install erlang (This was reported in #231).

Known Issues/Limitations

Building and running

There are two ways of building the release: Mix.install based (recommended) and .ez archives (deprecated).

Mix.install based release

mix deps.get
MIX_ENV=prod mix compile
MIX_ENV=prod mix elixir_ls.release2 -o <release_dir>

This copies language server and debugger adapter launch scripts to the <release_dir> and includes a VERSION manifest file. The launch scripts install a release specified by the version manifest via Mix.install and then launch it. This ensures that ElixirLS is built with the correct combination of Elixir and OTP.

Local setup

This section provides additional information on how to set up the ElixirLS locally.

When launching ElixirLS from an IDE that is itself launched from a graphical shell, the environment may not be complete enough to find or run the correct Elixir/OTP version. To address this on Unix or Linux, the ElixirLS wrapper scripts try to configure ASDF (a version manager for Elixir and other languages), but that may not always be what is needed.

To ensure that the correct environment is set up, you can create a setup script. The setup script location varies based on platform and shell:

In the setup script, the environment variable ELS_MODE is available and set to either debug_adapter or language_server to help you decide what to do.

Note: The setup script must not read from stdin or write to stdout. On Unix, Linux, and macOS this might be accomplished by adding >/dev/null at the end of any line that produces output; for a Windows batch script, you will want to add @echo off at the top and use >nul.

If you want to debug your setup script you can write to stderr.

Development

Please refer to DEVELOPMENT.md.

Environment variables

ElixirLS supports the following environment variables.

<dl> <dt>ELS_INSTALL_PREFIX</dt><dd>(not supported on Windows) The folder where the language server was installed - If set, this makes maintaining multiple versions/instances on the same host much easier. If it is not set or empty, a heuristic will be used to discover the install location.</dd> <dt>ELS_LOCAL</dt><dd>If set to <code>1</code>, this will make ElixirLS run a local release. If this is not set, a published release matching <code>VERSION</code> will be used (default).</dd> <dt>ELS_ELIXIR_OPTS</dt><dd>Optional parameters to pass to elixir CLI - May be used to set a node name and cookie.</dd> <dt>ELS_ERL_OPTS</dt><dd>Optional parameters to pass to the erl CLI</dd> <dt>ASDF_DIR</dt><dd>(not supported on Windows) If this is set, ElixirLS will look for the <a href="https://github.com/asdf-vm/asdf">ASDF</a> script in a directory given by that variable.</dd> </dl>

Telemetry

ElixirLS language server sends telemetry information to the client via LSP Telemetry notification, DAP Output event and DAP ErrorResponse. Telemetry data include usage, performance, environment info and error reports. Please refer to your client and/or extension documentation on telemetry.

Acknowledgements and related projects

ElixirLS incorporates code intelligence providers that were originally developed in Elixir Sense and still uses this library for lower lever operations. Other prior work includes Alchemist Server, Elixir plugin for Atom, VSCode Elixir. Credit for those projects goes to their respective authors.

License

ElixirLS source code is released under Apache License 2.0.

See LICENSE for more information.

ElixirLS includes parts of other projects, please see the respective licenses which apply to them.