当前位置:   article > 正文

LSP 语言服务协议_lsp协议

lsp协议

介绍

LSP 是Language Server Protocol 的缩写,它定义了一种标准化的协议,用于编辑器和语言工具之间的通信。这个协议定义了编辑器可以向语言工具查询的功能,同时还定义了语言工具可以向编辑器发送的信息。开发人员可以在多个编辑器中使用同一种语言工具,无需了解编辑器的具体实现细节。

LSP 可以提供多种功能,例如语法分析、代码高亮、错误检查、代码重构以及文档导航等。通过使用 LSP,我们可以在不同的编辑器和语言工具之间共享这些功能,让开发变得更加高效和一致。
LSP效果

常见协议

  • LSP: Language Server Protocol,由Microsoft推出的一个开放协议。
  • JSON-RPC:JSON Remote Procedure Call,一种轻量级的远程过程调用协议。
  • XML-RPC:XML Remote Procedure Call,使用XML格式进行数据交换的远程过程调用协议。

代码演示

  1. 创建一个新文件夹,并在Visual Studio Code中打开它。

  2. 添加一个名为 package.json 的新文件,并填写以下细节:
    {
    “name”: “lsp-demo”,
    “version”: “0.0.1”,
    “dependencies”: {
    “vscode”: “^1.32.0”
    }
    }
    这个文件告诉 npmNode.js 包管理器)你的项目依赖于 VSCode 扩展 API

  3. 创建一个名为 src 的新文件夹,并添加一个名为 server.ts 的文件。

  4. server.ts 中,添加下面的代码:

import * as vscode from 'vscode';
import { LanguageClient, LanguageClientOptions, ServerOptions, TransportKind } from 'vscode-languageclient';
let client: LanguageClient;
export function activate(context: vscode.ExtensionContext) {
 const serverOptions: ServerOptions = {
     run: { command: 'node', args: ['./src/server.js'], transport: TransportKind.stdio },
     debug: { command: 'node', args: ['--inspect-brk=0', './src/server.js'], transport: TransportKind.stdio }
 };
 const clientOptions: LanguageClientOptions = {
     documentSelector: ['javascript'],
     synchronize: {
         configurationSection: 'lsp-sample'
     }
 };
 client = new LanguageClient(
     'lsp-sample',
     'LSP Sample',
     serverOptions,
     clientOptions
 );
 client.start();
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22

这段代码为名称为 lsp-sample 的新 LanguageClient 创建对象,并启动它。

  1. src 文件夹中创建另一个名为 server.js 的文件,添加以下代码:
const { createConnection } = require('vscode-languageserver/node');
const { TextDocuments } = require('vscode-languageserver/node');
const { TextDocument } = require('vscode-languageserver-textdocument');
const connection = createConnection();
const documents = new TextDocuments(TextDocument);
connection.onInitialize(() => {
 return {
     capabilities: {
         textDocumentSync: documents.syncKind,
         completionProvider: {
             resolveProvider: true
         }
     }
 };
});
connection.onInitialized(() => {
 connection.client.register(DidChangeConfigurationNotification.type, undefined);
});
documents.onDidChangeContent((change) => {
 connection.console.log('Content changed!');
});
connection.onCompletion((textDocumentPosition) => {
 return [
     {
         label: 'TypeScript',
         kind: CompletionItemKind.Text,
         data: 1
     },
     {
         label: 'JavaScript',
         kind: CompletionItemKind.Text,
         data: 2
     }
 ];
});
documents.listen(connection);
connection.listen();
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37

这段代码创建了一个新的语言服务器,支持文本同步、配置更改和完成提供程序。

  1. 最后,在 VSCode 中启动客户端运行演示。打开一个扩展名为 .js 的新文件并开始输入。你应该会在编辑器中看到自动完成建议弹出。

应用范例

现在,越来越多的工具开始使用LSP,包括:

  • Visual Studio Code:JavaScript 语言服务器。
  • Eclipse:Java 语言服务器。
  • Atom:TypeScript 语言服务器。
  • Sublime Text:Python 语言服务器。

以下是应用了 LSP 的开源代码,可作为实现参考:

LanguageMaintainerRepositoryImplementation Language
1C EnterpriseContributorsBSL Language ServerJava
ActionScript 2.0Adam VernonAS2 Language SupportTypeScript
Ada/SPARKAdaCoreada_language_serverAda
AMLAMLAML Language ServerScalaJS
AnsibleAnsibleAnsible Language ServerTypeScript
AngularAngular team & ivanwonderAngular Language ServerTypeScript
AntlrKen DominoAntlrvsixC#
API ElementsVincenzo Chianese(@XVincentX)vscode-apielementsTypeScript
Apache CamelContributorsApache Camel Language ServerJava
ApexSalesforceVS Code Apex extensionTypeScript
IBM High Level AssemblerBroadcomHLASM Language SupportC++
IBM High Level AssemblerIBMIBM Z Open Editor VS Code extensionJava
ASN.1Eclipse TitanTitan Language ServerJava
AsyncAPIAMLAML Language ServerScalaJS
AWKStanislav ChernovAWK Language ServerTypeScript
BallerinaBallerina.ioBallerina Language ServerJava
BashMads HartmannBash Language ServerTypeScript
BicepMSBicepC#
BrightScript/BrighterScriptRokuCommunitybrighterscriptTypeScript
C#OmniSharpomnisharp-roslynC#
C#Saulius Menkevičiuscsharp-lsF#
C++MSVS Code C++ extensionC++
C++/clangLLVM ProjectclangdC++
C/C++/Objective-CJacob Dufault, MaskRay, topisanicqueryC++
C/C++/Objective-CMaskRaycclsC++
CSS/LESS/SASSMSvscode-css-languageserverTypeScript
CeylonJohn Vasileffvscode-ceylonCeylon
ClarityHiroclarity-lspTypeScript
ClojureCase Nelsonclojure-lspClojure
CMakeregen100cmake-language-serverPython
Coqejgallegocoq-lspOCaml
IBM Enterprise COBOL for z/OSBroadcomCOBOL Language SupportJava
IBM Enterprise COBOL for z/OSIBMIBM Z Open Editor VS Code extensionJava
CodeQLGitHubcodeqlJava
CoffeeScriptphil294CoffeeSenseTypeScript
CWLRabixBentenPython
CrystalElbaz JulienCrystallineCrystal
CrystalRyan L. BellScryCrystal
Cucumber/GherkinCucumber core teamCucumber Language ServerTypeScript
DJan Jurzitzaserve-dD
DLaurent TréguierD Language ServerD
DartDart TeamDart SDKDart
Data PackSPGodingData-pack Language ServerTypeScript
DelphiEmbarcaderoProprietary (DelphiLSP)Delphi and C
DenizenScriptDenizenScript TeamDenizenVSCodeC#
Deno (TypeScript/JavaScript)Deno Landdeno lspRust
DockerfilesRemy Suendockerfile-language-serverTypeScript
DreamMakerSpaceManiacDreamMaker Language ServerRust
ErlangOTP, Vlad DumitrescusourcerErlang
ErlangRoberto Aloi and Contributorserlang_lsErlang
ElixirElixir LSPelixir-lsElixir
ElmKolja LampeelmLSTypescript
EmberEmber communityember language serverTypeScript
F#@georgewfraserF# Language ServerF#
F#@Krzysztof-Cieslak & ContributorsFsAutoCompleteF#
FortranChris Hansenfortran-language-serverPython
FortranGiannis NikiteasfortlsPython
FuzionTokiwa Software GmbHFuzion Language ServerJava, Fuzion
GLSLSven-Hendrik Haase (@svenstaro)glsl-language-serverC++
GLSL for Minecraft@strum355mcshader-lspRust
GaugeGaugeGauge Language ServerGo
GDScriptGodotEngineGodotC++
GleamGleamgleamRust
GluonGluonGluon Language ServerRust
GoGo TeamgoplsGo
GoSourcegraphsourcegraph-goGo
GraphQLGraphQL FoundationOfficial GraphQL Language ServerTypeScript
GraphQLMayank Agarwal (@Mayank1791989)GQL Language ServerJavaScript
Graphviz/DOTNiklas Mollenhauerdot-language-serverTypeScript
GrainGrain TeamgrainReasonML
GroovyPalantirgroovy-language-serverJava
GroovyProminic.NETGroovy Language ServerJava
GroovyVsCode Groovy LintVsCode Groovy Lint Language ServerTypeScript
HTMLMSvscode-html-languageserverTypeScript
HaskellAlan ZimmermanHaskell Language Server (HLS)Haskell
HaxeHaxe FoundationHaxe Language ServerHaxe
HLSLTim JonesHLSL ToolsC#
IsabelleMakarius WenzelsourcesScala
Idris2Idris communityidris2-lspIdris2
Java (Eclipse)Eclipse, RedHatEclipse JDT LSJava
Java@georgewfraserJava Compiler (javac) API-based Java supportJava
JavaScriptquick-lint-jsquick-lint-jsC++
JavaScript FlowFacebook, Inc.flowOCaml, JavaScript
JavaScript Flowflowtypeflow-language-server(deprecated)JavaScript, Flow
JavaScript-TypescriptSourcegraphjavascript-typescriptTypeScript
JSONMSvscode-json-languageserverTypeScript
JsonnetGrafana Labsjsonnet-language-serverGo
JuliaContributorsJulia language serverJulia
Kerboscript (kOS)John Chabotkos-language-serverTypescript
KerMLSensmetrySysML2 ToolsTypescript
Kotlin@fwcdkotlin-language-serverKotlin
Language Server RobotTypeCobolTeamTypeCobol Language Server RobotC#
LanguageToolAdam VosslanguagetoolJava
LanguageToolJulian Valentinltex-lsKotlin
LaTeXEric Förstertexlab
LuaKyle McLamblua-lspLua
Lua最萌小汐lua-language-serverLua
LuaTencentLuaHelperGo
LiquidShopifytheme-checkRuby
IBM LALR Parser Generator languagekuafuwangLPG-language-serverC++
MarkdownArtem PianykhMarksmanF#
MarkdownMSvscode-markdown-languageserverTypeScript
Motorola 68000 AssemblyGraham Batesm68k-lspTypeScript
MSBuildAdam Friedmanmsbuild-project-tools-vscodeTypeScript
NimPeter Munch-EllingsennimlspNim
OCaml/Reasonfreebroccoloocaml-language-serverTypeScript
OCaml/ReasonOCaml LabsocamllspOCaml
OpenAPIAMLAML Language ServerScalaJS
openVALIDATIONopenVALIDATIONov-language-serverTypeScript
PapyrusJoel Daypapyrus-langC#
PerlGRICHTERPerl::LanguageServerPerl
PerlMarc ReisnerPLSPerl
PerlBrian ScannellPerl NavigatorPerl
PestPest MaintainersPest IDE ToolsRust
Crane PHPHvyIndustriesVS Code ExtensionTypeScript
PHPBen MewburnintelephenseTypeScript
PHPFelix Beckerphp-language-serverPHP
PHPTom GerritsSerenataPHP
PHPTyson AndrePhanPHP
PHPUnitRecca0120phpunit-language-serverTypeScript
IBM Enterprise PL/I for z/OSIBMIBM Z Open Editor VS Code extensionJava
PolymerPolymer Teampolymer-editor-serviceTypeScript
PowerPC AssemblyNoah FieldsPowerPC SupportTypeScript
PowerShellMSPowerShell Editor ServicesC#
PromQLTobias Guggenmospromql-langserverGo
PureScriptNicholas Wolversonpurescript-language-serverPureScript
PuppetLingua Pupulipuppet language serverRuby
PythonFabio ZadroznyPyDev on VSCodeJava, Python
PythonPalantir Technologiespython-language-server (unmaintained, use python-lsp-server instead)Python
PythonSpyder IDE team and the communitypython-lsp-serverPython
PythonMSpython-language-serverC#
PythonSamuel Roecajedi-language-serverPython
PonyMahan BakhshiPonyLSPony
Q#MSQ# Language ServerC#
QMLQtqmllsC++
RREditorSupportR language serverR
RacketJay McCarthyracket-langserverRacket
RakuBrian ScannellRaku NavigatorTypeScript
RAMLRAML Workgroupraml-language-server Work in Progress
RAMLAMLAML Language ServerScalaJS
ReasonMLJared Forsythreason-language-serverOCaml
RedbitbeginredlangserverRed
RELStefan Schlichthärlerel-lsC++
ReScriptrescript-langrescript-vscodeTypeScript
IBM TSO/E REXXIBMIBM Z Open Editor VS Code extensionJava
Robot FrameworkDaniel BiehlRobotCodePython
Robot FrameworkTomi TurtiainenVSCode RF language serverTypeScript
Robot FrameworkRobocorprobotframework-lspPython
RubyFred SnydersolargraphRuby
RubyFumiaki MATSUSHIMAlanguage_server-rubyRuby
RubyStripesorbetC++
RubyRafał ŁasochaorbacleRuby
RubyKurt Werleruby_language_serverRuby
RubyShopifyRuby LSPRuby
RustJonathan TurnerRust Language ServerRust
RustAleksey KladovRust AnalyzerRust
ScalaIulian Dragosdragos-vscode-scalaScala
ScalaScalametaMetalsScala
Schemeufo5260987423scheme-langserverChez Scheme
SlintSlintslint-lspRust
Smalltalk/PharoBenoît VerhaeghePharo Language ServerPharo
SnykSnykSnyk Language ServerSnyk SCA / SAST / IaC findings
SPARQLStardog UnionSPARQL Language ServerTypeScript
SQLToshikazu OhashisqlsGo
Standard MLazdavisMilletRust
StylableWix.comstylable/language-serviceTypeScript
SvelteContributorssvelte-language-serverTypeScript
SwiftAppleSourceKit-LSPSwift
SysML v2SensmetrySysML2 ToolsTypescript
SyslANZ BankSysl LSPGo
SystemVerilogdalancesvlsRust
SystemVerilogSigasiProprietary (Sigasi)Java
T-SQLMSVS Code SQL extensionTypeScript, Binary
Tads3Tomas Öbergtads3toolsTads3
TerraformJulio Tain Sueirasterraform-lspGo
TerraformHashiCorpterraform-lsGo
Tibbo BasicTibbotibbo-basicTibbo Basic
Trino SQLRocket BoosterstrinolsTypeScript
TTCN-3NokianttGo
TTCN-3Eclipse TitanTitan Language ServerJava
TurtleStardog UnionTurtle Language ServerTypeScript
TypeCobolTypeCobolTypeCobol language serverC#
TypeScriptTypeFoxtypescript-language-serverTypeScript
ValaBen Iofel, Princeton Ferrovala-language-serverVala
VDM-SL, VDM++, VDM-RTNick BattleVDMJ-LSPJava
VeryldalanceVeryl Language ServerRust
VHDLOlof Kraighervhdl_lsRust
VHDLSigasiProprietary (Sigasi)Java
VHDLViDE-SoftwareProprietary (VHDL for Professionals)C#
Vimliamccovim-language-serverTypescript
VisualforceSalesforceVS Code Visualforce extension
VuePine Wu & @HerringtonDarkholmevuejs/veturTypeScript
WebAssemblyDarin Morrisonwasm-language-serverRust
WebGPU Shading LanguageWGSL-Analyzer Teamwgsl-analyzerRust
Wolfram Language (Mathematica)kenkangxgwelsp-wlWolfram Language
Wolfram LanguageWolfram ResearchLSPServerWolfram Language
WXMLQiming Zhaowxml-languageserverTypeScript
XMLIBMXML Language ServerJava
XMLRed Hat Developers and Angelo ZERRXML Language Server (LemMinX)Java
MiniYAMLPavel PenevORAIDEC#
YAML (with JSON schemas)Adam Vossvscode-yaml-languageserviceTypeScript
YAMLRed Hat Developersyaml-language-serverTypeScript
YARAAvastYARA Language ServerPython
YANGYang toolsyang-lspXTend
ZigzigtoolszlsZig
*mattnefm-langserverGo
*iamccodiagnostic-languageserverTypeScript
*daquexiantaglsPython
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/菜鸟追梦旅行/article/detail/623169
推荐阅读
相关标签
  

闽ICP备14008679号