Code Monkey home page Code Monkey logo

metals-sublime's Introduction

LSP-Metals

lsp-metals

LSP-metals is the recommended Sublime LSP extension for Metals, the Scala language server. LSP-metals offers automated Metals installation, easy configuration, Metals-specific commands and many other small features.

Discord

Table of Contents

Requirements

  • Sublime Text (build 4000 or later)
  • LSP package: Command Palette (Cmd + Shift + P) > Install package > LSP
  • 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 8 or 11 installation.

Installing LSP-metals

Once you have LSP installed, you can then install Metals via

  • Automatically via package control: Command Palette (Cmd + Shift + P) > Install package > LSP-metals

  • manually: run git clone https://github.com/scalameta/metals-sublime.git LSP-metals in your sublime packages directory

Importing a build

The first time you open Metals in a new workspace it prompts you to import the build. Click "Import build" to start the installation step.

Build Import

  • "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.
  • Run lsp toggle server panel in the command palette to watch the build import progress. You can optionally add a key binding for this command.
  • 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.

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.

Configuration

You can edit the package settings by running LSP-metals Settings in the sublime palette or accessing Preferences > Package Settings > LSP > Servers > LSP-metals.

config

Java version

The LSP-metals extension by default uses the JAVA_HOME environment variable (via environ). Otherwise, it uses which to locate the java executable.

If no JAVA_HOME is detected you can then open Settings by following the instructions in the displayed error message.

No Java Home

Server version

In order to install the latest snapshot of metals you can explicitly set the snapshot version for server_version. Alternatively, you can also just default to the latest snapshot by setting server_version to latest-snapshot. The same can be done for the latest stable release by setting the value to latest-stable, If no version is set, it defaults to the latest stable release as well.

The new release check in done each time sublime text is started.

Workplace Diagnostic

To see all compilation errors and warnings in the workspace, run the following command Toggle Diagnostics Panel Or use the default mapping super+shift+M / ctr+alt+M

To cycle through the diagnostic use the default mapping Next F4 / Previous shift+F4

diagnostic

Run doctor

To troubleshoot problems with your build workspace, run Doctor run in the command pallet. This command opens a browser window.

Run Doctor Command

All Available Commands

The following commands can be invoked simply via the sublime command palette.

Show document symbols

Run the Document Symbols command to show a symbol outline for the current file. You can also set a key binding for the lsp_document_symbols command

Document Symbols

Formatting on save

If you'd like to have LSP-metals format your file on document save then make sure to add this setting to your Sublime settings, Syntax-specific settings and/or in Project files.

"lsp_format_on_save": true,
...

Organize imports on save

If you'd like to have LSP-metals organize your imports on document save then make sure to add this to your LSP settings.

"lsp_code_actions_on_save":{
  "source.organizeImports": true
},
...

Decoration protocol

This plugin implements the Decoration protocol (only for ST4) which allows showing worksheet evaluations (instead of comments), as well as inferred types and other info as Sublime Phantom.

To enable this feature enable the following LSP-metals settings:

"settings": {
  "metals": {
    ...
    "showInferredType": true,
    "showImplicitArguments": true,
    "showImplicitConversionsAndClasses": true
  }
}

Status Bar

Information about your workspace build like compilation errors count, build status, etc. are displayed by Metals in the sublime status bar.

Status bar info

Troubleshooting

If you have any questions or issues with LSP-metals, please submit an issue in this repository if it is related to the extension.

If the issue is general to Metals, please submit it in the Metals issue repo.

If you have any feature requests, we also have a feature request issue repo.

metals-sublime's People

Contributors

ayoub-benali avatar ckipp01 avatar jvican avatar masseguillaume avatar ninth-dev avatar prassee avatar predragnikolic avatar quot avatar rchl avatar rwols avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

metals-sublime's Issues

Is it possible to add the parent dir as the `rootUri` when opening a standalone Scala file.

As a follow-up to scalameta/metals#2391, the NPE should be avoided now and a message shown if a user just opens up a Scala file. However, without having any rootUri set, a lot of the functionality that is possible won't happen. I'm curios how much of the LSP api from the LSP package is exposed and if it's possible to detect if no root is there, just set the parent as the root. I know Neovim makes this super easy, as you can see here. Would this at all be possible in the Sublime extension until we do a proper refactoring on the Metals side to handle this case?

Fail to send `didFocusTextDocument` in Sublime 4

I'm using the latest Metals Sublime release with the latest Sublime Text release (Build 4116) and I'm getting the following errors in the Metals server log panel:

metals: 2021.10.01 14:18:10 WARN  Unexpected notification params received for didFocusTextDocument: {uri=file:///Users/jvicentecantero/Code/???}

This suggests that we're not sending the didFocusTextDocument well to the Metals server and it's potentially causing misbehaviors on the server. Looks like we might need to change the ST4 implementation here

class LspMetalsFocusViewCommand(LspTextCommand):
session_name = "metals"
def run(self, edit: sublime.Edit, view_id: int, event: Optional[Dict[str, Any]] = None) -> None:
view = sublime.View(view_id)
if not view.is_valid():
return
fname = view.file_name()
if not fname:
return
sublime.set_timeout_async(functools.partial(self.run_async, fname))
def run_async(self, fname: str) -> None:
session = self.session_by_name()
if not session:
return
uri = session.config.map_client_path_to_server_uri(fname)
session.send_notification(Notification("metals/didFocusTextDocument", {"uri": uri}))
class ActiveViewListener(sublime_plugin.EventListener):
def on_activated(self, view: sublime.View) -> None:
if view.file_name():
view.run_command("lsp_metals_focus_view", {"view_id": view.id()})

@ayoub-benali You're the last person that made the change, do you know what might be going on? Also, I've experienced cases where Metals is not publishing compilation errors for files that are not open. Every time it's happened has been annoying and unpredictable. I'm not sure if this is connected to that issue, but you might want to know about it. Let me know if you have any ideas here because I'd be willing to invest some time fixing the issue with missing diagnostics.

Metals Doctor opens regularly

I just installed and configured Metals in Sublime Text yesterday and I've found that Metals Doctor opens far more frequently than I'd expect. I'm not exactly sure what triggers it to open, but it often seems to happen after switching between git branches or after opening a .scala file in a different SBT sub-project.

Is there anything I can do to prevent this from opening except when I explicitly choose to run it from the command palette?

different scala version between targets

Hello.
I am using ubuntu 20.04 LTS x86_64 and here are other specs:

Scala code runner version 2.13.6 -- Copyright 2002-2021, LAMP/EPFL and Lightbend, Inc.
java 11.0.10 2021-01-19 LTS (oracle Java)
Java(TM) SE Runtime Environment 18.9 (build 11.0.10+8-LTS-162)
Java HotSpot(TM) 64-Bit Server VM 18.9 (build 11.0.10+8-LTS-162, mixed mode)
sbt --version
sbt version in this project: 1.5.4
sbt script version: 1.5.4

and sublime text with sublimelsp/LSP and scalameta/metals-sublime

the problem is this :
while building by shift+f10 is get this message you are using scala 2.12.14 which is not yet supported in this version of metals please downgrade to scala version 2.12.12 for the moment until the new metal release.
as you can see in the "http://127.0.0.1:5031/doctor" print out below I am using 2.13.
I don't know how to fix this issue.
thanks for you help.

Implement all members inserts literal text

scalameta/metals#1031 was recently merged which adds an "implement all members" completion similar to how the exhaustive match is done. However, in Sublime it seems to not show up in the same order in the completions as the other editors. It seems to be triggered by e for some reason. Also, when you select the completion, it puts in the literal text as seen in the gif below.

mygif

Version of Metals: Latest Snapshot - 0.7.6+224-b3ea857f-SNAPSHOT

metals-sublime plugin does not show worksheet output

the plugin lsp-metals v0.17.1 does not display worksheet results inline. However the compilation & auto-completion features works.
The plugin runs in the following error each time worksheet is evaluated.

Error handling notification
Traceback (most recent call last):
  File "/data/sysconfigs/sublime-text/Installed Packages/LSP.sublime-package/plugin/core/sessions.py", line 1987, in on_payload
    handler(result)
  File "/data/sysconfigs/sublime-text/Packages/LSP-metals/core/metals.py", line 77, in m_metals_publishDecorations
    handle_decorations(session, decorationsParams)
  File "/data/sysconfigs/sublime-text/Packages/LSP-metals/core/decorations.py", line 62, in handle_decorations
    phantom_set.update(phantoms)
  File "/data/cellar/sublime_text/Lib/python33/sublime.py", line 1897, in update
    new_phantoms = {p.to_tuple(): p for p in new_phantoms}
  File "/data/cellar/sublime_text/Lib/python33/sublime.py", line 1897, in <dictcomp>
    new_phantoms = {p.to_tuple(): p for p in new_phantoms}
  File "/data/sysconfigs/sublime-text/Packages/LSP-metals/core/decorations.py", line 107, in <lambda>
    return map(lambda o: decoration_to_phantom(o, view), options)
  File "/data/sysconfigs/sublime-text/Packages/LSP-metals/core/decorations.py", line 91, in decoration_to_phantom
    point = view.text_point(option['start'].row, option['start'].col)
KeyError: 'start'

Make the plugin enabled by default

enabled=False,

Why is it not enabled by default?

I think I lot of people would expect something to be enabled, rather the disabled, when installing something? :)

If it is enabled, that one step less that a user need to do :)

3.Enable "metals-sublime" in your scala project

Import the right symbol upon completion selection

Hey folks ๐Ÿ‘‹ I'd like to report a bug I run into often when using this plugin.

  1. Start writing some characters. The plugins shows completions.
  2. Select a candidate entry of the completion list and click enter.
  3. Go to the beginning of the file and find that a symbol different from the one you selected is imported.

Here's a quick reproduction video.

Screen.Recording.2021-01-23.at.10.59.25.AM.mov

The weird thing is that sometimes the right symbol is imported and sometimes it isn't. However, this happens often enough in my computer to be an annoying behavior that gets in the way of my coding flow.

I haven't had a look at the implementation, but my guess would be that there's some reordering of the results either on the client or server side and the index sent by the Sublime Text client doesn't match the one in the server.

Metals Server v1.0 and beyond

I'm using LSP v1.27.0 and LSP-metals v0.17.6 in Sublime Text build 4169 on Mac OS Sonoma 14.1.1.

I'm seeing the following message: "You are using Scala version 2.13.12, which is not yet supported in this version of Metals. ..." Per https://scalameta.org/metals/blog/2023/07/19/silver, there is a line of Metals versions beyond 0.11.12 - there are versions 1.0 through 1.2. Are those versions not supported through Sublime? Is there a timeframe / ETA for supporting them?

Thank you

Handle Metals installation

@olafurpg Following your proposal here

Shall we assume that coursier is installed and available in the classpath ? like in the vscode plugin?
Or should we embed some kind of coursier luncher like here https://github.com/tomv564/LSP-dotty

How are the server updates handled in the vscode plugin ? do you have to change the version by hand every time there is a server release ?

Just want to understand and document what is the expected workflow

cc @gabro

Sublime Text editor crashes when evaluating large verbose output on worksheet

Sublime text editor crashes when evaluating large output for e.g
the below code snippet when evaluated would crash the editor

import scala.collection.mutable.ListBuffer
import java.util.{ArrayList => jal}

val lb = ListBuffer[String]()
lb += "a"
lb += "b"

val jl = new jal[String]()
jl.add("a")
jl.add("b")

val x = 90
x + 1

val b = (1 to 5000).toList.foreach(x => (1 to x).foreach(println))

A diff for when LSP might remove the "syntaxes" key

I have a pull request for removing the "syntaxes" key over at the LSP package.

This helper package breaks when that PR is merged into master.
Please don't apply this patch until sublimelsp/LSP#931 is in the master branch (that could take a while, since ST4 isn't even out of alpha yet).

diff --git a/plugin.py b/plugin.py
index 3e68a56..31668e5 100644
--- a/plugin.py
+++ b/plugin.py
@@ -48,13 +48,7 @@ class LspMetalsPlugin(LanguageHandler):
             name=server_name,
             binary_args=launch_command,
             tcp_port=None,
-            languages=[
-                LanguageConfig(
-                    "scala",
-                    ["source.scala"],
-                    ["Packages/Scala/Scala.sublime-syntax"]
-                )
-            ],
+            languages=[LanguageConfig("scala")],
             enabled=True,
             init_options=dict(),
             settings=dict(),

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.