Closed JulianJesacher closed 7 months ago
Hi @JulianJesacher for syntax highlighting import this:
import 'vscode/default-extensions/python';
like it is done here for the json example:
https://github.com/TypeFox/monaco-languageclient-ng-example/blob/main/src/app/app.component.ts#L18
This should be sufficient. It was quite recently introduced by underlying monaco-vscode-api
.
Thank you very much for your response, @kaisalmen. I already used that import statement, but apparently, I didn't have the npm packet installed. So I installed it using npm:
npm install @codingame/monaco-vscode-api
But now when I run ng serve, I get a lot of errors, for example, one of them is the following: ./node_modules/vscode/dist/vscode/vs/workbench/services/workspaces/browser/workspacesService.js:191:142-154 - Error: export 'IFileService' (imported as 'IFileService') was not found in 'monaco-editor/esm/vs/platform/files/common/files.js' (possible exports: FileKind)
I don't know what I did wrong since I used most of the code from this repository, along with all the configurations.
@codingame/monaco-vscode-api
must be imported as vscode
, but monaco-languageclient
ensures that, so there is nothing to install. really. š¤
I just added import 'vscode/default-extensions/python';
for testing locally into app.component.ts and ng serve
works fine.
Btw, I update the repo to the latest version of monaco-languageclient
6.2.0
, monaco-vscode-api
1.79.3
, monaco-editor
0.39.0
and monaco-editor-workers
0.39.1
I cloned the repo again and didn't change anything except for the language and the path to the language server. The syntax errors are still shown (so the connection to the languge server works), but syntax highlighting and auto-indentation are still missing. Here are my modified app.component.ts:
/* --------------------------------------------------------------------------------------------
* Copyright (c) 2023 TypeFox GmbH (http://www.typefox.io). All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
* ------------------------------------------------------------------------------------------ */
import 'monaco-editor/esm/vs/editor/editor.all.js';
import 'monaco-editor/esm/vs/editor/standalone/browser/accessibilityHelp/accessibilityHelp.js';
import 'monaco-editor/esm/vs/editor/standalone/browser/iPadShowKeyboard/iPadShowKeyboard.js';
import { languages, Uri } from 'monaco-editor/esm/vs/editor/editor.api.js';
import { createConfiguredEditor, createModelReference } from 'vscode/monaco';
import { initServices, MonacoLanguageClient } from 'monaco-languageclient';
import { toSocket, WebSocketMessageReader, WebSocketMessageWriter } from 'vscode-ws-jsonrpc';
import normalizeUrl from 'normalize-url';
import { AfterViewInit, Component } from '@angular/core';
import { CloseAction, ErrorAction, MessageTransports } from 'vscode-languageclient/lib/common/client.js';
import 'vscode/default-extensions/theme-defaults';
import 'vscode/default-extensions/json';
import { buildWorkerDefinition } from 'monaco-editor-workers';
buildWorkerDefinition('./assets/monaco-editor-workers/workers', window.location.href + '../..', false);
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class MonacoEditorComponent implements AfterViewInit {
title = 'angular-client';
initDone = false;
createLanguageClient(transports: MessageTransports): MonacoLanguageClient {
return new MonacoLanguageClient({
name: 'Sample Language Client',
clientOptions: {
// use a language id as a document selector
documentSelector: ['py'],
// disable the default error handler
errorHandler: {
error: () => ({ action: ErrorAction.Continue }),
closed: () => ({ action: CloseAction.DoNotRestart })
}
},
// create a language client connection from the JSON RPC connection on demand
connectionProvider: {
get: () => {
return Promise.resolve(transports);
}
}
});
}
createUrl(hostname: string, port: number, path: string): string {
const protocol = location.protocol === 'https:' ? 'wss' : 'ws';
return normalizeUrl(`${protocol}://${hostname}:${port}${path}`);
}
createWebSocket(url: string): WebSocket {
const webSocket = new WebSocket(url);
webSocket.onopen = () => {
const socket = toSocket(webSocket);
const reader = new WebSocketMessageReader(socket);
const writer = new WebSocketMessageWriter(socket);
const languageClient = this.createLanguageClient({
reader,
writer
});
languageClient.start();
reader.onClose(() => languageClient.stop());
};
return webSocket;
}
private createDefaultJsonContent(): string {
return `{
"$schema": "http://json.schemastore.org/coffeelint",
"line_endings": "unix"
}`;
}
async ngAfterViewInit(): Promise<void> {
const languageId = 'python';
if (!this.initDone) {
await initServices({
enableFilesService: true,
enableKeybindingsService: true,
enableQuickaccessService: true,
enableThemeService: true,
enableTextmateService: true,
enableModelService: true,
configureEditorOrViewsServiceConfig: {
enableViewsService: false,
useDefaultOpenEditorFunction: true
},
enableLanguagesService: true,
debugLogging: true
});
this.initDone = true;
}
// register the JSON language with Monaco
languages.register({
id: languageId,
extensions: ['.py'],
aliases: ['py', 'Python', 'python'],
mimetypes: ['application/python']
});
// create the model
const uri = Uri.parse('/tmp/model.py');
const modelRef = await createModelReference(uri, this.createDefaultJsonContent());
modelRef.object.setLanguageId(languageId);
// create monaco editor
createConfiguredEditor(document.getElementById('container')!, {
model: modelRef.object.textEditorModel,
glyphMargin: true,
lightbulb: {
enabled: true
},
automaticLayout: true
});
// create the web socket
const url = this.createUrl('localhost', 3000, '/python');
this.createWebSocket(url);
}
}
Please replace
import 'vscode/default-extensions/json';
with
import 'vscode/default-extensions/python';
This should introduce syntax hihlighting.
Oh yes, that enables syntax highlighting. But when I replace it, the language server doesn't work as expected. When I inspect the WebSocket connection, only three messages are sent; if I change the text, no additional messages are sent. By simply replacing the import back to
import 'vscode/default-extensions/json';
it works again, messages over the WebSocket are sent when I change something, and the errors are shown as expected.
@JulianJesacher sorry, I didn't get that before. Which python language server are you using?
@kaisalmen I use the script examples/langserver_ext.py from this repository: https://github.com/python-lsp/python-lsp-jsonrpc
@CGNonofr do you have an idea? Thanks.
Why calling
languages.register({
id: languageId,
extensions: ['.py'],
aliases: ['py', 'Python', 'python'],
mimetypes: ['application/python']
});
?
I just changed it form the original code in this repository. If I remove the languages.register call, both syntax highlighting and the connection to the language server don't work.
I played around with it a bit more and the connection to the language server basically works flawlessly until I use the following import:
import 'vscode/default-extensions/python';
Now it finally works. The problem was that the documentSelector is 'python' not 'py'. And the languages.register call is required, I currently have it like this:
languages.register({
id: languageId,
extensions: [".py"],
aliases: ["py", "python"],
mimetypes: ["text/x-python-source"],
});
But now finally everything works, thank you so much for your help @kaisalmen and @CGNonofr !!
Nice to know
but I guarantee the call to languages.register
shouldn't be done. It's probably hiding another issue
Yeah that could be the case since the themes also don't work. Is there documentation for this? I can't find one
The documentation is probably not complete enough, we need to improve it
What would I need to do to change the theme to 'vs-dark'? Just adding
theme: 'vs-dark'
to the options of createConfiguredEditor doesn't do anything
vs-dark is the monaco theme, the vscode theme names are Default Dark+
, Default Light+
...
So like this?
createConfiguredEditor(document.getElementById("container")!, {
model: modelRef.object.textEditorModel,
glyphMargin: true,
theme: 'Default Dark+',
lightbulb: {
enabled: true,
},
automaticLayout: true,
});
@JulianJesacher sorry, I was away for a couple of weeks.
Before createConfiguredEditor
call updateUserConfiguration
. You can import it from here:
import { updateUserConfiguration } from 'vscode/service-override/configuration';
You can set vscode settings, for example like this:
updateUserConfiguration(`{
"workbench.colorTheme": "Default Dark Modern",
"editor.fontSize": 10,
"editor.guides.bracketPairsHorizontal": "active",
}`);
To ease things just set the model and automaticLayout with createConfiguredEditor
and all configuration you perform with updateUserConfiguration
.
Close this stale issue. Repository will be archived.
I hope this is not the completely wrong place to ask but I just can't figure out how to get it to work. I want to add the monaco editor in a angular project with syntax highlighting, intellisense and syntax checking for python. I used a custom language server for python from github for the syntax checking(https://github.com/python-lsp/python-lsp-jsonrpc) and this repository to connect to the server. I changed the language to python and while the syntax checking works, there is no syntax highlighting and also no auto identation. Here is how I create the editor:
I tried several things already: