Visual Studio Code Scala
Visual Studio Code Metals - Scala. Shop scalameta.org Best Offers This feature is enabled by default. If you need to disable/enable formatting on paste in Visual Studio Code you can check the Editor: Format On Paste setting: Worksheets. Worksheets are a great way to explore an api, try out an idea, or code up an example and quickly see. This video was recorded at Scala Days Lausanne 2019Follow us on Twitter @ScalaDays or visit our website for more information More inform.
The following table shows the status of various features.
Feature | Status | Notes |
---|---|---|
Import build | ✅ | Works with sbt, Gradle, Maven, Mill and Bloop. |
Compile errors | ✅ | Syntax errors as you type and type errors on file save. |
Completions | ✅ | |
Hover (type at point) | ✅ | |
Goto definition | ✅ | Works for project sources and Java/Scala library dependencies. |
Document symbols | ✅ | |
Formatting | ✅ | Uses Scalafmt. |
Find references | ✅ | |
Find implementations | ✅ | |
Workspace symbol | ✅ | Searches workspace sources and library dependencies. All-lowercase queries are case-insensitive. |
Highlight | ✅ | |
Folding | ✅ | |
Rename symbol | ✅ | |
Run/Debug | ✅ | |
Code actions | ✅ | |
Organize imports | ✅ | |
Show implicits | ✅ |
Requirements
Java 8 or 11 provided by OpenJDK or Oracle. Eclipse OpenJ9 is not supported,please make sure the JAVA_HOME
environment variable points to a valid Java 8or 11 installation.
macOS, Linux or Windows. Metals is developed on macOS and every PR is testedon Ubuntu+Windows.
Scala 2.13, 2.12, 2.11 and Scala 3. Metals supports these Scala versions2.13.5, 2.12.13, 2.12.12, 2.12.11, 2.12.10, 2.13.3, 2.13.4, 2.11.12, 2.12.8,2.12.9, 2.13.0, 2.13.1, 2.13.2, 3.0.0-RC3, 3.0.0-RC2, 3.0.0-RC1, 3.0.0-M3,3.0.0-M2 and 3.0.0-M1. Note that 2.11.x support is deprecated and it will beremoved in future releases. It's recommended to upgrade to Scala 2.12 or Scala2.13
Installation
Install the Metals extension from theMarketplace.
Make sure to disable the extensionsScala Language ServerandScala (sbt)if they are installed. TheDotty Language Serverdoes not need to be disabled because the Metals and Dotty extensions don'tconflict with each other. However, if you want to work on Scala 3 code in aworkspace that was previously opened with Dotty Language Server
you need tofirst remove .dotty-ide-artifact
before opening the workspace with Metals.
Next, open a directory containing your Scala code. The extension activates whenthe main directory contains build.sbt
or build.sc
file, a Scala file isopened, which includes *.sbt
, *.scala
and *.sc
file, or a standard Scaladirectory structure src/main/scala
is detected.
Importing a build
The first time you open Metals in a new workspace it prompts you to import thebuild. Click 'Import build' to start the installation step.
- 'Not now' disables this prompt for 2 minutes.
- 'Don't show again' disables this prompt forever, use
rm -rf .metals/
tore-enable the prompt. - Use
tail -f .metals/metals.log
to watch the build import progress. - Behind the scenes, Metals uses Bloopto import sbt builds, but you don't need Bloop installed on your machine torun 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 withgoto 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
andJAVA_OPTS
are not respected.
Update the 'Sbt Script' setting to use a custom sbt
script instead of thedefault Metals launcher if you need further customizations like readingenvironment variables.
Speeding up import
The 'Import build' step can take a long time, especially the first time you runit in a new build. The exact time depends on the complexity of the build and iflibrary dependencies need to be downloaded. For example, this step can takeeverything from 10 seconds in small cached builds up to 10-15 minutes in largeuncached builds.
Consult theBloop documentationto learn how to speed up build import.
Importing changes
When you change build.sbt
or sources under project/
, you will be prompted tore-import the build.
Manually trigger build import
To manually trigger a build import, execute the 'Import build' command throughthe command palette (Cmd + Shift + P
).
Run doctor
Execute the 'Run Doctor' through the command palette to troubleshoot potentialconfiguration problems in your workspace.
Configure Java version
The VS Code plugin uses by default the JAVA_HOME
environment variable (vialocate-java-home
) to locatethe java
executable. To override the default Java home location, update the'Java Home' variable in the settings menu.
If this setting is defined, the VS Code plugin uses the custom path instead ofthe JAVA_HOME
environment variable.
macOS
To globally configure $JAVA_HOME
for all GUI applications, seethis Stackoverflow answer.
If you prefer to manually configure Java home through VS Code, run the followingcommand to copy the Java 8 home path.
Custom artifact repositories (Maven or Ivy resolvers)
Use the 'Custom Repositories' setting for the Metals VS Code extension to tellCoursier to try to download Metalsartifacts from your private artifact repository.
Use .jvmopts
to set sbt options(https://www.scala-sbt.org/1.0/docs/Proxy-Repositories.html) forsbt bloopInstall
which resolves library dependencies. You can also provide acustom sbt script (see 'Custom sbt launcher').
HTTP proxy
Metals uses Coursier to downloadartifacts from Maven Central. To use Metals behind an HTTP proxy, configure thesystem properties -Dhttps.proxyHost=… -Dhttps.proxyPort=…
in one of thefollowing locations:
.jvmopts
file in the workspace directory.JAVA_OPTS
environment variable, make sure to startcode
from your terminalwhen using this option since environment variables don't always propagatecorrectly when opening VS Code as a GUI application outside a terminal.- 'Server Properties' setting for the Metals VS Code extension, which can beconfigured per-workspace or per-user.
Using latest Metals SNAPSHOT
Update the 'Server Version' setting to try out the latest pending Metalsfeatures.
Seehttps://scalameta.org/metals/docs/editors/vscode.html#using-latest-metals-snapshotto find the latest SNAPSHOT version.
Run the 'Reload Window' command after updating the setting for the new versionto take effect.
Files and Directories to include in your Gitignore
The Metals server places logs and other files in the .metals
directory. TheBloop compile server places logs and compilation artifacts in the .bloop
directory. The Bloop plugin that generates Bloop configuration is added in themetals.sbt
file, which is added at project/metals.sbt
as well as furtherproject
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 Ammonitescripts will place compiled scripts into the .ammonite
directory. It'srecommended to exclude these directories and files from version control systemslike git.
Show document symbols
Marshal windsor. Run the 'Explorer: Focus on Outline View' command to open the symbol outline forthe current file in the sidebar.
Run the 'Open Symbol in File' command to search for a symbol in the current filewithout opening the sidebar.
As you type, the symbol outline is also visible at the top of the file.
Go to parent code lenses
Metals has the ability to display code lenses that, when invoked, will go to theparent class that contains the definition of the method or symbol.Unfortunately, it might cause some lag in larger code bases, which is why it isnot enabled currently by default.
To enable the feature you need to modify the settingmetals.superMethodLensesEnabled
to true
.
Even without using the code lenses it's still possible to navigate the methodhierarchy using two commands:
Metals: Go to super method
- immediately goes to the parent of the methodthe cursor is pointing toMetals: Reveal super method hierachy
- displays the full method hierachy andenables to move to any parent, it is best used with the Metals Quick Pickextension.
You can also bind those commands to a shortcut.
Create new project from template
It is possible using Metals to easily setup a new project using the exitinggiter8templates. This is an equivalent to the sbt new
command, which uses the samemechanism. There is a great number of templates already available and it shouldbe easy to find something for yourself. To start the setup you can use theMetals: New Scala project command, which works as following:
Choose the template and then:
- Use the proposed templates.
- Choose 'Discover more' and then choose from the list downloaded from theGiter8 wiki page.
- Input a custom Github repository following the
organization/repo
schema.
Navigate to the parent directory that you want to create your new project in.
Choose the name or accept the default one.
Choose whether to open a new window for the created project or use theexisting one.
The same command will be invoked when clicking the 'New Scala Project' button inthe Metals view.
If you feel like a template should be included in the default displayed ones donot hesitate to create aPRor file an issue.
Running and debugging your code
Metals supports running and debugging tests and main methods via theDebug Adapter Protocol.The protocol is used to communicate between the editor and debugger, which meansthat applications can be run the same as for any other language in the nativelysupported Run
view. When using Metals the debugger itself isBloop, which is also responsible forstarting the actual process.
Users can begin the debugging session in two ways:
via code lenses
For each main or test class Metals shows two code lenses run | debug
ortest | test debug
, which show up above the definition as a kind of virtualtext. Clicking run
or test
will start running the main class or test withoutstopping at any breakpoints, while clicking debug
or test debug
will pauseonce any of them are hit. It's not possible to add any arguments or javaproperties when running using this method.
via a launch.json
configuration
Visual Studio Code uses .vscode/launch.json
to store user definedconfigurations, which can be run using:
- The
Run -> Start Debugging
menu item orworkbench.action.debug.start
shortcut. - The
Run -> Run Without Debugging
menu item orworkbench.action.debug.run
shortcut.
If a user doesn't have anything yet saved, a configuration wizard will pop up toguide them. In the end users should end up with something like this:
You can also add an optional build target name, which is needed in case thereare more than one class with the same name or when launching a class fromoutside the project. Inside 'configurations':
add the key buildTarget
withyour target name, e.g. root
:
The build target name corresponds to your project name. For example in sbt forlazy val interfaces = project
the name of the build target will beinterfaces
for sources and interfaces-test
for tests. To make sure you havethe correct target names please run the command Metals: Run Doctor
.
Call of duty 4 modern warfare razor1911. Multiple configurations can be stored in that file and can be chosen eithermanually in the Run
view or can be picked by invoking a shortcut defined underworkbench.action.debug.selectandstart
.
Visual Studio Code Scala Sbt
On type formatting for multiline string formatting
To properly support adding |
in multiline strings we are using theonTypeFormatting
method. The functionality is enabled by default, but you candisable/enable onTypeFormatting
inside Visual Studio Code settings by checkingEditor: Format On Type
:
Formatting on paste for multiline strings
Whenever text is paste into a multiline string with |
it will be properlyformatted by Metals:
This feature is enabled by default. If you need to disable/enable formatting onpaste in Visual Studio Code you can check the Editor: Format On Paste
setting: Star wars pepakura helmets model.
Worksheets
Worksheets are a great way to explore an api, try out an idea, or code up anexample and quickly see the evaluated expression or result. Behind the scenesworksheets are powered by the great work done inmdoc.
Getting started with Worksheets
Debug Scala In Vs Code
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
. Thisformat is important since this is what tells Metals that it's meant to betreated as a worksheet and not just a Scala script. Where you create the scriptalso matters. If you'd like to use classes and values from your project, youneed to make sure the worksheet is created inside of your src
directory. Youcan still create a worksheet in other places, but you will only have access tothe standard library and your dependencies.
Evaluations
After saving you'll see the result of the expression as a decoration at the endof the line. You may not see the full result for example if it's too long, soyou are also able to hover on the decoration to expand the decoration.
Keep in mind that you don't need to wrap your code in an object
. In worksheetseverything can be evaluated at the top level.
Using dependencies in worksheets
You are able to include an external dependency in your worksheet by including itin one of the following two ways.
::
is the same as %%
in sbt, which will append the current Scala binaryversion to the artifact name.
You can also import scalac
options in a special $scalac
import like below:
Visual Studio Code Scala 2019
Coming from IntelliJ
Visual Studio Code Scala Spark
Install theIntelliJ IDEA Keybindingsextension to use default IntelliJ shortcuts with VS Code.
Visual Studio Code Scala 2020
IntelliJ | VS Code |
---|---|
Go to class | Go to symbol in workspace |
Parameter info | Trigger parameter hints |
Basic completion | Trigger suggest |
Type info | Show hover |
Expand | Fold |
Extend Selection | Expand selection |