### Install AutoHotkey2 LSP Server Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md Download and install the AutoHotkey2 LSP server using Node.js and a provided installation script. Ensure Node.js is installed first. ```shell mkdir vscode-autohotkey2-lsp cd vscode-autohotkey2-lsp curl.exe -L -o install.js https://raw.githubusercontent.com/thqby/vscode-autohotkey2-lsp/main/tools/install.js node install.js ``` -------------------------------- ### Array Class Declaration File Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/05-configuration.md Example of a declaration file (.d.ahk) for the built-in Array class, providing type definitions for external use. It demonstrates extending a base class and defining a method signature. ```ahk ; array.d.ahk ; #ClsName represents the ahk built-in class /** @extends {#Array} */ class Array { /** Array filtering function */ Filter(FilterFunc) => Array } ``` -------------------------------- ### Completion Provider Example Usage Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/04-lsp-providers.md Demonstrates how to import and use the completionProvider function with provided parameters and a cancellation token. ```typescript import { completionProvider } from './common'; const items = await completionProvider(params, cancellationToken); ``` -------------------------------- ### ahk2.debug.configs Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Enables the selection from saved debug configurations to start a debugging session. This command allows users to choose pre-defined debugging setups. ```APIDOC ## ahk2.debug.configs ### Description Enables selection from saved debug configurations to start a debugging session. ### Method Not applicable (Command) ### Parameters None explicitly listed, but the underlying function `beginDebug('c')` suggests initiation via configurations. ``` -------------------------------- ### Function Parameter Mismatch Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Shows an example of a function call with an incorrect number of parameters, specifically too many for the Array constructor. ```ahk Array(1, 2, 3) ; Error: Array constructor takes 0 parameters ``` -------------------------------- ### ahk2.debug.file Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Starts the debugging session for the current script. This command is available when debuggers are available in the environment. ```APIDOC ## ahk2.debug.file ### Description Starts debugging the current script. This command is available when debuggers are available. ### Method Not applicable (Command) ### Parameters None explicitly listed, but the underlying function `beginDebug('f')` suggests a file-based debug initiation. ``` -------------------------------- ### Syntax Error Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Demonstrates a syntax error due to an invalid token sequence, specifically missing braces or a condition. ```ahk if x ; Missing braces or condition y := 1 ``` -------------------------------- ### Get All Modules Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Retrieves an array of all parsed modules within the workspace, starting from a given lexer. ```typescript function getAllModules(lex: Lexer): Module[] ``` -------------------------------- ### Extension Activation Entry Point Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md The main entry point for the VS Code extension, called when the extension loads. It's responsible for initializing the language client and starting the extension. ```typescript export async function activate(context: ExtensionContext) ``` ```typescript import { ExtensionContext } from 'vscode'; export async function activate(context: ExtensionContext) { // Extension starts here const client = new LanguageClient(/* ... */); await client.start(); } ``` -------------------------------- ### getAllModules(lex: Lexer): Module[] Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Retrieves an array of all parsed modules (files) within the workspace, starting from the given lexer. ```APIDOC ## getAllModules(lex: Lexer): Module[] ### Description Retrieves an array of all parsed modules (files) within the workspace, starting from the given lexer. ### Parameters #### Path Parameters - **lex** (Lexer) - Required - The starting lexer. ### Returns Array of all parsed modules. ``` -------------------------------- ### Undefined Symbol Error Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Illustrates an error where a symbol (function in this case) is not found in the current scope. ```ahk x := UndefinedFunc() ; Error: UndefinedFunc not found ``` -------------------------------- ### Custom Format Provider Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Implements a custom formatting rule to ensure comments have at least two spaces before them. Requires Lexer and FormatOptions from './common'. ```typescript import { FormatOptions, TextEdit } from 'vscode-languageserver' import { Lexer } from './common' function customFormat(lex: Lexer, options: FormatOptions): TextEdit[] { const edits: TextEdit[] = [] // Add custom formatting rules for (const token of lex.tokens) { if (token.type === TokenType.Comment) { // Ensure comments have at least 2 spaces before them const prevToken = token.previous_token if (prevToken) { const endPos = lex.document.positionAt(prevToken.offset + prevToken.length) const tokenPos = lex.document.positionAt(token.offset) if (endPos.line === tokenPos.line) { const spaceBefore = tokenPos.character - endPos.character if (spaceBefore < 2) { edits.push( TextEdit.replace( { start: endPos, end: tokenPos }, ' ' ) ) } } } } } return edits } ``` -------------------------------- ### Get Signature Help Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Provides signature help for functions at a specific cursor position. This helps users understand and correctly use function parameters. ```typescript getSignatureHelp(position: Position): SignatureHelp | undefined ``` -------------------------------- ### Configure coc.nvim for AutoHotkey v2 LSP Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md Add this JSON configuration to your coc.nvim configuration file to enable the AutoHotkey v2 language server. Ensure the module path points to your installed server. ```json { "languageserver": { "lsp-ahk2": { "module": "/server/dist/server.js", "filetypes": ["autohotkey"], "args": ["--node-ipc"], "initializationOptions": { // Same as initializationOptions for Sublime Text4 } } } } ``` -------------------------------- ### Local Same as Global Warning Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Shows a warning where a local variable declaration shadows a global variable with the same name. ```ahk global x fn() { x := 1 ; Warning: shadows global x } ``` -------------------------------- ### TypeScript: Example Usage of getCallInfo Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Shows how to retrieve and log the parameter count and the index of the current parameter being edited using `getCallInfo`. ```typescript const info = getCallInfo(lex, position); if (info) { console.log('Parameter count:', info.count); console.log('Current param:', info.comma.length); } ``` -------------------------------- ### Unreachable Code Warning Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Illustrates a warning for code that appears after an unconditional return statement within a function. ```ahk fn() { return x y := 1 ; Warning: unreachable code } ``` -------------------------------- ### Get Inlay Hints Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Fetches inlay hints, such as parameter names or type hints, for a given range. This can improve code readability by providing contextual information inline. ```typescript getInlayHints(range: Range): InlayHint[] ``` -------------------------------- ### Multilingual Support Reference Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/05-configuration.md Example of referencing a locale-specific declaration file for multilingual support. This uses a reference directive to load appropriate language definitions based on the A_Locale variable. ```ahk ;@reference array.%A_Locale%.d.ahk ``` -------------------------------- ### Variable Unset Warning Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Illustrates a warning where a variable might be used before it has been assigned a value, depending on conditional logic. ```ahk if condition x := 1 y := x ; Warning: x may be unset if condition is false ``` -------------------------------- ### Folding Range Provider Method Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/04-lsp-providers.md Shows how to get folding ranges directly from the lexer instance, supporting various folding features. ```typescript lex.getFoldingRanges(): FoldingRange[] ``` -------------------------------- ### TypeScript: Example Usage of getParamCount Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Demonstrates how to use `getParamCount` to check if the number of provided arguments matches the expected parameter count for a function. ```typescript const count = getParamCount(myFunc); if (args.length !== count) { // Parameter count mismatch } ``` -------------------------------- ### Example Declaration File for Array Class Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md This snippet shows a declaration file for the Array class, defining its Filter method. It uses JSDOC-style annotations and specifies the generic type T. ```ahk ; array.d.ahk ; #ClsName represents the ahk built-in class /** @extends {#Array} */ class Array { /** jsdoc-default */ Filter(FilterFunc) => Array } ``` -------------------------------- ### activate(context: ExtensionContext): Promise Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md The main extension entry point called by VS Code when the extension loads. It initializes the language client, registers commands, sets up the status bar, configures the output channel, registers event listeners, and loads extension configuration. ```APIDOC ## activate(context: ExtensionContext): Promise ### Description Main extension entry point called by VS Code when the extension loads. Initializes the language client with the server, registers all commands, sets up the status bar, configures the output channel, registers event listeners, and loads extension configuration. ### Parameters #### Path Parameters - **context** (ExtensionContext) - Required - VS Code extension context ### Request Example ```typescript import { ExtensionContext } from 'vscode'; export async function activate(context: ExtensionContext) { // Extension starts here const client = new LanguageClient(/* ... */); await client.start(); } ``` ``` -------------------------------- ### Enhance Custom Hover Provider Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Extend the default hover provider to include additional details about symbols in AutoHotkey v2 scripts. This example adds information about class inheritance and function parameters. ```typescript import { Hover, Position } from 'vscode-languageserver' import { findSymbol, getSymbolDetail, Lexer } from './common' export function enhancedHoverProvider(position: Position, lex: Lexer): Hover | undefined { // Get base hover from default provider const baseHover = hoverProvider(position, lex) if (!baseHover) return undefined // Get the symbol at position const { symbol } = lex.getContext(position) if (!symbol) return baseHover // Add custom information let content = baseHover.contents as string if (symbol.kind === 5) { // Class const baseClass = (symbol as ClassNode).base if (baseClass) { content += `\n\n**Extends:** ${baseClass.name}` } } if (symbol.kind === 6) { // Function const funcNode = symbol as FuncNode content += `\n\n**Parameters:** ${funcNode.params.length}` content += `\n**Local Vars:** ${Object.keys(funcNode.local).length}` } return { ...baseHover, contents: content } } ``` -------------------------------- ### English Diagnostic Message Examples Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md These are examples of English diagnostic messages that use placeholders for dynamic content. ```plaintext "'{\'name\'}\' is not defined" ``` ```plaintext "'Expect '{\'expected\'}\' but got '{\'actual\'}''" ``` ```plaintext "'Function takes {count} parameters, got {actual}"' ``` -------------------------------- ### Chinese Diagnostic Message Examples Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md These are examples of Chinese diagnostic messages that use placeholders for dynamic content, demonstrating localization. ```plaintext "'{\'name\'}\' 未定义" ``` ```plaintext "'期望 '{\'expected\'}\' 但得到 '{\'actual\'}''" ``` ```plaintext "'函数需要 {count} 个参数,但得到 {actual} 个"' ``` -------------------------------- ### Quick Help Command Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Opens AutoHotkey documentation and navigates to the keyword under the cursor. Enabled when not in a web context. ```typescript quickHelp() ``` -------------------------------- ### Filter and Log Parameter Errors in Language Server Code Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Demonstrates how to access and filter diagnostics within the language server code itself. This example specifically logs parameter errors by filtering diagnostics with the 'call' code. ```typescript const diags = lex.diagnostics; diags.filter(d => d.code === DiagnosticCode.call) .forEach(diag => { console.log('Parameter error:', diag.message); }) ``` -------------------------------- ### Handle Configuration Changes Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Illustrates how to listen for configuration changes in VS Code and react to updates that affect the AutoHotkey v2 extension. ```typescript workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration('AutoHotkey2')) { // Re-read and resend to server } }) ``` -------------------------------- ### initLocalize(): Promise Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Loads localization strings from resource files. This asynchronous function prepares the language server for localized output. ```APIDOC ## initLocalize(): Promise ### Description Load localization strings from resource files. ### Method Promise ### Parameters None ``` -------------------------------- ### Get Localized String Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Retrieves a localized string based on a key, with support for argument substitution. This function returns a function that can be called to get the final formatted string. ```typescript const msg = localize('ahk2.run')(); const formatted = localize('ahk2.current', 'v2.0')('Current: v2.0'); ``` -------------------------------- ### getColorPresentation Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Gets color representations within a specified range for a given color. ```APIDOC ## getColorPresentation(range: Range, color: Color) ### Description Get color representations at range. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript getColorPresentation(range: Range, color: Color) ``` ### Response #### Success Response - **ColorPresentation[]**: Array of ColorPresentation objects. #### Response Example ```typescript ColorPresentation[] ``` ``` -------------------------------- ### ahk2.select.syntaxes Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Allows selection of custom syntax definition files. This command is enabled for 'ahk2' files and when not in a web environment. ```APIDOC ## ahk2.select.syntaxes ### Description Allows selection of custom syntax definition files. Enabled when the editor language is 'ahk2' and not in a web environment. ### Method Not applicable (Command) ### Parameters None. ``` -------------------------------- ### Sublime Text 4 LSP Configuration Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md Configure Sublime Text 4 to use the AutoHotkey2 LSP client. This involves installing the Sublime LSP plugin and defining client settings, including the command to run the server and language selectors. ```json { "clients": { "lsp-ahk2": { "enabled": true, "command": [ "node", "/server/dist/server.js", "--stdio" ], // Update the path of node.exe(maybe it's already in PATH, so you don't need to set it) and the folder of vscode-autohotkey2-lsp "selector": "source.ahk2", // Same as scope in AutoHotkey2.sublime-syntax "schemes": ["file", "buffer", "res"], "initializationOptions": { "locale": "en-us", // or "zh-cn" "fullySemanticToken": true, // Provide more semantic tokens "AutoLibInclude": "Disabled", // or "Local" or "User and Standard" or "All" "CommentTags": ">=;;\\s*(?.+)", "CompleteFunctionParens": false, "Diagnostics": { "ClassStaticMemberCheck": true, "ParamsCheck": true }, "ActionWhenV1IsDetected": "Continue", "FormatOptions": { "array_style": "none", // or "collapse" or "expand" "break_chained_methods": false, "ignore_comment": false, "indent_string": "\t", "max_preserve_newlines": 2, "brace_style": "One True Brace", // or "Allman" or "One True Brace Variant" "object_style": "none", // or "collapse" or "expand" "preserve_newlines": true, "space_after_double_colon": true, "space_before_conditional": true, "space_in_empty_paren": false, "space_in_other": true, "space_in_paren": false, "wrap_line_length": 0 }, "InterpreterPath": "C:/Program Files/AutoHotkey/v2/AutoHotkey.exe", "WorkingDirs": [], "SymbolFoldingFromOpenBrace": false } } }, "semantic_highlighting": true } ``` -------------------------------- ### Get Definition Location Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Finds the location(s) of the definition for the symbol at the specified position. ```typescript getDefinition(position: Position): Location | Location[] ``` -------------------------------- ### ahk2.help Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Opens the AutoHotkey documentation and navigates to the keyword currently under the cursor. This command is enabled when the editor language is 'ahk2' and the environment is not a web context. ```APIDOC ## ahk2.help ### Description Opens AutoHotkey documentation and jumps to the keyword under the cursor. Enabled when the editor language is 'ahk2' and not in a web environment. ### Method Not applicable (Command) ### Parameters None. ``` -------------------------------- ### getParamCount Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Gets the number of parameters for a function node. This count excludes ByRef markers. ```APIDOC ## getParamCount(func: FuncNode): number ### Description Get function parameter count. ### Parameters #### Path Parameters - **func** (FuncNode) - Required - Function node ### Returns Number of parameters (excluding ByRef markers). ``` -------------------------------- ### Get Document Symbols Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Retrieves all document symbols, typically used for populating an outline view. ```typescript const symbols = lex.getDocumentSymbols(); ``` -------------------------------- ### Single-Point Imports for LSP Providers Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/04-lsp-providers.md Demonstrates how to import multiple LSP providers from a single common export file, simplifying the import process. ```typescript import { completionProvider, hoverProvider, defintionProvider, // ... etc } from './common'; ``` -------------------------------- ### loadSyntax(name?: string, priority?: number): void Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Loads a syntax definition file (.d.ahk) with an optional name and priority. Supports built-in syntaxes like 'ahk2', 'ahk2_h', and 'winapi'. ```APIDOC ## loadSyntax(name?: string, priority?: number): void ### Description Loads a syntax definition file (.d.ahk) with an optional name and priority. Supports built-in syntaxes like 'ahk2', 'ahk2_h', and 'winapi'. ### Parameters #### Path Parameters - **name** (string) - Optional - Syntax file name or path - **priority** (number) - Optional - Load priority (lower = first) ### Example ```typescript loadSyntax(); // Load default v2 syntax loadSyntax('ahk2_h'); // Load v2.1 H syntax ``` ``` -------------------------------- ### Configure nvim-lspconfig for AutoHotkey v2 LSP Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md This Lua configuration sets up the AutoHotkey v2 LSP for nvim-lspconfig. It specifies the command to run the server and interpreter path, and customizes attach behavior. ```lua local function custom_attach(client, bufnr) require("lsp_signature").on_attach({ bind = true, use_lspsaga = false, floating_window = true, fix_pos = true, hint_enable = true, hi_parameter = "Search", handler_opts = { "double" }, }) end local ahk2_configs = { autostart = true, cmd = { "node", vim.fn.expand("$HOME/vscode-autohotkey2-lsp/server/dist/server.js"), "--stdio" }, filetypes = { "ahk", "autohotkey", "ah2" }, init_options = { locale = "en-us", InterpreterPath = "C:/Program Files/AutoHotkey/v2/AutoHotkey.exe", -- Same as initializationOptions for Sublime Text4, convert json literal to lua dictionary literal }, single_file_support = true, flags = { debounce_text_changes = 500 }, capabilities = capabilities, on_attach = custom_attach, } local configs = require "lspconfig.configs" configs["ahk2"] = { default_config = ahk2_configs } local nvim_lsp = require("lspconfig") nvim_lsp.ahk2.setup({}) ``` -------------------------------- ### Unused Symbol Warning Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Demonstrates a hint that a variable declared within a function is never used. ```ahk fn() { x := 1 ; Hint: x is never used } ``` -------------------------------- ### Select Syntaxes Command Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Allows selection of custom syntax definition files for AutoHotkey v2. ```typescript selectSyntaxes() ``` -------------------------------- ### getInlayHints Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Fetches inlay hints, such as parameter names and type hints, for a given range. ```APIDOC ## getInlayHints(range: Range) ### Description Get inlay hints (parameter names, type hints). ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript getInlayHints(range: Range) ``` ### Response #### Success Response - **InlayHint[]**: Array of InlayHint objects. #### Response Example ```typescript InlayHint[] ``` ``` -------------------------------- ### Virtual Reference Error Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Shows an error where a literal value is attempted to be referenced using the address-of operator. ```ahk x := &5 ; Error: cannot reference literal ``` -------------------------------- ### Get Class Constructor Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Retrieves the constructor method (`__Init`) of a class. Returns undefined if the class has no explicit constructor. ```typescript function getClassConstructor(cls: ClassNode): FuncNode | undefined ``` -------------------------------- ### Load Syntax Definition Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Loads a syntax definition file (.d.ahk) with an optional priority. Built-in syntaxes like 'ahk2' and 'winapi' are available. ```typescript function loadSyntax( name?: string, priority?: number ): void ``` ```typescript loadSyntax(); // Load default v2 syntax ``` ```typescript loadSyntax('ahk2_h'); // Load v2.1 H syntax ``` -------------------------------- ### Get Class Base Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Retrieves the direct base class of a given class. Useful for traversing inheritance chains. ```typescript function getClassBase(cls: ClassNode): ClassNode | undefined ``` ```typescript let current = myClass; while (current) { console.log(current.name); current = getClassBase(current); // Traverse inheritance chain } ``` -------------------------------- ### Signature Help Provider Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/04-lsp-providers.md Provides signature help for functions and methods, displaying parameter information, active parameter tracking, and documentation. ```APIDOC ## Signature Help Provider ### Description Provides signature help for functions and methods, displaying parameter information, active parameter tracking, and documentation. ### Method Signature ```typescript function signatureProvider(position: Position, lex: Lexer): SignatureHelp | undefined ``` ### Parameters #### Path Parameters - **position** (Position) - Required - Cursor position - **lex** (Lexer) - Required - Current lexer instance ### Returns SignatureHelp with active parameter and signatures. ### Features - Function parameter display - Method signature help - Parameter highlighting - Active parameter tracking - Documentation for parameters ``` -------------------------------- ### Importing Public APIs Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/_MANIFEST.txt Demonstrates how to import public APIs from the common module for external use and extension. ```typescript import { findSymbol, completionProvider, ... } from './common' ``` -------------------------------- ### Get Specific Class Member Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Retrieves a specific class member by its name. Returns undefined if the member is not found. ```typescript function getClassMember( cls: ClassNode, name: string ): AhkSymbol | undefined ``` -------------------------------- ### Get Hover Information Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Fetches hover information for the symbol at the given position. Returns undefined if no information is available. ```typescript const hover = lex.getHover(position); if (hover) { return hover; } ``` -------------------------------- ### findSymbol Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Finds a symbol by its name within a specified scope. This function can optionally start the search from a given position. ```APIDOC ## findSymbol(lex: Lexer, name: string, searchPos?: Position, searchScope?: AhkSymbol): AhkSymbol | undefined ### Description Find symbol by name in scope. ### Parameters #### Path Parameters - **lex** (Lexer) - Required - Current lexer - **name** (string) - Required - Symbol name to find - **searchPos** (Position) - Optional - Position to start search - **searchScope** (AhkSymbol) - Optional - Scope to search in ### Returns Symbol or undefined if not found. ``` -------------------------------- ### ByRef Parameter Violation Example Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/09-error-handling.md Demonstrates an error where a literal value is passed to a function parameter that requires a variable (ByRef). ```ahk fn(byRef x) {} fn(5) ; Error: literal cannot be passed ByRef ``` -------------------------------- ### Create File System Watcher Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Creates a file system watcher to monitor for new, changed, or deleted .ahk files. This is essential for real-time updates related to script files. ```typescript const fsw = workspace.createFileSystemWatcher('**/*.{ahk}'); ``` -------------------------------- ### Autohotkey2 LSP Import Information Interface Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Details the structure for tracking import sources, tokens, wildcards, variables, modules, and aliases. ```typescript interface Import { imp: Array<{ from: string // Import source file k: Token // Token in source wildcard: Wildcard // None | Import | Export var: Variable[] // Imported symbols }> mod?: Record // Imported modules alias?: Record // Import aliases } ``` -------------------------------- ### Apply Dynamic Configuration Update Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Applies a new language server configuration, validating the InterpreterPath and triggering a reparse of open documents. Requires updateConfig and LSConfig from './common'. ```typescript import { updateConfig, LSConfig } from './common' async function applyNewConfiguration(newConfig: LSConfig) { // Validate configuration if (!newConfig.InterpreterPath) { console.error('InterpreterPath is required') return false } // Apply configuration updateConfig(newConfig) // Trigger reparse of open documents for (const [uri, lex] of Object.entries(lexers)) { lex.update() } return true } ``` -------------------------------- ### Get Rename Range Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Determines the range of a symbol that can be renamed at a specific cursor position. Returns undefined if renaming is not possible. ```typescript getRenameRange(position: Position): Range | undefined ``` -------------------------------- ### Initialize Localization Strings Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Loads localization strings from resource files. This is an asynchronous operation that prepares the language server for localized output. ```typescript async function initLocalize(): Promise ``` -------------------------------- ### Get Symbol References Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Finds all references to a symbol at the given position. The 'includeDeclaration' parameter controls whether the declaration itself is included. ```typescript getReferences(position: Position, includeDeclaration?: boolean): Location[] ``` -------------------------------- ### Get Symbol Context Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Retrieves the symbol context at a specific cursor position. The 'forCompletion' parameter can optimize for completion requests. ```typescript const lex = lexers[uri]; const { token, symbol, word } = lex.getContext(position); ``` -------------------------------- ### Get Color Presentation Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Retrieves different ways a color can be represented within a given range. Useful for color pickers and formatters. ```typescript getColorPresentation(range: Range, color: Color): ColorPresentation[] ``` -------------------------------- ### ahk2.debug.params Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Initiates a debugging session after prompting the user for command-line parameters. This provides flexibility by allowing runtime arguments to be specified. ```APIDOC ## ahk2.debug.params ### Description Prompts for command-line parameters before starting a debugging session. ### Method Not applicable (Command) ### Parameters None explicitly listed, but the underlying function `beginDebug('p')` suggests initiation with parameters. ``` -------------------------------- ### Get Completion Items Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Retrieves an array of completion items for a given cursor position. Useful for providing code suggestions to the user. ```typescript getCompletionItems(position: Position): CompletionItem[] ``` -------------------------------- ### Use Localized Strings Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Demonstrates how to import and use the `localize` function to retrieve localized strings within your extension code. ```typescript import { localize } from './extension'; const msg = localize('ahk2.run'); ``` -------------------------------- ### VSCode AutoHotkey2 LSP Module Graph Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/01-project-overview.md Illustrates the architecture of the VSCode AutoHotkey2 LSP, showing the connection between the VS Code extension, the Language Client, and the Language Server with its various components. ```text Extension (VS Code) ├── registerCommonFeatures() ├── LanguageClient └── LSP Protocol <--> Language Server ├── Lexer (parser & analyzer) ├── Providers (completion, hover, definition, etc.) ├── Symbol Management ├── Type System └── AHK Provider (Windows-only, for built-in library info) ``` -------------------------------- ### parseUserLib(): void Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Parses user-defined and standard AutoHotkey libraries, populating the library symbol cache. ```APIDOC ## parseUserLib(): void ### Description Parses user-defined and standard AutoHotkey libraries, populating the library symbol cache. ### Example ```typescript parseUserLib(); ``` ``` -------------------------------- ### Get Symbol Detail Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Retrieves detailed, markdown-formatted information about a symbol. Includes signature, parameters, return type, JSDoc, and source location. ```typescript function getSymbolDetail( sym: AhkSymbol, brief?: boolean ): string ``` -------------------------------- ### LSConfig Interface Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/02-types-reference.md Defines the complete language server configuration, including initialization options and VS Code settings. ```typescript interface LSConfig { // Initialization options only locale?: string commands?: string[] extensionUri?: string fullySemanticToken?: boolean CompletionTriggerCharacters?: string // Settings (from VS Code configuration) ActionWhenV1IsDetected?: ActionType AutoLibInclude: LibIncludeType CommentTags?: string CompleteFunctionParens?: boolean CompletionCommitCharacters?: { Class?: string Function?: string } CompletionKindSortOrder?: string[] Diagnostics?: { ClassNonDynamicMemberCheck?: boolean InvokeCheck?: string[] } ExplicitContextOnly?: boolean Files?: { Exclude?: string[] MaxDepth?: number } FormatOptions?: FormatOptions InlayHints?: { ParameterNames?: boolean SuppressWhenArgumentMatchesName?: boolean } InterpreterPath: string GlobalStorage?: string Syntaxes?: string SymbolFoldingFromOpenBrace?: boolean Warn?: { Unused?: boolean VarUnset?: boolean LocalSameAsGlobal?: boolean CallWithoutParentheses?: boolean | 1 } WorkingDirs: string[] } ``` -------------------------------- ### Get All Class Members Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Retrieves all accessible members of a given class, optionally including inherited members. Useful for inspecting class structure. ```typescript function getClassMembers( cls: ClassNode, includeBase?: boolean ): Record ``` ```typescript const members = getClassMembers(myClass, true); const filter = members['Filter']; // Array.Filter method ``` -------------------------------- ### Get Document Colors Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Finds all color information within the entire document. This can be used to generate a color palette or perform color-related refactoring. ```typescript getDocumentColors(): ColorInformation[] ``` -------------------------------- ### ahk2.run Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Runs the current script file directly. It can also be configured to run only the selected code snippet if the `selection` parameter is set to true. ```APIDOC ## ahk2.run ### Description Runs the current script file directly. If a selection is active and the `selection` parameter is true, it will run only the selected code. ### Method Not applicable (Command) ### Parameters - **editor** (TextEditor) - Required - The current text editor instance. - **selection** (boolean) - Optional - If true, run selected code only. ``` -------------------------------- ### getSignatureHelp Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Provides signature help for functions at a given cursor position, displaying parameter information. ```APIDOC ## getSignatureHelp(position: Position) ### Description Get function signature help. ### Method Not applicable (SDK method) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript getSignatureHelp(position: Position) ``` ### Response #### Success Response - **SignatureHelp | undefined**: SignatureHelp object showing function parameters. #### Response Example ```typescript SignatureHelp | undefined ``` ``` -------------------------------- ### traverseInclude Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Traverses the include chain. This function starts with a given lexer and executes a callback for each included file, allowing for processing of the include hierarchy. ```APIDOC ## traverseInclude(lex: Lexer, callback: (lex: Lexer, isIncluded: boolean) => any): any ### Description Traverse include chain. ### Parameters #### Path Parameters - **lex** (Lexer) - Required - Starting lexer - **callback** (function) - Required - Called for each included file ### Returns Result from callback. ``` -------------------------------- ### Listen for Configuration Changes and Reformat Documents Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Listens for changes to the 'AutoHotkey2.FormatOptions' configuration. When changes are detected, it logs the new indent string and triggers a reformat command for all visible AHK2 documents. ```typescript import { workspace } from 'vscode' workspace.onDidChangeConfiguration(event => { if (event.affectsConfiguration('AutoHotkey2.FormatOptions')) { console.log('Format options changed') const formatConfig = workspace.getConfiguration('AutoHotkey2.FormatOptions') console.log('New indent:', formatConfig.indent_string) // Trigger reformatting of open documents window.visibleTextEditors.forEach(editor => { if (editor.document.languageId === 'ahk2') { commands.executeCommand('editor.action.formatDocument', editor.document.uri) } }) } }) ``` -------------------------------- ### Get Enum Member Names Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Retrieves the string names of enum members from a given enum object. Ensure the input is a valid enum record. ```typescript function enumNames(e: T): string[] ``` ```typescript const tokenTypeNames = enumNames(TokenType); // ["EOF", "Comma", "Dot", ...] ``` -------------------------------- ### Localized Declaration File for Array Class (Chinese) Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md This snippet demonstrates a localized declaration file for the Array class, specifically for Chinese (zh-cn). It mirrors the structure of the default declaration file but includes Chinese comments. ```ahk ; array.zh-cn.d.ahk ; #ClsName 表示ahk内置类 /** @extends {#Array} */ class Array { /** jsdoc-zh */ Filter(FilterFunc) => Array } ``` -------------------------------- ### Read Workspace Configuration Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Shows how to access VS Code workspace configuration settings for the AutoHotkey v2 extension, such as interpreter path and formatting options. ```typescript const config = workspace.getConfiguration('AutoHotkey2'); const interpreterPath = config.get('InterpreterPath'); const formatOptions = config.get('FormatOptions'); ``` -------------------------------- ### Get Folding Ranges Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Retrieves code folding ranges for regions, classes, functions, and blocks. This allows the editor to offer code collapsing functionality. ```typescript getFoldingRanges(): FoldingRange[] ``` -------------------------------- ### Extension Configuration Defaults Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Defines default editor settings for AutoHotkey v2 files, including the default formatter and quick suggestion preferences. ```json { "[ahk2]": { "editor.defaultFormatter": "thqby.vscode-autohotkey2-lsp", "editor.quickSuggestions": { "other": true, "comments": false, "strings": true } } } ``` -------------------------------- ### Get Semantic Tokens Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Generates semantic tokens for syntax highlighting, providing more detailed information than basic tokenization. An optional range can be provided to limit the scope. ```typescript getSemanticTokens(range?: Range): SemanticTokens ``` -------------------------------- ### Continuation Section with Standard Alignment Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/server/src/test/formatting/continuation_section.txt Shows a basic continuation section where parentheses are aligned with the variable and content is indented. ```autohotkey if 1 { a := ' ( Parentheses are aligned with a, and the first two lines are indented by one level. The line be indented by two level. )' b := ' (ltrim Parentheses are aligned with b, and all line are indented by one level. )' ;@format align_continuation_section_with_ltrim0_to_left: false c := ' (ltrim0 Parentheses are aligned with c, and other lines remain unchanged. )' ;@format align_continuation_section_with_ltrim0_to_left: true d := ' (ltrim0 Parentheses are left-aligned, and other lines remain unchanged. )' } ``` -------------------------------- ### Configuration and Workspace Caches Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Caches for language server configuration, library directories, and open workspace folders. These are crucial for initializing and operating the LSP. ```typescript export const configCache: LSConfig // Current configuration export const libDirs: string[] // Library search paths export const workspaceFolders: string[] // Open workspace folders ``` -------------------------------- ### Traverse Include Chain Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Recursively traverses the include chain starting from a given lexer. A callback function is executed for each file in the chain, indicating whether it was included. ```typescript function traverseInclude( lex: Lexer, callback: (lex: Lexer, isIncluded: boolean) => any ): any ``` ```typescript traverseInclude(lex, (fileLex, isIncluded) => { console.log(fileLex.uri, isIncluded ? 'included' : 'main'); }); ``` -------------------------------- ### Handle Debug Extension Changes Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Listens for changes in installed VS Code extensions to automatically detect and integrate with compatible debug adapters, such as the AutoHotkey debug extension. ```typescript extensions.onDidChange(updateExtensionsInfo) ``` -------------------------------- ### Handle Runtime Configuration Updates Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/05-configuration.md Listens for configuration changes from the client and updates the server's settings accordingly. This involves re-reading configuration, updating cached lexers, and re-running diagnostics if necessary. ```typescript connection.onDidChangeConfiguration(async change => { // Re-read configuration from client const settings = await connection.workspace.getConfiguration('AutoHotkey2'); updateConfig(settings); }) ``` -------------------------------- ### TypeScript: Get Function Parameter Count Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Retrieves the number of parameters a function accepts, excluding special parameters like `this` or `super`. Useful for validating function calls. ```typescript function getParamCount(func: FuncNode): number ``` -------------------------------- ### Register LSP Providers Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/04-lsp-providers.md All Language Server Protocol providers are registered in `connection.ts` during the initialization phase of the language server. ```typescript connection.onCompletion(completionProvider) connection.onHover((params) => hoverProvider(params.position, lex)) connection.onDefinition((params) => defintionProvider(params.position, lex)) ``` -------------------------------- ### Syntax Declaration File Configuration Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/05-configuration.md Configuration snippet for setting a custom syntax declaration file path within VS Code settings. This allows the language server to use specific syntax definitions. ```json { "AutoHotkey2.Syntaxes": "path/to/syntax.d.ahk" } ``` -------------------------------- ### Get Code Actions Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/03-lexer-parser.md Fetches applicable code actions, such as rename, remove unused, or convert blocks, for a specified range and context. This enables automated code modifications. ```typescript getCodeActions(range: Range, context?: CodeActionContext): CodeAction[] ``` -------------------------------- ### Read Formatting Configuration Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Retrieves formatting configuration options from a cache. Provides default values if none are found. Requires configCache and FormatOptions from './common'. ```typescript import { configCache, FormatOptions } from './common' function getFormatConfig(): FormatOptions { return configCache.FormatOptions || { indent_string: '\t', array_style: 0, object_style: 0, space_in_paren: false, preserve_newlines: true } } function getDiagnosticConfig() { return { checkClassMembers: configCache.Diagnostics?.ClassNonDynamicMemberCheck ?? true, checkParamCount: configCache.Diagnostics?.InvokeCheck?.includes('ParamCount') ?? false, checkByRef: configCache.Diagnostics?.InvokeCheck?.includes('ByrefParam') ?? false } } // Usage const formatOpts = getFormatConfig() console.log(`Using indent: '${formatOpts.indent_string}'`) ``` -------------------------------- ### JsDoc Annotations for AutoHotkey v2 Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/README.md Demonstrates the use of JsDoc-style annotations for type hinting and documentation within AutoHotkey v2 code. Supports type definitions for parameters, return values, variables, and COM objects. ```js /** * @param {Array} a - a param * @return {Integer} */ fn(a*) { /** @type {Map} */ d := Map() /** * @var {Map} e * @var {Object} f */ e := Map(), f := {} /** @type {(a,b)=>Integer} */ cb := (a, b) => a + b /** @type {ComObject} */ wb := ComObject('Excel.Sheet.12') return a[1] + a[2] } class abc { /** @type {Map} */ p := dosomethingandreturnmap() } ``` -------------------------------- ### TypeScript: Get Function Call Information Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/07-symbol-resolution.md Obtains detailed parameter information for a function call at a specific cursor position within the code. Returns parameter positions and counts. ```typescript function getCallInfo( lex: Lexer, position: Position ): ParamInfo | undefined ``` -------------------------------- ### Re-exporting Utilities from Common Module Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Demonstrates how to re-export all utilities from a common module for convenient single-line imports. This simplifies the import process for consumers of the library. ```typescript export * from './lexer' export * from './lexer2' export * from './types' export * from './lsp-enums' export * from './completionProvider' export * from './hoverProvider' // ... all providers and utilities ``` ```typescript import { resolvePath, readTextFile, findSymbol, parseProject, loadSyntax, // ... etc } from './common' ``` -------------------------------- ### Find Functions by Prefix Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Filters symbols within a Lexer to find functions whose names start with a specified prefix, case-insensitively. Returns an array of matching function nodes. ```typescript import { SymbolKind } from './common' function findFunctionsByPrefix(lex: Lexer, prefix: string): FuncNode[] { const symbols = lex.children.filter(s => s.kind === SymbolKind.Function && s.name.toLowerCase().startsWith(prefix.toLowerCase()) ) return symbols as FuncNode[] } // Usage const classes = findAllClassesInFile(lex) console.log(`Found ${classes.length} classes`) const utilFuncs = findFunctionsByPrefix(lex, 'Util') console.log('Utility functions:', utilFuncs.map(f => f.name)) ``` -------------------------------- ### localize(key: string, ...args: any[]): (...args: any[]) => string Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Retrieves a localized string based on a key, with support for argument substitution. This function returns a callable that can format the string with provided arguments. ```APIDOC ## localize(key: string, ...args: any[]): (...args: any[]) => string ### Description Get localized string with substitution support. ### Method (...args: any[]) => string ### Parameters #### Path Parameters - **key** (string) - Required - The localization key. - **args** (any[]) - Optional - Arguments for substitution. ### Example ```typescript const msg = localize('ahk2.run')(); const formatted = localize('ahk2.current', 'v2.0')('Current: v2.0'); ``` ``` -------------------------------- ### ahk2.compile Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/06-extension-api.md Compiles the current script into an executable (EXE) file. The compilation process utilizes the `AutoHotkey2.CompilerCMD` setting for configuration. ```APIDOC ## ahk2.compile ### Description Compiles the current script to an EXE file. The compilation process uses the `AutoHotkey2.CompilerCMD` setting. ### Method Not applicable (Command) ### Parameters - **editor** (TextEditor) - Required - The current text editor instance. ``` -------------------------------- ### initCaches(): void Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/08-utility-functions.md Initializes or resets all parser caches, including completion items, library symbols, hover information, and type caches in lexers. This function is called on language server initialization, when changing the AutoHotkey interpreter, and on configuration changes. ```APIDOC ## initCaches(): void ### Description Initializes or resets all parser caches. ### Method void ### Parameters None ### Called - On language server initialization - When changing AutoHotkey interpreter - On configuration change ``` -------------------------------- ### Add Custom Code Action Provider Source: https://github.com/thqby/vscode-autohotkey2-lsp/blob/main/_autodocs/10-examples.md Implement a custom code action provider to add specific refactoring options to AutoHotkey v2 scripts. This example shows how to add type annotations to functions. ```typescript import { CodeAction, CodeActionContext, CodeActionKind, Range } from 'vscode-languageserver' import { Lexer } from './common' export function myCustomProvider( lex: Lexer, range: Range, context: CodeActionContext ): CodeAction[] { const actions: CodeAction[] = [] // Get all symbols in the range const symbols = lex.children.filter(sym => sym.range.start.line >= range.start.line && sym.range.end.line <= range.end.line ) // Create action to convert all functions to have explicit types if (symbols.some(s => s.kind === 6)) { // 6 = SymbolKind.Function actions.push({ title: 'Add type annotations to functions', kind: CodeActionKind.Refactor, edit: { changes: { [lex.uri]: [ // TextEdit objects here ] } } }) } return actions } ``` ```typescript connection.onCodeAction((params) => { const lex = lexers[params.textDocument.uri.toLowerCase()] if (!lex) return [] return [ ...codeActionProvider(lex, params.range, params.context), ...myCustomProvider(lex, params.range, params.context) ] }) ```