Skip to main content

Emacs

Metals works in Emacs thanks to the lsp-mode package.

Emacs demo

Requirements#

Java 8, 11, 17 provided by OpenJDK or Oracle. Eclipse OpenJ9 is not supported, please make sure the JAVA_HOME environment variable points to a valid Java 8, 11 or 17 installation.

macOS, Linux or Windows. Metals is developed on many operating systems and every PR is tested on Ubuntu, Windows and MacOS.

Scala 2.13, 2.12, 2.11 and Scala 3. Metals supports these Scala versions:

  • Scala 2.13: 2.13.6, 2.13.5, 2.13.4, 2.13.3, 2.13.2, 2.13.1, 2.13.0

  • Scala 2.12: 2.12.15, 2.12.14, 2.12.13, 2.12.12, 2.12.11, 2.12.10, 2.12.9, 2.12.8

  • Scala 2.11: 2.11.12

  • Scala 3: 3.1.0-RC3, 3.0.2, 3.0.1, 3.0.0

Note that 2.11.x support is deprecated and it will be removed in future releases. It's recommended to upgrade to Scala 2.12 or Scala 2.13

Installation#

To use Metals in Emacs, place this snippet in your Emacs configuration (for example .emacs.d/init.el) to load lsp-mode along with its dependencies:

(require 'package)
;; Add melpa to your packages repositories
(add-to-list 'package-archives '("melpa" . "https://melpa.org/packages/") t)
(package-initialize)
;; Install use-package if not already installed
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
;; Enable defer and ensure by default for use-package
;; Keep auto-save/backup files separate from source code: https://github.com/scalameta/metals/issues/1027
(setq use-package-always-defer t
use-package-always-ensure t
backup-directory-alist `((".*" . ,temporary-file-directory))
auto-save-file-name-transforms `((".*" ,temporary-file-directory t)))
;; Enable scala-mode for highlighting, indentation and motion commands
(use-package scala-mode
:interpreter
("scala" . scala-mode))
;; Enable sbt mode for executing sbt commands
(use-package sbt-mode
:commands sbt-start sbt-command
:config
;; WORKAROUND: https://github.com/ensime/emacs-sbt-mode/issues/31
;; allows using SPACE when in the minibuffer
(substitute-key-definition
'minibuffer-complete-word
'self-insert-command
minibuffer-local-completion-map)
;; sbt-supershell kills sbt-mode: https://github.com/hvesalai/emacs-sbt-mode/issues/152
(setq sbt:program-options '("-Dsbt.supershell=false"))
)
;; Enable nice rendering of diagnostics like compile errors.
(use-package flycheck
:init (global-flycheck-mode))
(use-package lsp-mode
;; Optional - enable lsp-mode automatically in scala files
:hook (scala-mode . lsp)
(lsp-mode . lsp-lens-mode)
:config
;; Uncomment following section if you would like to tune lsp-mode performance according to
;; https://emacs-lsp.github.io/lsp-mode/page/performance/
;; (setq gc-cons-threshold 100000000) ;; 100mb
;; (setq read-process-output-max (* 1024 1024)) ;; 1mb
;; (setq lsp-idle-delay 0.500)
;; (setq lsp-log-io nil)
;; (setq lsp-completion-provider :capf)
(setq lsp-prefer-flymake nil))
;; Add metals backend for lsp-mode
(use-package lsp-metals)
;; Enable nice rendering of documentation on hover
;; Warning: on some systems this package can reduce your emacs responsiveness significally.
;; (See: https://emacs-lsp.github.io/lsp-mode/page/performance/)
;; In that case you have to not only disable this but also remove from the packages since
;; lsp-mode can activate it automatically.
(use-package lsp-ui)
;; lsp-mode supports snippets, but in order for them to work you need to use yasnippet
;; If you don't want to use snippets set lsp-enable-snippet to nil in your lsp-mode settings
;; to avoid odd behavior with snippets and indentation
(use-package yasnippet)
;; Use company-capf as a completion provider.
;;
;; To Company-lsp users:
;; Company-lsp is no longer maintained and has been removed from MELPA.
;; Please migrate to company-capf.
(use-package company
:hook (scala-mode . company-mode)
:config
(setq lsp-completion-provider :capf))
;; Use the Debug Adapter Protocol for running tests and debugging
(use-package posframe
;; Posframe is a pop-up tool that must be manually installed for dap-mode
)
(use-package dap-mode
:hook
(lsp-mode . dap-mode)
(lsp-mode . dap-ui-mode)
)

You may need to disable other packages like ensime or sbt server to prevent conflicts with Metals.

Next you have to install metals server. Emacs can do it for you when lsp-mode is enabled in a scala buffer or via lsp-install-server command. Also you can do it manually executing coursier install metals and configuring $PATH variable properly.

Importing a build#

The first time you open Metals in a new workspace it prompts you to import the build. Type "Import build" or press Tab and select "Import build" to start the installation step.

Import build

  • "Not now" disables this prompt for 2 minutes.
  • "Don't show again" disables this prompt forever, use rm -rf .metals/ to re-enable the prompt.
  • Use tail -f .metals/metals.log to watch the build import progress.
  • Behind the scenes, Metals uses Bloop to import sbt builds, but you don't need Bloop installed on your machine to run this step.

Once the import step completes, compilation starts for your open *.scala files.

Once the sources have compiled successfully, you can navigate the codebase with goto definition.

Custom sbt launcher#

By default, Metals runs an embedded sbt-launch.jar launcher that respects .sbtopts and .jvmopts. However, the environment variables SBT_OPTS and JAVA_OPTS are not respected.

Update the server property -Dmetals.sbt-script=/path/to/sbt to use a custom sbt script instead of the default Metals launcher if you need further customizations like reading environment variables.

Speeding up import#

The "Import build" step can take a long time, especially the first time you run it in a new build. The exact time depends on the complexity of the build and if library dependencies need to be downloaded. For example, this step can take everything from 10 seconds in small cached builds up to 10-15 minutes in large uncached builds.

Consult the Bloop documentation to learn how to speed up build import.

Importing changes#

When you change build.sbt or sources under project/, you will be prompted to re-import the build.

Import sbt changes

LSP Tips#

Show navigable stack trace#

You can annotate your stack trace with code lenses (which requires the following bit of configuration mentioned earlier: (lsp-mode . lsp-lens-mode)). These allow you to run actions from your code.

One of these actions allow you to navigate your stack trace.

You can annotate any stack trace by marking a stack trace with your region and using M-x lsp-metals-analyze-stacktrace on it.

This will open a new Scala buffer that has code lenses annotations: just click on the small "open" annotation to navigate to the source code relative to your stack trace.

This will work as long as the buffer your are marking your stack trace on exists within the project directory tracked by lsp-mode, because lsp-metals-analyze-stacktrace needs the lsp workspace to find the location of your errors.

Note that if you try to do that from sbt-mode, you may get an error unless you patch lsp-find-workspace with the following:

(defun lsp-find-workspace (server-id &optional file-name)
"Find workspace for SERVER-ID for FILE-NAME."
(-when-let* ((session (lsp-session))
(folder->servers (lsp-session-folder->servers session))
(workspaces (if file-name
(let* ((folder (lsp-find-session-folder session file-name))
(folder-last-char (substring folder (- (length folder) 1) (length folder)))
(key (if (string= folder-last-char "/") (substring folder 0 (- (length folder) 1)) folder)))
(gethash key folder->servers))
(lsp--session-workspaces session))))
(--first (eq (lsp--client-server-id (lsp--workspace-client it)) server-id) workspaces)))

The above shall become unnecessary once this issue is solved.

Reference#

Manually trigger build import#

To manually trigger a build import, run M-x lsp-metals-build-import.

Import build command

Run doctor#

Run M-x lsp-metals-doctor-run to troubleshoot potential configuration problems in your build.

Run doctor command

eglot#

There is an alternative LSP client called eglot that might be worth trying out if you want to use an alternative to lsp-mode.

To configure Eglot with Metals:

(require 'package)
;; Add melpa-stable to your packages repositories
(add-to-list 'package-archives '("melpa-stable" . "https://stable.melpa.org/packages/") t)
(package-initialize)
;; Install use-package if not already installed
(unless (package-installed-p 'use-package)
(package-refresh-contents)
(package-install 'use-package))
(require 'use-package)
;; Enable defer and ensure by default for use-package
(setq use-package-always-defer t
use-package-always-ensure t)
;; Enable scala-mode and sbt-mode
(use-package scala-mode
:interpreter
("scala" . scala-mode))
;; Enable sbt mode for executing sbt commands
(use-package sbt-mode
:commands sbt-start sbt-command
:config
;; WORKAROUND: https://github.com/ensime/emacs-sbt-mode/issues/31
;; allows using SPACE when in the minibuffer
(substitute-key-definition
'minibuffer-complete-word
'self-insert-command
minibuffer-local-completion-map)
;; sbt-supershell kills sbt-mode: https://github.com/hvesalai/emacs-sbt-mode/issues/152
(setq sbt:program-options '("-Dsbt.supershell=false"))
)
(use-package eglot
:pin melpa-stable
;; (optional) Automatically start metals for Scala files.
:hook (scala-mode . eglot-ensure))

If you start Emacs now then it will fail since the metals-emacs binary does not exist yet.

Next, build a metals-emacs binary for the latest Metals release using the Coursier command-line interface.

VersionPublishedResolver
0.10.716 Sep 2021 16:28-r sonatype:releases
0.10.7+151-a79d7e37-SNAPSHOT21 Oct 2021 09:46-r sonatype:snapshots
# Make sure to use coursier v1.1.0-M9 or newer.
curl -L -o coursier https://git.io/coursier-cli
chmod +x coursier
./coursier bootstrap \
--java-opt -Xss4m \
--java-opt -Xms100m \
--java-opt -Dmetals.client=emacs \
org.scalameta:metals_2.12:0.10.7 \
-r bintray:scalacenter/releases \
-r sonatype:snapshots \
-o /usr/local/bin/metals-emacs -f

Make sure the generated metals-emacs binary is available on your $PATH.

You can check version of your binary by executing metals-emacs -version.

Configure the system properties -Dhttps.proxyHost=… -Dhttps.proxyPort=… if you are behind an HTTP proxy.

The -Dmetals.client=emacs flag is important since it configures Metals for usage with Emacs.

Files and Directories to include in your Gitignore#

The Metals server places logs and other files in the .metals directory. The Bloop compile server places logs and compilation artifacts in the .bloop directory. The Bloop plugin that generates Bloop configuration is added in the metals.sbt file, which is added at project/metals.sbt as well as further project directories depending on how deep *.sbt files need to be supported. To support each *.sbt file Metals needs to create an additional file at ./project/project/metals.sbt relative to the sbt file. Working with Ammonite scripts will place compiled scripts into the .ammonite directory. It's recommended to exclude these directories and files from version control systems like git.

# ~/.gitignore
.metals/
.bloop/
.ammonite/
metals.sbt

Worksheets#

Worksheets are a great way to explore an api, try out an idea, or code up an example and quickly see the evaluated expression or result. Behind the scenes worksheets are powered by the great work done in mdoc.

Getting started with Worksheets#

To get started with a worksheet you can either use the metals.new-scala-file command and select Worksheet or create a file called *.worksheet.sc. This format is important since this is what tells Metals that it's meant to be treated as a worksheet and not just a Scala script. Where you create the script also matters. If you'd like to use classes and values from your project, you need to make sure the worksheet is created inside of your src directory. You can still create a worksheet in other places, but you will only have access to the standard library and your dependencies.

Evaluations#

After saving you'll see the result of the expression as a comment as the end of the line. You may not see the full result for example if it's too long, so you are also able to hover on the comment to expand.

Keep in mind that you don't need to wrap your code in an object. In worksheets everything can be evaluated at the top level.

Using dependencies in worksheets#

You are able to include an external dependency in your worksheet by including it in one of the following two ways.

// $dep.`organisation`::artifact:version` style
import $dep.`com.lihaoyi::scalatags:0.7.0`
// $ivy.`organisation::artifact:version` style
import $ivy.`com.lihaoyi::scalatags:0.7.0`

:: is the same as %% in sbt, which will append the current Scala binary version to the artifact name.

You can also import scalac options in a special $scalac import like below:

import $scalac.`-Ywarn-unused`