How to use vscode-languageserver - 10 common examples

To help you get started, we’ve selected a few vscode-languageserver examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github elm-tooling / elm-language-server / src / index.ts View on Github external
import { ILanguageServer } from "./server";

// Show version for `-v` or `--version` arguments
if (process.argv[2] === "-v" || process.argv[2] === "--version") {
  // require is used to avoid loading package if not necessary (~30ms time difference)
  // tslint:disable-next-line no-var-requires
  process.stdout.write(`${require("pjson").version}\n`);
  process.exit(0);
}

// default argument `--stdio`
if (process.argv.length === 2) {
  process.argv.push("--stdio");
}

const connection: IConnection = createConnection(ProposedFeatures.all);
let server: ILanguageServer;

connection.onInitialize(
  async (params: InitializeParams): Promise => {
    await Parser.init();
    const absolute = Path.join(__dirname, "tree-sitter-elm.wasm");
    const pathToWasm = Path.relative(process.cwd(), absolute);
    connection.console.info(
      `Loading Elm tree-sitter syntax from ${pathToWasm}`,
    );
    const language = await Parser.Language.load(pathToWasm);
    const parser = new Parser();
    parser.setLanguage(language);

    const { Server } = await import("./server");
    server = new Server(connection, params, parser);
github iamcco / vim-language-server / src / handles / signatureHelp.ts View on Github external
(params: TextDocumentPositionParams): SignatureHelp | undefined => {
    const { textDocument, position } = params;
    const doc = documents.get(textDocument.uri);
    if (!doc) {
      return;
    }

    const currentLine = doc.getText(
      Range.create(
        Position.create(position.line, 0),
        Position.create(position.line + 1, 0),
      ),
    );

    // comment line
    if (commentPattern.test(currentLine)) {
      return;
    }

    const preSegment = currentLine.slice(0, position.character);

    const m = preSegment.match(/([\w#&:]+)[ \t]*\(([^()]*|\([^)]*\))*$/);
    if (!m) {
      return;
    }
    const functionName = m["1"];
github marko-js / language-server / server / src / server.ts View on Github external
import {
  createConnection,
  TextDocuments,
  InitializeParams,
  ProposedFeatures
} from "vscode-languageserver";

import { MLS } from "./service";

let mls: MLS;

// Create a connection for the server
// Also include all preview / proposed LSP features.
const connection =
  process.argv.length <= 2
    ? createConnection(process.stdin, process.stdout) // no arg specified
    : createConnection(ProposedFeatures.all);
const DEBUG = process.env.DEBUG === 'true' || false;

console.log = connection.console.log.bind(connection.console);
console.error = connection.console.error.bind(connection.console);

// Create a simple text document manager. The text document manager
// supports full document sync only
let documents: TextDocuments = new TextDocuments();

// let hasConfigurationCapability: boolean = false;
// let hasWorkspaceFolderCapability: boolean = false;
// let hasDiagnosticRelatedInformationCapability: boolean = false;

// After the server has started the client sends an initilize request. The server receives
// in the passed params the rootPath of the workspace plus the client capabilites.
github microsoft / vscode-extension-samples / lsp-multi-server-sample / server / src / server.ts View on Github external
/*---------------------------------------------------------
 * Copyright (C) Microsoft Corporation. All rights reserved.
 *--------------------------------------------------------*/
'use strict';

import {
	createConnection, TextDocuments, ProposedFeatures, TextDocumentSyncKind
} from 'vscode-languageserver';

// Creates the LSP connection
let connection = createConnection(ProposedFeatures.all);
// Create a manager for open text documents

let documents = new TextDocuments();

// The workspace folder this server is operating on
let workspaceFolder: string;

documents.onDidOpen((event) => {
	connection.console.log(`[Server(${process.pid}) ${workspaceFolder ? workspaceFolder : 'generic'}] Document opened: ${event.document.uri}`);
})
documents.listen(connection);

connection.onInitialize((params) => {
	if (params.initializationOptions && params.initializationOptions.genericServer) {
		connection.console.log(`[Server(${process.pid}) generic] Started and initialize received`);
	} else {
		workspaceFolder = params.rootUri;
		connection.console.log(`[Server(${process.pid}) ${workspaceFolder}] Started and initialize received`);
	}
github iamcco / diagnostic-languageserver / src / index.ts View on Github external
import { IConfig } from './common/types';
import {
  next as diagnosticNext,
  unsubscribe as diagnosticUnsubscribe
} from './handles/handleDiagnostic'
import logger from './common/logger';
import { formatDocument } from './handles/handleFormat';

// create connection by command argv
const connection: IConnection = createConnection();

// init logger
logger.init(connection)

// sync text document manager
const documents: TextDocuments = new TextDocuments();

// config of initializationOptions
let config: IConfig

// lsp initialize
connection.onInitialize((param: InitializeParams) => {
  const { initializationOptions = {} } = param

  config = initializationOptions

  return {
    capabilities: {
      textDocumentSync: documents.syncKind,
      documentFormattingProvider: true
    }
  };
github apazureck / openui5vscodeTypescriptTools / ui5xmlserver / src / server.ts View on Github external
/**
	 * Instance of the schemastore, which handles the xml schemas
	 */
	export let schemastore: XmlStorage;
	/**
	 * Root folder of the current workspace
	 */
	export let workspaceRoot: string;
}

// Create a connection for the server. The connection uses Node's IPC as a transport
const connection: IConnection = createConnection(new IPCMessageReader(process), new IPCMessageWriter(process));

// Create a simple text document manager. The text document manager
// supports full document sync only
const documents: TextDocuments = new TextDocuments();

connection.onInitialize((params): InitializeResult => {
	connection.console.info("Initializing XML language server");
	// connection.console.log("params: " + JSON.stringify(params));

	Global.serverSettings = params.initializationOptions;
	Global.workspaceRoot = params.rootPath;
	Global.schemastore = new XmlStorage(Global.serverSettings.storagepath, connection, LogLevel.None);

	connection.console.info("Starting Listener");
	// Make the text document manager listen on the connection
	// for open, change and close text document events
	documents.listen(connection);

	return {
		capabilities: {
github GameMakerDiscord / gml-tools-langserver / src / completion.ts View on Github external
kind: CompletionItemKind.Function,
                    textEdit: {
                        newText: thisItem.replace(thisWord, ''),
                        range: thisRange
                    }
                });
            }
        }

        // Extensions
        const extensionList = this.reference.extensionGetAllExtensionNames();
        for (const thisItem of extensionList) {
            if (thisItem && rx.test(thisItem) === true) {
                workingArray.push({
                    label: thisItem,
                    kind: CompletionItemKind.Function,
                    textEdit: {
                        newText: thisItem.replace(thisWord, ''),
                        range: thisRange
                    }
                });
            }
        }

        // Objects
        const objectList = this.reference.objectGetList();
        for (const thisItem of objectList) {
            if (rx.test(thisItem) === true) {
                workingArray.push({
                    label: thisItem,
                    kind: CompletionItemKind.Class,
                    textEdit: {
github Azure / autorest / src / autorest-core / dist / language-service / language-service.js View on Github external
log(text) {
        this.connection.console.log(text);
    }
    verbose(text) {
        if (this.settings.verbose) {
            this.connection.console.log(text);
        }
    }
    verboseDebug(text) {
        if (this.settings.verbose && this.settings.debug) {
            this.connection.console.info(text);
        }
    }
}
// Create the IPC Channel for the lanaguage service.
let connection = vscode_languageserver_1.createConnection(new vscode_languageserver_1.IPCMessageReader(process), new vscode_languageserver_1.IPCMessageWriter(process));
let languageService = new OpenApiLanguageService(connection);
process.on("unhandledRejection", function (err) {
    //
    // @Future_Garrett - only turn this on as a desperate move of last resort.
    // You'll be sorry, and you will waste another day going down this rat hole
    // looking for the reason something is failing only to find out that it's only
    // during the detection if a file is swagger or not, and then you'll
    // realize why I wrote this message. Don't say I didn't warn you.
    // -- @Past_Garrett
    //
    // languageService.verboseDebug(`Unhandled Rejection Suppressed: ${err}`);
});
// Listen on the connection
connection.listen();
//# sourceMappingURL=language-service.js.map
github GameMakerDiscord / gml-tools-langserver / src / completion.ts View on Github external
const getAll = ourWords[1] == undefined;
        const rx = new RegExp('^' + ourWords[1]);

        // Idiotic Macros
        if (this.reference.macroExists(ourWords[0])) {
            const macroVal = this.reference.macroGetMacroValue(ourWords[0]);
            if (macroVal) ourWords[0] = macroVal;
        }

        // Variables
        const variableList = this.reference.instGetAllInsts(ourWords[0]);
        for (const thisVar of variableList) {
            if (rx.test(thisVar) || getAll) {
                workingArray.push({
                    label: thisVar,
                    kind: CompletionItemKind.Variable,
                    textEdit: {
                        newText: thisVar,
                        range: Range.create(params.position, params.position)
                    }
                });
            }
        }

        // Enums
        const enumMembers = this.reference.enumGetMemberNames(ourWords[0]);
        if (enumMembers) {
            for (const enumMember of enumMembers) {
                if (rx.test(enumMember) || getAll) {
                    workingArray.push({
                        label: enumMember,
                        kind: CompletionItemKind.EnumMember,
github apazureck / openui5vscodeTypescriptTools / ui5xmlserver / src / providers / XmlCompletionProvider.ts View on Github external
}

		// Append additional elements
		for (const ns in this.usedNamespaces) {
			if (this.usedNamespaces[ns] === element.schema.targetNamespace) {
				foundElements.push({ namespace: ns, elements: ownelements, ciKind: CompletionItemKind.Property });
				break;
			}
		}

		foundElements = foundElements.concat(derivedelements);
		let ret: CompletionItem[] = [];
		for (let item of foundElements) {
			for (const entry of item.elements)
				try {
					const citem = CompletionItem.create(entry.$.name);
					const nsprefix = item.namespace.length > 0 ? item.namespace + ":" : "";
					citem.insertText = "<" + nsprefix + entry.$.name + ">$0";
					citem.insertTextFormat = 2;
					citem.kind = item.ciKind || CompletionItemKind.Class;
					if (item.namespace.length > 0)
						citem.detail = "Namespace: " + item.namespace;
					try {
						citem.documentation = this.markdownText(entry.annotation[0].documentation[0]);
					} catch (error) {

					}
					ret.push(citem);
				} catch (error) {
					this.connection.console.error("Item error: " + error.toString());
				}
		}