### Basic start example in React Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco.md Shows a minimal React setup: create a LeanMonaco instance, set the infoview element, start with WebSocket options, wait for readiness, then start an editor. Cleanup by disposing the instance. ```TSX import { LeanMonaco, LeanMonacoEditor, LeanMonacoOptions } from 'lean4monaco' const options: LeanMonacoOptions = { websocket: { url: 'ws://localhost:8080/' }, htmlElement: undefined, vscode: { 'editor.wordWrap': true }, } const leanMonaco = new LeanMonaco() leanMonaco.setInfoviewElement(infoviewRef.current!) ;(async () => { await leanMonaco.start(options) await leanMonaco.whenReady // idempotent; resolves after start() const editor = new LeanMonacoEditor() await editor.start(editorDiv, '/project/test.lean', '#check Nat') })() // cleanup leanMonaco.dispose() ``` -------------------------------- ### Start demo server with npm start Source: https://github.com/hhu-adam/lean4monaco/blob/main/doc/development.md Starts the demo server required for interactive testing. ```bash npm start ``` -------------------------------- ### Setup Monaco Client with LeanMonaco Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/monaco-lean-client.md Shows how to import and start the LeanMonaco client, including direct use of setupMonacoClient for a custom LeanClient. The websocket URL and clientOptions are configurable. ```ts import { setupMonacoClient } from 'lean4monaco/src/monacoleanclient' // internal location import { LeanMonaco } from 'lean4monaco' // Normal usage is indirect — through LeanMonaco options: const leanMonaco = new LeanMonaco() await leanMonaco.start({ websocket: { url: 'ws://localhost:8080/' }, clientOptions: { // vscode-languageclient LanguageClientOptions, e.g.: // documentSelector: [{ language: 'lean4', scheme: 'file' }] (the LeanClientProvider provides its own), // revealOutputChannelOn: 3, }, }) // Direct use for a custom LeanClient: // const factory = setupMonacoClient({ $type: 'WebSocketUrl', url: 'ws://localhost:8080/' }) // const client = await factory({ documentSelector: [{ language: 'lean4' }] } as LanguageClientOptions) ``` -------------------------------- ### Set up Python virtual environment for scripts Source: https://github.com/hhu-adam/lean4monaco/blob/main/scripts/README.md One-time setup to create a local Python virtual environment at scripts/.python/ and install requirements from scripts/requirements.txt. After this, activate with `source scripts/.python/bin/activate` and deactivate with `deactivate`. ```bash cd scripts python -m venv .python source .python/bin/activate pip install -r requirements.txt ``` -------------------------------- ### Run the lean4monaco demo Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Clone the repository with submodules, then install dependencies and start the demo. The demo opens a webpage with Monaco editors and an infoview at localhost:5173. ```bash cd lean4monaco npm install npm run demo:setup # this builds lean4monaco and calls `npm install` in `demo/` npm start ``` -------------------------------- ### start() method signature Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco.md Declares the public `start` method that initializes the Lean environment. Returns a Promise that resolves when the environment is ready. If the instance is already disposed, the promise resolves without action. ```TypeScript async start(options: LeanMonacoOptions) ``` -------------------------------- ### React example using LeanMonaco and LeanMonacoEditor Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Example of using LeanMonaco and LeanMonacoEditor in a React component. Requires a single LeanMonaco instance and one or more LeanMonacoEditor instances. Must await leanMonaco.start or use whenReady before starting editors. ```tsx import { LeanMonaco, LeanMonacoEditor, LeanMonacoOptions } from 'lean4monaco' [...] // Refs for the editor and infoview const editorRef = useRef(null) const infoviewRef = useRef(null) // Lean4monaco options const [options, setOptions] = useState({ websocket: { url: 'ws://localhost:8080/' }, htmlElement: undefined, // The wrapper div for monaco vscode: { "editor.wordWrap": true, } }) // Optional: restrict monaco's extend (e.g. context menu) to the editor itself useEffect(() => { setOptions({...options, htmlElement: editorRef.current ?? undefined}) }, [editorRef]) // Start infoview and editor(s) useEffect(() => { // You must create a single `LeanMonaco` instance (infoview), but you can create multiple // `LeanMonacoEditor` instances (editor) // You must await `leanMonaco.start` or use `await leanMonaco.whenReady` before // starting the editors! const leanMonaco = new LeanMonaco() const leanMonacoEditor = new LeanMonacoEditor() leanMonaco.setInfoviewElement(infoviewRef.current!) ;(async () => { await leanMonaco.start(options) await leanMonacoEditor.start(editorRef.current!, '/project/test.lean', '#check Nat') })() return () => { leanMonaco.dispose() leanMonacoEditor.dispose() } }, [options, infoviewRef, editorRef]) ``` -------------------------------- ### start(options: LeanMonacoOptions): Promise Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco.md Starts the LeanMonaco instance, initializing the Lean environment and resolving when ready. It sets up workers, registers the Lean extension, applies VSCode options, and loads fonts. ```APIDOC ## `start(options: LeanMonacoOptions): Promise` ### Description Starts the LeanMonaco instance, initializing the Lean environment and resolving when ready. It sets up workers, registers the Lean extension, applies VSCode options, and loads fonts. ### Method `start` ### Parameters - **options** (`LeanMonacoOptions`) - Required - Configuration options for the LeanMonaco instance. ### Returns `Promise` - Resolves when the Lean environment is fully initialized. ### Behavior 1. If the instance is already active, logs a warning and returns. 2. If another instance is active, disposes it and makes this the active instance. 3. Installs Monaco environment workers if not set. 4. Initializes VSCode services with overrides. 5. Waits for theme default extension. 6. Registers the Lean extension. 7. Applies VSCode options. 8. Registers Lean editor providers and creates features. 9. Loads fonts. 10. Creates webview factory and info provider. 11. Applies default editor settings and resolves `whenReady`. ### Example (React) ```tsx import { LeanMonaco, LeanMonacoEditor, LeanMonacoOptions } from 'lean4monaco' const options: LeanMonacoOptions = { websocket: { url: 'ws://localhost:8080/' }, htmlElement: undefined, vscode: { 'editor.wordWrap': true }, } const leanMonaco = new LeanMonaco() leanMonaco.setInfoviewElement(infoviewRef.current!) ;(async () => { await leanMonaco.start(options) await leanMonaco.whenReady // idempotent; resolves after start() const editor = new LeanMonacoEditor() await editor.start(editorDiv, '/project/test.lean', '#check Nat') })() // cleanup leanMonaco.dispose() ``` ### Example (Singleton behavior) ```ts const a = new LeanMonaco() await a.start(opts) // a becomes LeanMonaco.activeInstance const b = new LeanMonaco() await b.start(opts) // disposes a, b becomes active console.log(a.disposed) // true: b.start() called dispose() on the previous instance console.log(LeanMonaco.activeInstance === b) // true ``` ``` -------------------------------- ### start Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Starts or restarts the language server. Delegates to restart(). ```APIDOC ## start ### Description Starts or restarts the language server. Delegates to restart(). ### Method start ### Returns - `Promise` - Resolves when the server has started. ``` -------------------------------- ### Awaiting LeanMonaco before starting editor with disposal guard Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco-editor.md Shows how to start the LeanMonaco instance first, wait for it with whenReady, then start the editor inside an async IIFE. On startup failure, logs the error and disposes the editor. Also disposes both instances on beforeunload. The editor start is async and must be awaited explicitly. ```TypeScript import { LeanMonaco, LeanMonacoEditor } from 'lean4monaco' const leanMonaco = new LeanMonaco() leanMonaco.setInfoviewElement(document.querySelector('#infoview')!) void leanMonaco.start({ websocket: { url: 'ws://' + window.location.hostname + ':8080/' } }) const editor = new LeanMonacoEditor() ;(async () => { await leanMonaco.whenReady // start() is async; wait for it explicitly try { await editor.start(container, '/project/Test0.lean', 'example : Nat := 42') } catch (err) { console.error('editor startup failed', err) editor.dispose() } })() window.addEventListener('beforeunload', () => { leanMonaco.dispose() editor.dispose() }) ``` -------------------------------- ### Obtain and drive the Lean client (without polling) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Shows the pattern used by the demo: start LeanMonaco, get the first client, subscribe to progress and stopped events, send a raw LSP request and notification, then dispose subscriptions and stop the client. ```TypeScript import { LeanMonaco } from 'lean4monaco' const leanMonaco = new LeanMonaco() await leanMonaco.start({ websocket: { url: 'ws://localhost:8080/' } }) const client = leanMonaco.clientProvider!.getClients()[0]! console.log(client.getClientFolder().toString(), client.isRunning()) // subscribe to server events const sub = client.progressChanged(([uri, infos]) => console.log('processing', uri, infos.length)) const sub2 = client.stopped(reason => console.warn('server stopped:', reason.message, reason.reason)) // raw LSP request const res = await client.sendRequest('$/lean/rpc/connect', { uri: '/project/test.lean' }) console.log('session id:', res.sessionId) client.sendNotification('$/lean/rpc/keepAlive', { uri: '/project/test.lean', sessionId: res.sessionId }) sub.dispose() sub2.dispose() client.stop() ``` -------------------------------- ### Install esbuild-import-meta-url-plugin Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Install the esbuild plugin required for Vite dev mode. ```bash npm install --save-dev '@codingame/esbuild-import-meta-url-plugin' ``` -------------------------------- ### Singleton behavior example Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco.md Demonstrates that only one LeanMonaco instance can be active. Starting a second instance disposes the previous one, making the new instance the active one. ```TypeScript const a = new LeanMonaco() await a.start(opts) // a becomes LeanMonaco.activeInstance const b = new LeanMonaco() await b.start(opts) // disposes a, b becomes active console.log(a.disposed) // true: b.start() called dispose() on the previous instance console.log(LeanMonaco.activeInstance === b) // true ``` -------------------------------- ### Install lean4monaco package Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Install the lean4monaco npm package in your project. ```bash npm install lean4monaco ``` -------------------------------- ### start method implementation Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco-editor.md Initializes the Monaco editor and its model. Returns immediately if disposed. Creates the model via createModelReference, creates the editor with automaticLayout and hard-set options (contextmenu, lineNumbersMinChars, lineDecorationsWidth), attaches the model, and focuses the editor to open the infoview. Errors from model creation or editor creation propagate to the caller. ```TypeScript async start(editorEl: HTMLElement, fileName: string, code: string) { if (this.disposed) return // Create editor and model this.modelRef = await createModelReference(Uri.parse(fileName), code) this.editor = monaco.editor.create(editorEl, { automaticLayout: true, contextmenu: true, // the context menu breaks mobile support. lineNumbersMinChars: 1, // minimal no. of characters for line numbers lineDecorationsWidth: 5, // distance (px) between line number and code. }) this.editor.setModel(this.modelRef.object.textEditorModel) // Set focus on editor to trigger infoview to open this.editor.focus() } ``` -------------------------------- ### start(editorEl, fileName, code) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco-editor.md Initializes the editor by creating a model reference and a Monaco editor instance, attaching the model, and focusing the editor. Must be called after the LeanMonaco instance is ready. ```APIDOC ## start(editorEl, fileName, code) ### Description Initializes the editor by creating a model reference and a Monaco editor instance, attaching the model, and focusing the editor. Must be called after the LeanMonaco instance is ready. ### Method start ### Parameters - **editorEl** (HTMLElement) - Required - DOM element the editor is created in - **fileName** (string) - Required - URI passed to `Uri.parse(...)`; must be a path inside the served Lean project (e.g. `/project/test.lean`) - **code** (string) - Required - initial file content ### Returns `Promise` ### Behavior Creates the file model via `createModelReference(Uri.parse(fileName), code)`, creates the editor with `automaticLayout: true` (plus `contextmenu: true`, `lineNumbersMinChars: 1`, `lineDecorationsWidth: 5`), attaches the model with `setModel`, then calls `editor.focus()` to make the infoview open at the cursor. ### Errors Errors from model creation or `monaco.editor.create` propagate to the caller. If `disposed` is already `true`, returns immediately without creating anything. ``` -------------------------------- ### Install vite-plugin-node-polyfills and memfs Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Install node polyfills for Vite. Version 0.17.0 is used due to a bug in the plugin. ```bash npm install vite-plugin-node-polyfills@0.17.0 --save-exact npm install memfs ``` -------------------------------- ### RpcSessions usage example with RpcServerIface Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc-sessions.md Shows how to create an RpcSessions instance with a custom RpcServerIface and connect to a session. The example includes error handling for RPC calls and cleanup via closeSessionForFile or dispose. Note that protocol-level closing is implementation-defined; the bundled infoview closes sessions through InfoProvider.closeRpcSession. ```TypeScript import { RpcSessions, RpcServerIface } from '@leanprover/infoview-api' // or from 'lean4monaco' const iface: RpcServerIface = { createRpcSession: uri => client.sendRequest('$/lean/rpc/connect', { uri }), // Protocol-level closing is implementation-defined: the bundled infoview closes // sessions through its editor API bookkeeping (InfoProvider.closeRpcSession), so any // side effects for the sessionId (e.g. a close notification) belong here. closeRpcSession: sessionId => console.log('closing session', sessionId), call: params => client.sendRequest('$/lean/rpc/call', params), release: params => void client.sendNotification('$/lean/rpc/release', params), } const sessions = new RpcSessions(iface) // session for /project/test.lean at line 1, character 0 const sess = sessions.connect({ textDocument: { uri: '/project/test.lean' }, position: { line: 1, character: 0 } }) try { const goals = await sess.call('Lean.Widget.getInteractiveGoals', { ... }) console.log(goals) } catch (err) { console.error('RPC failed', err) } // cleanup on navigation away: sessions.closeSessionForFile('/project/test.lean') // or sessions.dispose() ``` -------------------------------- ### Webview side RPC setup with InfoviewApi Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/info-provider.md Webview code that creates an Rpc instance, listens for messages, obtains the typed InfoviewApi via rpc.getApi, and registers the API with loadRenderInfoview. The comment indicates loadRenderInfoview is called with imports, the editorApi, a div, and a callback to register the api. ```TypeScript import type { EditorApi } from '@leanprover/infoview' import { loadRenderInfoview } from '@leanprover/infoview/loader' import { Rpc } from '../vscode-lean4/vscode-lean4/src/rpc' const vscodeApi = window.parent const rpc = new Rpc((m: any) => vscodeApi.postMessage(JSON.stringify(m))) window.addEventListener('message', e => { try { rpc.messageReceived(JSON.parse(e.data)) } catch (error) { /* JSON.parse failure */ } }) const editorApi: EditorApi = rpc.getApi() // ... loadRenderInfoview(imports, [editorApi, div], api => rpc.register(api)) ``` -------------------------------- ### Run Docker container Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Start the Docker container, mapping ports 5173 and 8080. The demo is accessible at localhost:5173. ```bash docker run -it -p 5173:5173 -p 8080:8080 lean4monaco ``` -------------------------------- ### setupMonacoClient function signature and implementation Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/monaco-lean-client.md Defines the internal adapter that creates a LanguageClientWrapper, initializes it for 'lean4', starts it, and returns the wrapped LanguageClient. It intercepts error messages to display a notification and forwards them via next(). ```TypeScript export const setupMonacoClient = ( options: WebSocketConfigOptions | WebSocketConfigOptionsUrl | WorkerConfigOptions | WorkerConfigDirect, moreClientOptions?: LanguageClientOptions ) => { return async (clientOptions: LanguageClientOptions) => { const languageClientWrapper = new LanguageClientWrapper() await languageClientWrapper.init({ languageClientConfig: { languageId: 'lean4', options, clientOptions: { ...merge({}, clientOptions, moreClientOptions), connectionOptions: { ...clientOptions.connectionOptions, messageStrategy: { handleMessage: (message: any, next: (message: Message) => void) => { if (message.error) { // TODO: Handle Lean errors correctly displayNotification("Error", message.error.message) next(message) // remove this to prevent propagating the message } else { next(message) } } } } } } }) await languageClientWrapper?.start() const client = languageClientWrapper.getLanguageClient()!; (client as any)._serverProcess = { stderr: { on: () => {} }} return client } } ``` -------------------------------- ### Run automated Cypress tests Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Install dependencies and run the automated Cypress tests. ```bash npm install npm test ``` -------------------------------- ### Default editor settings applied in start() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco.md These defaults are applied at the end of `start()` with `...options.vscode` taking precedence. They configure editor behavior such as line numbers, word wrap, and color theme based on system preference. ```TypeScript this.updateVSCodeOptions({ "editor.lineNumbers": "on", "editor.stickyScroll.enabled": false, "editor.folding": false, "editor.minimap.enabled": false, "editor.glyphMargin": true, "editor.semanticHighlighting.enabled": true, "editor.lightbulb.enabled": "on", "editor.detectIndentation": false, "editor.acceptSuggestionOnEnter": "off", "editor.renderWhitespace": "trailing", "editor.fontFamily": "'Noto Color Emoji', 'JuliaMono'", "editor.wordWrap": "on", "editor.wrappingStrategy": "advanced", "workbench.colorTheme": isBrowserDefaultDark() ? "Visual Studio Dark" : "Visual Studio Light", ...options.vscode }) ``` -------------------------------- ### Reference LeanMonacoOptions with websocket URL in editor-atoms.ts Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/configuration.md Ships the reference options for the demo, setting the websocket URL to the current hostname on port 8080 and leaving vscode overrides optional. The Lean server is started with `lake serve --` inside `demo/server/LeanProject`, which must contain files like `LeanProject/Test0.lean` for lake to accept them. ```TypeScript const socketUrl = 'ws://' + window.location.hostname + ':8080/' export const leanMonacoOptionsAtom = atom({ websocket: { url: socketUrl }, vscode: { /* optional overrides, e.g. "editor.wordWrap": false */ }, }) ``` -------------------------------- ### Run font subsetting script Source: https://github.com/hhu-adam/lean4monaco/blob/main/scripts/README.md Creates a subset of the NotoColorEmoji font containing only glyphs used by lean4monaco. Requires the original font at src/fonts/NotoColorEmoji-Regular.ttf; if missing, download it from Google Fonts. ```bash npm run font:subset ``` -------------------------------- ### setInfoviewElement method signature Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco.md Stores the host element for the infoview iframe. If iframeWebviewFactory already exists (after start()), also calls setInfoviewElement on it. Recommended to call before start(). Returns void. ```ts setInfoviewElement(infoviewEl: HTMLElement){ ``` -------------------------------- ### restart() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Restarts the Lean client. Guards against double restarts, determines the server executable, stops any existing client, and starts a new one. ```APIDOC ## [METHOD] restart ### Description Restarts the Lean client. Guards against double restarts, determines the server executable, stops any existing client, and starts a new one. ### Method async restart ### Signature ```ts async restart(): Promise ``` ### Parameters None ### Returns `Promise` ``` -------------------------------- ### startClientRequest(uri, method, params, options?) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc.md Starts a client request over the RPC channel. Returns a request id that can be used with awaitClientRequest or cancelClientRequest. ```APIDOC ## startClientRequest(uri, method, params, options?) ### Description Starts a client request over the RPC channel. Returns a request id that can be used with awaitClientRequest or cancelClientRequest. ### Method startClientRequest ### Parameters - **uri** (string) - Required - The URI of the resource. - **method** (string) - Required - The method name to invoke. - **params** (any) - Required - The parameters for the method. - **options** (ClientRequestRpcOptions) - Optional - Options for the request, excluding abortSignal. ### Returns Promise - The request id. ``` -------------------------------- ### dispose method implementation Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco-editor.md Releases the model reference and the editor, and marks the instance as disposed. Safe to call even if start() never ran because it checks for existence of modelRef and editor. After disposal, subsequent start() calls become no-ops. ```TypeScript dispose(){ if (this.modelRef) this.modelRef.dispose() if (this.editor) this.editor.dispose() this.disposed = true } ``` -------------------------------- ### DocumentPosition usage example Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/document-position.md Shows how to import and use DocumentPosition with the useRpcSessionAtPos hook and manual conversion to TextDocumentPositionParams. ```TypeScript import { DocumentPosition } from 'lean4monaco' import { useRpcSessionAtPos } from 'lean4monaco/src/vscode-lean4/lean4-infoview/src/infoview/rpcSessions' const pos: DocumentPosition = { uri: '/project/test.lean', line: 0, character: 0 } console.log(DocumentPosition.toString(pos)) // '/project/test.lean:1:0' if (DocumentPosition.isEqual(pos, { uri: '/project/test.lean', line: 0, character: 0 })) { console.log('same position') } // feed it directly into the hook / RpcSessions: const session = useRpcSessionAtPos(pos) // or, manually: const tdpp = DocumentPosition.toTdpp(pos) // tdpp === { textDocument: { uri: '/project/test.lean' }, position: { line: 0, character: 0 } } ``` -------------------------------- ### LeanClient.restarted Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Event that fires after the server (re)started. Use it to react to server restarts. ```APIDOC ## Event: restarted ### Description Fires after the server (re)started. ### Type `Event` ### Usage ```typescript client.restarted(() => { // handle restart }); ``` ``` -------------------------------- ### dispose() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Disposes all subscriptions and stops the client if it is started. Returns void. ```APIDOC ## [METHOD] dispose ### Description Disposes all subscriptions and stops the client if it is started. Returns void. ### Method dispose ### Signature ```ts dispose(): void ``` ### Parameters None ### Returns `void` ``` -------------------------------- ### dispose() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco-editor.md Releases the model reference and the editor and marks the instance disposed. Safe to call even if `start()` never ran. ```APIDOC ## dispose() ### Description Releases the model reference and the editor and marks the instance disposed. Safe to call even if `start()` never ran. ### Method dispose ### Parameters None ### Returns `void` ### Behavior If `this.modelRef` exists, disposes it. If `this.editor` exists, disposes it. Sets `this.disposed = true`. ``` -------------------------------- ### Basic usage of LeanMonacoEditor Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/leanmonaco-editor.md Creates a LeanMonacoEditor, starts it with a file path inside the Lean project and initial content, reads back the editor content, and disposes it in a cleanup function. The file name must be a real path inside the Lean project; a root-level path like /test.lean is known to misbehave. ```TypeScript import { LeanMonacoEditor } from 'lean4monaco' const editorDiv = document.querySelector('#codeview')! const leanMonacoEditor = new LeanMonacoEditor() await leanMonacoEditor.start(editorDiv, '/project/test.lean', '#check Nat') // read back the current content const text = leanMonacoEditor.editor.getValue() console.log(text) // later, in a cleanup function: leanMonacoEditor.dispose() ``` -------------------------------- ### RPC usage in IFrameInfoWebviewFactory.make() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc.md Hosting side setup for the RPC bridge. Creates an Rpc instance that posts JSON messages to the iframe, registers the editor API, and listens for messages from the iframe. ```ts // In IFrameInfoWebviewFactory.make(): const rpc = new Rpc(m => { try { void this.iframe.contentWindow!.postMessage(JSON.stringify(m)) } catch (e) { /* disposed */ } }) rpc.register(editorApiOfRpc(editorRpcApi)) // hosting side document.defaultView!.addEventListener('message', m => { if (m.source != this.iframe.contentWindow) { return } try { rpc.messageReceived(JSON.parse(m.data)) } catch { /* disposed */ } }) return new IFrameInfoWebview(this.iframe, rpc) ``` -------------------------------- ### Connect RPC session from browser and make RPC call Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc-session-at-pos.md Pattern from demo/src/LeanMonacoEditorComponent.tsx: starts LeanMonaco and editor, polls for the client, opens an RPC session via '$/lean/rpc/connect', wraps it with RpcSessionAtPos (keepalives sent every 10 s), calls a widget method, and disposes. Requires a running server at ws://localhost:8080/. ```ts import { LeanMonaco, LeanMonacoEditor, LeanClient, RpcSessionAtPos } from 'lean4monaco' import { RpcConnectParams } from '@leanprover/infoview-api' const leanMonaco = new LeanMonaco() await leanMonaco.start({ websocket: { url: 'ws://localhost:8080/' } }) const editor = new LeanMonacoEditor() await editor.start(editorDiv, '/project/test.lean', '#check Nat') await leanMonaco.whenReady // poll for the client (it becomes available once the server starts) const clients: LeanClient[] = leanMonaco.clientProvider?.getClients() ?? [] const client = clients[0] const model = editor.editor.getModel()! const fileUri = model.uri.toString() // 1. open the session const result = await client.sendRequest('$/lean/rpc/connect', { uri: fileUri } as RpcConnectParams) // 2. wrap it: keepalives are now sent automatically every 10 s const rpcSess = new RpcSessionAtPos(client, result.sessionId, fileUri) // 3. call a widget method try { const answer = await rpcSess.client.sendRequest('$/lean/rpc/call', { method: 'Lean.Widget.getInteractiveDiagnostics', params: { lineRange: { start: 0, end: 1 } }, textDocument: { uri: rpcSess.uri }, position: { line: 0, character: 0 }, sessionId: rpcSess.sessionId, }) console.log('Got an answer to the Rpc request!', answer) } catch (reason) { console.error('Rpc request failed!', reason) } // 4. cleanup rpcSess.dispose() ``` -------------------------------- ### RPC usage in src/webview/webview.ts (iframe side) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc.md Iframe side setup for the RPC bridge. Creates an Rpc instance that posts JSON messages to the parent window, listens for messages, and retrieves the EditorApi. ```ts // In src/webview/webview.ts (iframe side): const rpc = new Rpc((m) => window.parent.postMessage(JSON.stringify(m))) window.addEventListener('message', e => { try { rpc.messageReceived(JSON.parse(e.data)) } catch (err) { /* ignore */ } }) const editorApi: EditorApi = rpc.getApi() // ... loadRenderInfoview(imports, [editorApi, div], api => rpc.register(api)) ``` -------------------------------- ### Calling setupMonacoClient from LeanMonaco.start() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/monaco-lean-client.md Shows how LeanMonaco.start() invokes setupMonacoClient with WebSocket options and client options, wrapped in a LeanClientProvider. The provider's appendLine is stubbed as a no-op. ```TypeScript this.clientProvider = new LeanClientProvider( { appendLine: () => {} } as any, setupMonacoClient(this.getWebSocketOptions(options), options.clientOptions) ) ``` -------------------------------- ### InfoProvider construction inside LeanMonaco.start Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/info-provider.md Shows how LeanMonaco.start constructs the InfoProvider with an IFrameInfoWebviewFactory, setting the infoview element if present. This provider is required for the infoview to work. ```TypeScript // inside LeanMonaco.start(): this.iframeWebviewFactory = new IFrameInfoWebviewFactory(themeService, configurationService, fontFiles) if (this.infoviewEl) this.iframeWebviewFactory.setInfoviewElement(this.infoviewEl) this.infoProvider = new InfoProvider(this.clientProvider, {language: 'lean4'} as any, this.iframeWebviewFactory) ``` -------------------------------- ### static init(folderUri, outputChannel, setupLanguageClient) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Static factory method that instantiates a LeanClient. It stores the language client factory and registers config-file watchers that trigger restart notifications. ```APIDOC ## [STATIC] init ### Description Static factory method that instantiates a LeanClient. It stores the language client factory and registers config-file watchers that trigger restart notifications. ### Method static async init ### Signature ```ts static async init(folderUri: ExtUri, outputChannel: OutputChannel, setupLanguageClient: (clientOptions: LanguageClientOptions) => Promise): Promise ``` ### Parameters - **folderUri** (ExtUri) - Required - folder the client manages - **outputChannel** (OutputChannel) - Required - where client logs go - **setupLanguageClient** ((clientOptions: LanguageClientOptions) => Promise) - Required - factory; in lean4monaco this is the function returned by `setupMonacoClient(...)` ### Returns `Promise` (the created, not-yet-started client) ``` -------------------------------- ### Open Cypress with npx cypress open Source: https://github.com/hhu-adam/lean4monaco/blob/main/doc/development.md Launches the Cypress test runner for interactive testing. Requires the demo server to be running. ```bash npx cypress open ``` -------------------------------- ### cancelClientRequest(id) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc.md Cancels a previously started client request. ```APIDOC ## cancelClientRequest(id) ### Description Cancels a previously started client request. ### Method cancelClientRequest ### Parameters - **id** (number) - Required - The request id returned by startClientRequest. ### Returns Promise - Resolves when the cancellation is complete. ``` -------------------------------- ### awaitClientRequest(id) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc.md Waits for the result of a previously started client request. ```APIDOC ## awaitClientRequest(id) ### Description Waits for the result of a previously started client request. ### Method awaitClientRequest ### Parameters - **id** (number) - Required - The request id returned by startClientRequest. ### Returns Promise - The result of the request. ``` -------------------------------- ### Publish package with npm publish Source: https://github.com/hhu-adam/lean4monaco/blob/main/doc/development.md Uploads the package to npmjs.com. ```bash npm publish ``` -------------------------------- ### LeanClient.customNotification Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Event that fires on custom LSP notifications (methods starting with `$`). Provides the method name and parameters. ```APIDOC ## Event: customNotification ### Description Fires on custom LSP notifications (methods starting with `$`). ### Type `Event<{ method: string; params: any }>` ### Usage ```typescript client.customNotification((notification) => { // handle custom notification }); ``` ``` -------------------------------- ### Build Docker image Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Build the Docker image tagged as lean4monaco. ```bash docker build -t lean4monaco . ``` -------------------------------- ### leanServerCapabilities() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Returns the experimental part of the server capabilities, which contains Lean-specific extensions such as moduleHierarchyProvider and rpcProvider. ```APIDOC ## [METHOD] leanServerCapabilities ### Description Returns the experimental part of the server capabilities, which contains Lean-specific extensions such as moduleHierarchyProvider and rpcProvider. ### Method leanServerCapabilities ### Signature ```ts leanServerCapabilities(): LeanServerCapabilities | undefined ``` ### Parameters None ### Returns `LeanServerCapabilities | undefined` ``` -------------------------------- ### sendModuleHierarchyImportedBy(module) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Sends a request to get the modules that import a given module. Returns a tagged union result. ```APIDOC ## [METHOD] sendModuleHierarchyImportedBy ### Description Sends a request to get the modules that import a given module. Returns a tagged union result. ### Method async sendModuleHierarchyImportedBy ### Signature ```ts async sendModuleHierarchyImportedBy(module: LeanModule): Promise ``` ### Parameters - **module** (LeanModule) - Required - module name + uri ### Returns `Promise` ### Result Types ```ts export type ModuleHierarchyImportedByResult = | { kind: 'Success'; imports: LeanImport[] } | { kind: 'StoppedClient' } | { kind: 'Unsupported' } ``` ### Notes Returns `{ kind: 'StoppedClient' }` if the client is not running and `{ kind: 'Unsupported' }` if `leanServerCapabilities().moduleHierarchyProvider` is undefined. Uses LSP method `$/lean/moduleHierarchy/importedBy`. ``` -------------------------------- ### $/lean/prepareModuleHierarchy Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/endpoints.md Prepares the module hierarchy for a document. Returns the root module or undefined. ```APIDOC ## [REQUEST] $/lean/prepareModuleHierarchy ### Description Prepares the module hierarchy for a document. Returns the root module or undefined. ### Method Request ### Endpoint `$/lean/prepareModuleHierarchy` ### Parameters #### Request Body - **textDocument** (object) - Required - Contains the document URI. - **uri** (DocumentUri) - Required - The URI of the document. ### Request Example ```json { "textDocument": { "uri": "file:///path/to/file.lean" } } ``` ### Response #### Success Response - **result** (LeanModule | undefined) - The root module of the hierarchy, or undefined. #### Response Example ```json { "result": {} } ``` ``` -------------------------------- ### sendModuleHierarchyImports(module) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Sends a request to get the imports of a module in the module hierarchy. Returns a tagged union result. ```APIDOC ## [METHOD] sendModuleHierarchyImports ### Description Sends a request to get the imports of a module in the module hierarchy. Returns a tagged union result. ### Method async sendModuleHierarchyImports ### Signature ```ts async sendModuleHierarchyImports(module: LeanModule): Promise ``` ### Parameters - **module** (LeanModule) - Required - module name + uri ### Returns `Promise` ### Result Types ```ts export type ModuleHierarchyImportsResult = | { kind: 'Success'; imports: LeanImport[] } | { kind: 'StoppedClient' } | { kind: 'Unsupported' } ``` ### Notes Returns `{ kind: 'StoppedClient' }` if the client is not running and `{ kind: 'Unsupported' }` if `leanServerCapabilities().moduleHierarchyProvider` is undefined. Uses LSP method `$/lean/moduleHierarchy/imports`. ``` -------------------------------- ### EditorRpcApi Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/types.md RPC bridge API for editor requests. Extends EditorApi with methods to start, await, and cancel client requests. ```APIDOC ## EditorRpcApi ### Description RPC bridge API for editor requests. Extends EditorApi with methods to start, await, and cancel client requests. ### Methods #### startClientRequest(uri, method, params, options?) - **uri** (string) - Required - Document URI - **method** (string) - Required - RPC method name - **params** (any) - Required - Parameters for the method - **options** (ClientRequestOptionsRpc) - Optional - Request options (excluding abortSignal) - **Returns**: Promise - Request ID #### awaitClientRequest(id) - **id** (number) - Required - Request ID from startClientRequest - **Returns**: Promise - Result of the request #### cancelClientRequest(id) - **id** (number) - Required - Request ID to cancel - **Returns**: Promise ``` -------------------------------- ### Serve infoview files with viteStaticCopy Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Copy infoview JavaScript files and codicon.ttf to the appropriate destinations. ```ts // vite.config.ts import { viteStaticCopy } from 'vite-plugin-static-copy' import { normalizePath } from 'vite' import path from 'node:path' export default { plugins: [ viteStaticCopy({ targets: [ { src: [ normalizePath(path.resolve(__dirname, './node_modules/lean4monaco/node_modules/@leanprover/infoview/dist/*')), normalizePath(path.resolve(__dirname, './node_modules/lean4monaco/dist/webview/webview.js')), ], dest: 'infoview' }, { src: [ normalizePath(path.resolve(__dirname, './node_modules/lean4monaco/node_modules/@leanprover/infoview/dist/codicon.ttf')) ], dest: 'assets' } ] }) ] } ``` -------------------------------- ### initializeResult Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Returns the LSP InitializeResult, or undefined when not running. ```APIDOC ## initializeResult ### Description Returns the LSP InitializeResult, or undefined when not running. ### Method initializeResult (getter) ### Returns - `InitializeResult | undefined` - The initialize result, or `undefined` if not running. ``` -------------------------------- ### serverCapabilities() Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/lean-client.md Returns the LSP ServerCapabilities from the initialize result, or undefined before the server initializes or after stop. ```APIDOC ## [METHOD] serverCapabilities ### Description Returns the LSP ServerCapabilities from the initialize result, or undefined before the server initializes or after stop. ### Method serverCapabilities ### Signature ```ts serverCapabilities(): ServerCapabilities | undefined ``` ### Parameters None ### Returns `ServerCapabilities | undefined` ``` -------------------------------- ### Troubleshooting: monaco-vscode-api error Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Error message shown when multiple versions of the npm package monaco-vscode-api are installed. Ensure only one version is present. ```text this._configurationService.onDidChangeConfiguration is not a function ``` -------------------------------- ### Error Handling with displayNotification Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/monaco-lean-client.md When the Lean server replies with an error, the strategy shows a notification and still calls next(message) to continue the language client's normal pipeline. ```ts // When the Lean server replies with an error, the strategy shows: displayNotification("Error", message.error.message) // and still calls next(message), so the language client's normal pipeline continues. ``` -------------------------------- ### initialHtml method Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/infowebview.md Generates the initial HTML document for the iframe. It includes the provided stylesheet, links to CSS files, and loads the webview script. ```typescript private initialHtml(stylesheet: string) { return ` Infoview
` } ``` -------------------------------- ### Publish npm package Source: https://github.com/hhu-adam/lean4monaco/blob/main/README.md Bump the version with npm version patch and publish the package. ```bash npm version patch npm publish ``` -------------------------------- ### Rpc.register method Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/rpc.md Registers procedures that the other side can invoke. Must be called exactly once; a second call throws an error. Starts an initialize handshake every 50 ms until the other side replies. ```TypeScript /** Register procedures that the other side of the channel can invoke. Must be called exactly once. */ register(methods: T): void { if (this.initialized) throw new Error('RPC methods already registered') this.methods = { ...methods } as any const interval = setInterval(() => { this.sendMessage({ kind: 'initialize' }) }, 50) const prevResolveInit = this.resolveInit this.resolveInit = () => { clearInterval(interval) prevResolveInit() } this.initialized = true } ``` -------------------------------- ### LeanClient (class) Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/README.md The LeanClient class is an LSP client wrapper that manages the connection to the Lean language server. It provides methods for sending requests and notifications. ```APIDOC ## LeanClient (class) ### Description The LeanClient class is an LSP client wrapper that manages the connection to the Lean language server. It provides methods for sending requests and notifications. ### Module `src/vscode-lean4/vscode-lean4/src/leanclient.ts` ### Re-exported at root? Yes ``` -------------------------------- ### Catch errors from raw LSP request, RPC session call, and startup Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/errors.md Shows how to catch errors in consumer code for three scenarios: raw LSP request via client.sendRequest, RPC session call via session.call, and startup via leanMonaco.start. The only typed error payloads exported are RpcError/RpcErrorCode/isRpcError from @leanprover/infoview-api; everything else is plain Error/string rejections or notifications. For RPC session calls, check isRpcError(err) and err.code === RpcErrorCode.WorkerCrashed; the next connect() reconnects automatically. For startup, catch errors like Error('Unimplemented worker ...') from window.MonacoEnvironment.getWorker. ```TypeScript import { isRpcError } from '@leanprover/infoview-api' // or use structural checks // raw LSP request try { const res = await client.sendRequest('$/lean/rpc/call', params) } catch (reason) { if (reason === 'No connection to Lean') { // server/client not running — start it first: await client.restart() } else { console.error('RPC failed', reason) } } // RPC session call try { const goals = await session.call('Lean.Widget.getInteractiveGoals', { params }) } catch (err) { if (isRpcError(err) && err.code === RpcErrorCode.WorkerCrashed) { // session is now failed; the next connect() reconnects automatically } else { throw err } } // startup const leanMonaco = new LeanMonaco() try { await leanMonaco.start(options) } catch (err) { // e.g. Error('Unimplemented worker ...') from window.MonacoEnvironment.getWorker console.error('lean4monaco failed to start', err) } ``` -------------------------------- ### make method signature Source: https://github.com/hhu-adam/lean4monaco/blob/main/_autodocs/api-reference/infowebview.md Signature of the make method. It takes an EditorRpcApi and a stylesheet string, and returns a new IFrameInfoWebview. ```typescript make(editorRpcApi: EditorRpcApi, stylesheet: string) { ```