Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ This language client would not have been possible without the work of Julian Val
- Printing diagnostics (linting) for each checked file
- Printing code actions for each diagnostic
- Supplying client configuration to the server
- Supplying a workspace folder and initialization options to the server
- Customization of usage message and default argument values via JSON file (path supplied by environment variable)

If you'd like support for other LSP features as well, please open a feature request or a pull request.
Expand Down Expand Up @@ -59,10 +60,12 @@ Any command-line arguments supplied to the startup scripts are processed by `lsp
Only for LT<sub>E</sub>X LS: A flattened JSON object (`{"latex.commands": ...}`) is also allowed, and setting names may be prefixed by a top level named `ltex` (e.g., `{"ltex.latex.commands": ...}` is accepted as well).
- `-h`, `--help`: Show help message and exit.
- `--hide-commands`: Hide commands in lists of code actions for diagnostics, only show quick fixes.
- `--initialization-options=<file>`: Send the JSON value stored in the file `<file>` to the language server as `initializationOptions`. In `.lsp-cli-plus.json`, a relative path is resolved against the directory of that file.
- `--server-command-line=<string>`: Required. Command line to start the language server, starting with the path of its executable. If you want to supply arguments to the language server, separate them with spaces. If the path of the executable or one of the arguments contain spaces, you can escape them by using `\ ` instead. In `.lsp-cli-plus.json`, this option can either be specified as an array of arguments or as a string with space-separated arguments.
- `--server-working-directory=<directory>`: Working directory for `--server-command-line`. If omitted, use the parent directory of `.lsp-cli-plus.json` if given, otherwise use the current working directory.
- `-V`, `--version`: Print version information as JSON to the standard output and exit. The format is a JSON object with `"java"` and `"lsp-cli-plus"` keys and string values. A key may be missing if no information about the corresponding version could be retrieved.
- `--verbose`: Write to standard error output what is being done, along with the language server's standard error output (usually its log).
- `--workspace-folder=<directory>`: Send `<directory>` to the language server as the workspace folder, as `rootUri` and as the only entry of `workspaceFolders`. If omitted, use the current working directory. In `.lsp-cli-plus.json`, a relative path is resolved against the directory of that file.
- `<path> <path> ...`: Required. Paths of files or directories to check. Directories are traversed recursively for supported file types. If `-` is given, standard input will be checked as plain text.

Instead of using the equals sign `=` to separate option names and values, it is also possible to use one or more spaces.
Expand Down
3 changes: 3 additions & 0 deletions changelog.xml
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,9 @@
<action type="fix" issue="ltex-plus/lsp-cli-plus#69" due-to="Parker Wahle (@regulad)">
Stop waiting forever for a language server whose process has ended, for example because it crashed on start. Waiting for the answer to `initialize`, for a file's diagnostics, or for code actions now fails with the server's exit code instead.
</action>
<action type="add" issue="ltex-plus/lsp-cli-plus#67" due-to="Parker Wahle (@regulad)">
Send a workspace folder to the language server with `initialize`, as `rootUri` and as the only entry of `workspaceFolders`: the current working directory, or the directory given with the new option `--workspace-folder`. Add `--initialization-options`, a JSON file whose value is sent as `initializationOptions`. The client now declares the `workspace.workspaceFolders` capability and answers `workspace/workspaceFolders`.
</action>
</release>
<release version="3.0.1" date="2026-11-23">
<action type="fix" issue="ltex-plus/ltex-ls-plus#199" due-to="Andrea Alberti (@alberti42)">
Expand Down
45 changes: 45 additions & 0 deletions src/main/kotlin/org/bsplines/lspcli/LspCliLauncher.kt
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,28 @@ class LspCliLauncher : Callable<Int> {
)
var clientConfigurationFilePath: Path? = null

@CommandLine.Option(
names = ["--workspace-folder"],
paramLabel = "<directory>",
description = [
"Send <directory> to the language server as the workspace folder, as rootUri and as the " +
"only entry of workspaceFolders. If omitted, use the current working directory. In " +
".lsp-cli-plus.json, a relative path is resolved against the directory of that file.",
],
)
var workspaceFolderPath: Path? = null

@CommandLine.Option(
names = ["--initialization-options"],
paramLabel = "<file>",
description = [
"Send the JSON value stored in the file <file> to the language server as " +
"initializationOptions. In .lsp-cli-plus.json, a relative path is resolved against " +
"the directory of that file.",
],
)
var initializationOptionsFilePath: Path? = null

@CommandLine.Option(
names = ["--hide-commands"],
description = [
Expand Down Expand Up @@ -140,6 +162,10 @@ class LspCliLauncher : Callable<Int> {
?.let { Path.of(it) }
}

this.workspaceFolderPath = getPathOption(parseResult, lspCliSettings, "--workspace-folder")
this.initializationOptionsFilePath =
getPathOption(parseResult, lspCliSettings, "--initialization-options")

this.hideCommands =
if (parseResult.hasMatchedOption("--hide-commands")) {
parseResult.matchedOptionValue("--hide-commands", false)
Expand Down Expand Up @@ -178,6 +204,8 @@ class LspCliLauncher : Callable<Int> {
serverCommandLine,
this.serverWorkingDirPath,
this.clientConfigurationFilePath,
this.workspaceFolderPath,
this.initializationOptionsFilePath,
)

try {
Expand Down Expand Up @@ -242,6 +270,23 @@ class LspCliLauncher : Callable<Int> {
}
}

// A path from the command line is taken as it is, so a relative one is resolved against the
// current working directory. A default from .lsp-cli-plus.json is resolved against the
// directory of that file, which is also what --server-working-directory defaults to.
private fun getPathOption(
parseResult: CommandLine.ParseResult,
lspCliSettings: LspCliSettings,
name: String,
): Path? =
if (parseResult.hasMatchedOption(name)) {
parseResult.matchedOptionValue(name, null)
} else {
lspCliSettings
.getValue("defaultValues", name)
?.asString
?.let { lspCliSettings.resolvePath(it) }
}

private fun getLspCliSettingsFilePath(): Path? {
val environmentVariable: String = System.getenv("LSP_CLI_JSON_SETTINGS_PATH") ?: ""
val path: Path? =
Expand Down
52 changes: 50 additions & 2 deletions src/main/kotlin/org/bsplines/lspcli/client/LspCliLanguageClient.kt
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import org.bsplines.lspcli.server.LspCliLanguageServer
import org.bsplines.lspcli.tools.FileIo
import org.bsplines.lspcli.tools.I18n
import org.bsplines.lspcli.tools.Logging
import org.eclipse.lsp4j.ClientCapabilities
import org.eclipse.lsp4j.ConfigurationItem
import org.eclipse.lsp4j.ConfigurationParams
import org.eclipse.lsp4j.Diagnostic
Expand All @@ -23,6 +24,8 @@ import org.eclipse.lsp4j.MessageActionItem
import org.eclipse.lsp4j.MessageParams
import org.eclipse.lsp4j.PublishDiagnosticsParams
import org.eclipse.lsp4j.ShowMessageRequestParams
import org.eclipse.lsp4j.WorkspaceClientCapabilities
import org.eclipse.lsp4j.WorkspaceFolder
import org.eclipse.lsp4j.jsonrpc.Launcher
import org.eclipse.lsp4j.jsonrpc.services.ServiceEndpoints
import org.eclipse.lsp4j.launch.LSPLauncher
Expand All @@ -38,7 +41,16 @@ class LspCliLanguageClient(
serverCommandLine: List<String>,
serverWorkingDirPath: Path? = null,
clientConfigurationFilePath: Path? = null,
workspaceFolderPath: Path? = null,
initializationOptionsFilePath: Path? = null,
) : LanguageClient {
private val initializeParams: InitializeParams =
createInitializeParams(
workspaceFolderPath ?: Path.of(""),
initializationOptionsFilePath?.let {
JsonParser.parseString(FileIo.readFileWithException(it))
},
)
val languageServerProcess: Process =
startLanguageServerProcess(serverCommandLine, serverWorkingDirPath)
val languageServer: LanguageServer = initializeLanguageServer()
Expand Down Expand Up @@ -85,7 +97,41 @@ class LspCliLanguageClient(
return CompletableFuture.completedFuture(result)
}

override fun workspaceFolders(): CompletableFuture<List<WorkspaceFolder>> =
CompletableFuture.completedFuture(this.initializeParams.workspaceFolders)

companion object {
/**
* Create the parameters of the `initialize` request. The workspace folder is sent as
* `rootUri` and as the only entry of `workspaceFolders`, as an editor sends the folder it
* opened, and the client declares the `workspace.workspaceFolders` capability that the
* latter requires. A relative workspace folder is resolved against the current working
* directory.
*/
fun createInitializeParams(
workspaceFolderPath: Path,
initializationOptions: JsonElement? = null,
): InitializeParams {
val absoluteWorkspaceFolderPath: Path = workspaceFolderPath.toAbsolutePath().normalize()
val workspaceFolderUri: String = absoluteWorkspaceFolderPath.toUri().toString()
// A root directory such as C:\ or / has no file name; use the whole path then.
val workspaceFolderName: String =
(absoluteWorkspaceFolderPath.fileName ?: absoluteWorkspaceFolderPath).toString()

val workspaceClientCapabilities = WorkspaceClientCapabilities()
workspaceClientCapabilities.workspaceFolders = true
val clientCapabilities = ClientCapabilities()
clientCapabilities.workspace = workspaceClientCapabilities

val initializeParams = InitializeParams()
initializeParams.capabilities = clientCapabilities
initializeParams.rootUri = workspaceFolderUri
initializeParams.workspaceFolders =
listOf(WorkspaceFolder(workspaceFolderUri, workspaceFolderName))
initializeParams.initializationOptions = initializationOptions
return initializeParams
}

private fun startLanguageServerProcess(
serverCommandLine: List<String>,
serverWorkingDirPath: Path? = null,
Expand Down Expand Up @@ -146,8 +192,10 @@ class LspCliLanguageClient(
launcher.startListening()
executorService.shutdown()

Logging.logger.info(I18n.format("initializingLanguageServer"))
server.initialize(InitializeParams()).get()
Logging.logger.info(
I18n.format("initializingLanguageServer", this.initializeParams.rootUri),
)
server.initialize(this.initializeParams).get()
return server
}
}
13 changes: 13 additions & 0 deletions src/main/kotlin/org/bsplines/lspcli/tools/LspCliSettings.kt
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,19 @@ class LspCliSettings(
return jsonElement
}

/**
* Resolve a path given in the settings file: a relative path is resolved against the
* directory of the settings file, as if it were the working directory. Without a settings
* file, the path is returned as it is.
*/
fun resolvePath(pathString: String): Path {
val path: Path = Path.of(pathString)
return this.settingsFilePath
?.toAbsolutePath()
?.parent
?.resolve(path) ?: path
}

fun getValueAsListOfString(vararg keys: String): List<String>? {
val jsonElement: JsonElement = getValue(*keys) ?: return null
val list = ArrayList<String>()
Expand Down
2 changes: 1 addition & 1 deletion src/main/resources/LspCliMessagesBundle.properties
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ checkingFile = Checking '{0}'...
couldNotReadFile = Could not read file '{0}'
couldNotWriteFile = Could not write file '{0}'
followingExceptionOccurred = The following exception occurred:
initializingLanguageServer = Initializing language server...
initializingLanguageServer = Initializing language server with workspace folder '{0}'...
requiredArgumentNotSpecified = Required argument '{0}' not specified
serverExitedWithExitCode = The language server exited with exit code {0}
settingLocale = Setting locale to '{0}'
Expand Down
89 changes: 89 additions & 0 deletions src/test/kotlin/org/bsplines/lspcli/LspCliLauncherTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,15 @@
package org.bsplines.lspcli

import org.bsplines.lspcli.testtools.TestTools
import org.bsplines.lspcli.tools.LspCliSettings
import org.junit.jupiter.api.io.TempDir
import picocli.CommandLine
import java.nio.file.Files
import java.nio.file.Path
import kotlin.test.BeforeTest
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertNull

class LspCliLauncherTest {
@BeforeTest
Expand Down Expand Up @@ -79,6 +85,76 @@ class LspCliLauncherTest {
assertEquals(0, returncode)
}

@Test
fun testWorkspaceFolderAndInitializationOptions() {
val testfile = TestTools.createTextFile("This is a test.", "markdown-2.md")
val initializationOptions =
TestTools.createTextFile("""{"locale": "en"}""", "initialization-options.json")
val returncode =
LspCliLauncher.run(
arrayOf(
"--server-command-line",
TestTools.getExecutable(),
"--workspace-folder",
TestTools.getCurrentDirectory(),
"--initialization-options",
initializationOptions,
"--verbose",
testfile,
),
)
assertEquals(0, returncode)
}

@Test
fun testUnknownInitializationOptionsFile() {
val testfile = TestTools.createTextFile("This is a test.", "markdown-3.md")
val returncode =
LspCliLauncher.run(
arrayOf(
"--server-command-line",
TestTools.getExecutable(),
"--initialization-options",
"unknownFile.json",
testfile,
),
)
assertEquals(1, returncode)
}

@Test
fun testPathOptionDefaults(
@TempDir tempDirPath: Path,
) {
val settingsFilePath: Path =
Files.writeString(
tempDirPath.resolve(".lsp-cli-plus.json"),
"""{"defaultValues": {"--workspace-folder": "project", """ +
""""--initialization-options": "options.json"}}""",
)
val lspCliSettings = LspCliSettings(settingsFilePath)

// Defaults from .lsp-cli-plus.json are resolved against its directory.
var launcher = createLauncher(lspCliSettings)
assertEquals(tempDirPath.resolve("project"), launcher.workspaceFolderPath)
assertEquals(tempDirPath.resolve("options.json"), launcher.initializationOptionsFilePath)

// Command-line values override them and are taken as they are.
launcher =
createLauncher(
lspCliSettings,
"--workspace-folder=other",
"--initialization-options=other.json",
)
assertEquals(Path.of("other"), launcher.workspaceFolderPath)
assertEquals(Path.of("other.json"), launcher.initializationOptionsFilePath)

// Without either, the client uses the current working directory and sends no options.
launcher = createLauncher(LspCliSettings())
assertNull(launcher.workspaceFolderPath)
assertNull(launcher.initializationOptionsFilePath)
}

@Test
fun testCheckFilesInDirectory() {
val subdir = "test-dir"
Expand Down Expand Up @@ -159,4 +235,17 @@ class LspCliLauncherTest {
)
assertEquals(0, returncode)
}

private fun createLauncher(
lspCliSettings: LspCliSettings,
vararg arguments: String,
): LspCliLauncher {
val parseResult: CommandLine.ParseResult =
CommandLine(LspCliLauncher()).parseArgs(
"--server-command-line=server",
*arguments,
"file.md",
)
return LspCliLauncher(parseResult, lspCliSettings)
}
}
Loading
Loading