### LspStdioConfig Start Method Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspStdioConfig/start.html This method initializes and starts an LSP client with the provided configuration. ```APIDOC ## static Future start ### Description Initializes and starts an LSP client with the provided configuration. ### Method static ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **executable** (String) - Required - The path to the LSP executable. - **workspacePath** (String) - Required - The path to the workspace. - **languageId** (String) - Required - The language ID for the LSP. - **capabilities** (LspClientCapabilities) - Optional - Client capabilities for the LSP. - **initializationOptions** (Map) - Optional - Initialization options for the LSP. - **workspaceConfiguration** (Map) - Optional - Workspace configuration for the LSP. - **args** (List?) - Optional - Additional arguments for the LSP process. - **environment** (Map?) - Optional - Environment variables for the LSP process. - **disableWarning** (bool) - Optional - Whether to disable warnings. - **disableError** (bool) - Optional - Whether to disable errors. ### Request Example ```dart // Example usage (assuming LspStdioConfig and LspClientCapabilities are defined) final config = await LspStdioConfig.start( executable: '/path/to/lsp/server', workspacePath: '/path/to/your/workspace', languageId: 'dart', capabilities: LspClientCapabilities(), initializationOptions: {'someOption': 'value'}, ); ``` ### Response #### Success Response (LspStdioConfig) - **config** (LspStdioConfig) - The initialized LspStdioConfig object. #### Response Example ```json // This is a conceptual example, as LspStdioConfig is a Dart object. // The actual return value is a Dart object representing the configuration. { "message": "LSP client configured successfully" } ``` ``` -------------------------------- ### Start LspStdioConfig Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspStdioConfig/start.html Use this method to create and start an LspStdioConfig. It requires the executable path, workspace path, and language ID. Optional parameters allow for custom capabilities, initialization options, workspace configuration, arguments, environment variables, and disabling warnings or errors. ```dart static Future start({ required String executable, required String workspacePath, required String languageId, LspClientCapabilities capabilities = const LspClientCapabilities(), Map initializationOptions = const {}, Map workspaceConfiguration = const {}, List? args, Map? environment, bool disableWarning = false, bool disableError = false, }) async { final config = LspStdioConfig._( executable: executable, languageId: languageId, workspacePath: workspacePath, args: args, environment: environment, disableWarning: disableWarning, disableError: disableError, capabilities: capabilities, initializationOptions: initializationOptions, workspaceConfiguration: workspaceConfiguration, ); await config._startProcess(); return config; } ``` -------------------------------- ### MatchHighlightStyle Usage Example Source: https://pub.dev/documentation/code_forge/latest/code_forge_styling/MatchHighlightStyle-class.html Example demonstrating how to instantiate MatchHighlightStyle with specific text styles for current and other matches. Prefer using const constructors for performance. ```dart matchHighlightStyle: const MatchHighlightStyle( currentMatchStyle: TextStyle( backgroundColor: Color(0xFFFFA726), ), otherMatchStyle: TextStyle( backgroundColor: Color(0x55FFFF00), ), ), ``` -------------------------------- ### Initialization and Lifecycle Methods Source: https://pub.dev/documentation/code_forge/latest/code_forge_scroll/Render2DCodeField-class.html Methods related to the initial setup and lifecycle of render objects. ```APIDOC ## Initialization and Lifecycle Methods ### Description These methods are involved in the initial setup and lifecycle management of render objects. ### Methods #### `scheduleInitialLayout()` Bootstrap the rendering pipeline by scheduling the very first layout. #### `scheduleInitialPaint(ContainerLayer rootLayer)` Bootstrap the rendering pipeline by scheduling the very first paint. #### `scheduleInitialSemantics()` Bootstrap the semantics reporting mechanism by marking this node as needing a semantics update. #### `reassemble()` Cause the entire subtree rooted at the given RenderObject to be marked dirty for layout, paint, etc, so that the effects of a hot reload can be seen, or so that the effect of changing a global debug flag (such as debugPaintSizeEnabled) can be applied. ``` -------------------------------- ### Start LSP Server via WebSocket Source: https://pub.dev/documentation/code_forge/latest Command to start the basedpyright language server using lsp-ws-proxy on a specific port. Ensure you navigate to the lsp-ws-proxy directory first. ```bash cd /Downloads/lsp-ws-proxy_linux # Navigate to the directory where lsp-ws-proxy is located ./lsp-ws-proxy --listen 5656 -- basedpyright-langserver --stdio # Start the pyright language server on port 5656 ``` -------------------------------- ### Get bufferLineRopeStart Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/bufferLineRopeStart.html This getter returns the value of the private _bufferLineRopeStart variable. Use this to access the starting position of the buffer line rope. ```dart int get bufferLineRopeStart => _bufferLineRopeStart; ``` -------------------------------- ### Get Inlay Hints Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/inlayHints.html Retrieves the current list of inlay hints. ```APIDOC ## GET /inlayHints ### Description Returns the current inlay hints. ### Method GET ### Endpoint /inlayHints ### Parameters None ### Request Example None ### Response #### Success Response (200) - **inlayHints** (List) - A list of current inlay hints. #### Response Example ```json { "inlayHints": [ { "label": "variableName", "position": { "line": 10, "character": 5 }, "textEdits": [] } ] } ``` ``` -------------------------------- ### Example: Adding Background Line Decoration Source: https://pub.dev/documentation/code_forge/latest/code_forge_styling/LineDecoration-class.html Demonstrates how to add a background decoration to a range of lines using the LineDecoration class. ```APIDOC ## Example: Git diff added lines ```dart controller.addLineDecoration(LineDecoration( startLine: 10, endLine: 15, type: LineDecorationType.background, color: Colors.green.withOpacity(0.2), )); ``` ``` -------------------------------- ### Example: Breakpoint Icon Source: https://pub.dev/documentation/code_forge/latest/code_forge_styling/GutterDecoration-class.html Shows how to add a red circle icon decoration to a specific line to represent a breakpoint. ```dart controller.addGutterDecoration(GutterDecoration( startLine: 25, endLine: 25, type: GutterDecorationType.icon, color: Colors.red, icon: Icons.circle, )); ``` -------------------------------- ### ScrollPhysics applyTo Example Snippet Source: https://pub.dev/documentation/code_forge/latest/code_forge_code_area/RTLAwareScrollPhysics/applyTo.html A code snippet demonstrating the use of the applyTo method. ```APIDOC ## DELETE /api/users/{id} ### Description Deletes a user account. ### Method DELETE ### Endpoint /api/users/{id} ### Parameters #### Path Parameters - **id** (string) - Required - The unique identifier of the user to delete. ### Response #### Success Response (204) No content is returned upon successful deletion. #### Response Example (No content) ``` -------------------------------- ### findLineStart Method Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/findLineStart.html The findLineStart method calculates the starting index of the line that contains the provided offset. ```APIDOC ## findLineStart Method ### Description Finds the start of the line containing `offset`. ### Method N/A (This appears to be a method within a class, not a standalone API endpoint) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Return Value** (int) - The starting index of the line. #### Response Example N/A ## Implementation ```dart int findLineStart(int offset) => _rope.findLineStart(offset); ``` ``` -------------------------------- ### Get Line Start Offset Source: https://pub.dev/documentation/code_forge/latest/code_forge_rope/Rope/getLineStartOffset.html Returns the starting offset for a given line index. If the line index is invalid, it defaults to 0. ```dart int getLineStartOffset(int lineIndex) { final start = _lineStartByIndex(lineIndex); return start == -1 ? 0 : start; } ``` -------------------------------- ### Get Length Implementation Source: https://pub.dev/documentation/code_forge/latest/code_forge_rope/BiDiSegment/length.html Use this getter to calculate the length based on start and end values. Ensure 'end' and 'start' are defined in the scope. ```dart int get length => end - start; ``` -------------------------------- ### Initialize LSP Configuration Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspStdioConfig-class.html Create an async method to initialize the LSP configuration by starting the language server. This method handles potential errors during initialization. ```dart Future _initLsp() async { try { final config = await LspStdioConfig.start( executable: '/home/athul/.nvm/versions/node/v20.19.2/bin/pyright-langserver', args: ['--stdio'] workspacePath: '/home/athul/Projects/lsp', languageId: 'python', ); return config; } catch (e) { debugPrint('LSP Initialization failed: $e'); return null; } } ``` -------------------------------- ### Get Line Start Offset in Dart Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/getLineStartOffset.html Calculates the character offset where a line starts. `lineIndex` is zero-based. This method is useful for navigating text buffers and determining the exact position of line beginnings. ```dart int getLineStartOffset(int lineIndex) { if (_bufferLineIndex != null && _bufferDirty) { final newLines = '\n'.allMatches(_bufferLineText!).length; if (newLines > 0) { if (lineIndex == _bufferLineIndex!) { return _bufferLineRopeStart; } else if (lineIndex > _bufferLineIndex! && lineIndex <= _bufferLineIndex! + newLines) { final lines = _bufferLineText!.split('\n'); int offset = _bufferLineRopeStart; for (int i = 0; i < lineIndex - _bufferLineIndex!; i++) { offset += lines[i].length + 1; } return offset; } else if (lineIndex > _bufferLineIndex! + newLines) { final delta = _bufferLineText!.length - _bufferLineOriginalLength; return _rope.getLineStartOffset(lineIndex - newLines) + delta; } } else { if (lineIndex == _bufferLineIndex!) return _bufferLineRopeStart; if (lineIndex > _bufferLineIndex!) { final delta = _bufferLineText!.length - _bufferLineOriginalLength; return _rope.getLineStartOffset(lineIndex) + delta; } } } return _rope.getLineStartOffset(lineIndex); } ``` -------------------------------- ### Get canRedo Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_undo_redo/UndoRedoController/canRedo.html Returns true if the redo stack is not empty, indicating that redo is available. No setup is required. ```dart bool get canRedo => _redoStack.isNotEmpty; ``` -------------------------------- ### Initialize Stdio LSP Client Source: https://pub.dev/documentation/code_forge/latest Asynchronously start an LSP server using stdio configuration. This method requires the executable path, arguments, workspace path, and language ID. It returns a Future that resolves to an LspConfig. ```dart Future _initLsp() async { try { final config = await LspStdioConfig.start( executable: '/home/athul/.nvm/versions/node/v20.19.2/bin/basedpyright-langserver', args: ['--stdio'], workspacePath: '/home/athul/Projects/lsp', languageId: 'python', ); return config; } catch (e) { debugPrint('LSP Initialization failed: $e'); return null; } } ``` -------------------------------- ### Get Foldings Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/foldings.html Retrieves the map of all fold ranges detected in the document. The map is keyed by the start line index. ```APIDOC ## GET /foldings ### Description Retrieves the map of all fold ranges detected in the document, keyed by start line index. ### Method GET ### Endpoint /foldings ### Parameters None ### Response #### Success Response (200) - **foldings** (Map) - A map where keys are the start line indices and values are FoldRange objects or null. ``` -------------------------------- ### Initialize and Use CodeForgeController Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController-class.html Demonstrates initializing the controller, setting its text content, accessing selection, retrieving specific lines, and performing code folding/unfolding operations. ```dart final controller = CodeForgeController(); controller.text = 'void main() { print("Hello"); }'; // Access selection print(controller.selection); // Get specific line print(controller.getLineText(0)); // 'void main() { // Fold/unfold code controller.foldAll(); controller.unfoldAll(); ``` -------------------------------- ### Get Foldings Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/foldings.html Retrieves the map of all fold ranges detected in the document. This map is keyed by the start line index. ```dart Map get foldings => _foldings; ``` -------------------------------- ### Connect Method Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspSocketConfig/connect.html Initializes the LSP server. This method is intended for internal use by the `CodeCrafter` widget and should not be called directly. Direct calls may lead to server instability if invoked multiple times. ```APIDOC ## connect() ### Description Initializes the LSP server. This method is used internally by the `CodeCrafter` widget. Calling it directly is not recommended and may crash the LSP server if called multiple times. ### Method `Future` ### Endpoint N/A (Internal Method) ### Parameters None ### Request Body None ### Response None ### Implementation Details Listens to the `_channel` stream, decodes incoming JSON data, and adds it to the `_responseController`. Throws a `FormatException` if the received data is not valid JSON. ``` -------------------------------- ### Get Document Version Source: https://pub.dev/documentation/code_forge/latest/code_forge_syntax_highlighter/SyntaxHighlighter/documentVersion.html Use this getter to retrieve the current document version. No specific setup is required beyond the class definition. ```dart int get documentVersion => _documentVersion; ``` -------------------------------- ### Get caseSensitive Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_find_controller/FindController/caseSensitive.html Retrieves the current state of the case sensitivity for the search. No specific setup is required beyond having an instance of the class. ```dart bool get caseSensitive => _caseSensitive; ``` -------------------------------- ### Initialize CodeForgeController with LSP Config Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/CodeForgeController.html Initializes the controller, connects to the LSP server if a socket configuration is provided, initializes the LSP if not already done, and opens the current document. Includes error handling for initialization. ```dart CodeForgeController({this.lspConfig}) { if (lspConfig != null) { (() async { try { if (lspConfig is LspSocketConfig) { await (lspConfig! as LspSocketConfig).connect(); } if (!lspConfig!.isInitialized) { await lspConfig!.initialize(); } if (openedFile != null) { await _openDocumentInLsp(); } } catch (e) { debugPrint('Error initializing LSP: $e'); } finally { _listeners.add(_highlightListener); } })(); _lspResponsesSubscription = lspConfig!.responses.listen((data) async { try { if (data['method'] == 'workspace/applyEdit') { final Map? params = data['params']; if (params != null && params.isNotEmpty) { if (params.containsKey('edit')) { await applyWorkspaceEdit(params); } } } if (data['method'] == 'workspace/configuration') { final id = data['id']; await lspConfig!.sendResponse(id, [ lspConfig!.workspaceConfiguration, ]); } if (data['method'] == 'textDocument/publishDiagnostics') { final List rawDiagnostics = data['params']?['diagnostics'] ?? []; if (rawDiagnostics.isNotEmpty) { final List errors = []; for (final item in rawDiagnostics) { if (item is! Map) continue; int severity = item['severity'] ?? 0; if (severity == 1 && lspConfig!.disableError) { severity = 0; } if (severity == 2 && lspConfig!.disableWarning) { severity = 0; } if (severity > 0) { errors.add( LspErrors( severity: severity, range: item['range'], message: item['message'] ?? '', ), ); } } if (!_isDisposed) diagnosticsNotifier.value = errors; _codeActionTimer?.cancel(); _codeActionTimer = Timer( const Duration(milliseconds: 250), () async { if (errors.isEmpty) { if (!_isDisposed) codeActionsNotifier.value = null; return; } int minStartLine = errors .map((d) => d.range['start']?['line'] as int? ?? 0) .reduce((a, b) => a < b ? a : b); int minStartChar = errors .map((d) => d.range['start']?['character'] as int? ?? 0) .reduce((a, b) => a < b ? a : b); int maxEndLine = errors .map((d) => d.range['end']?['line'] as int? ?? 0) .reduce((a, b) => a > b ? a : b); int maxEndChar = errors .map((d) => d.range['end']?['character'] as int? ?? 0) .reduce((a, b) => a > b ? a : b); try { final actions = await lspConfig!.getCodeActions( filePath: openedFile!, startLine: minStartLine, startCharacter: minStartChar, endLine: maxEndLine, endCharacter: maxEndChar, diagnostics: rawDiagnostics.cast>(), ); if (!_isDisposed) codeActionsNotifier.value = actions; } catch (e) { debugPrint('Error fetching code actions: $e'); } }, ); } else { if (!_isDisposed) diagnosticsNotifier.value = []; } } if (data['method'] == r'$ccls/publishSemanticHighlight') { final params = data['params'] as Map?; if (params != null) { final uri = params['uri'] as String?; final symbols = params['symbols'] as List?; if (uri != null && openedFile != null && uri.endsWith(openedFile!.split('/').last) && symbols != null) { _usesCclsSemanticHighlight = true; final tokens = _convertCclsSymbolsToTokens(symbols); if (!_isDisposed) { semanticTokens.value = (tokens, _semanticTokensVersion++); } } } } } catch (e, st) { debugPrint('Error handling LSP response: $e\n$st'); } }); } else { _listeners.add(() async { _debounceTimer?.cancel(); _debounceTimer = Timer(const Duration(milliseconds: 200), () async { if (text != _previousValue) { _wordCache = await compute(CodeForgeController._extractWords, text); } _previousValue = text; }); }); } } ``` -------------------------------- ### LSP Server Initialization Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspConfig/initialize.html The `initialize` method is crucial for setting up the LSP server. It configures essential parameters like process ID, root URI, workspace folders, initialization options, and capabilities. It also handles potential initialization errors and processes the server's capabilities, including semantic token information. This method is intended for internal use and direct calls are not advised. ```APIDOC ## POST /lsp/initialize ### Description Initializes the LSP server with necessary configuration. ### Method POST ### Endpoint /lsp/initialize ### Request Body - **processId** (integer) - Required - The process ID of the client. - **rootUri** (string) - Required - The root URI of the workspace. - **workspaceFolders** (array of objects) - Required - An array containing workspace folder information. - **uri** (string) - Required - The URI of the workspace folder. - **name** (string) - Required - The name of the workspace folder. - **initializationOptions** (object) - Optional - Custom initialization options. - **capabilities** (object) - Required - The client's capabilities. ### Request Example ```json { "processId": 12345, "rootUri": "file:///path/to/workspace", "workspaceFolders": [ { "uri": "file:///path/to/workspace", "name": "workspace" } ], "initializationOptions": {}, "capabilities": {} } ``` ### Response #### Success Response (200) - **capabilities** (object) - The server's capabilities. - **semanticTokensProvider** (object) - Information about the semantic token provider. - **legend** (object) - The legend for semantic tokens. - **tokenTypes** (array of strings) - List of supported token types. - **tokenModifiers** (array of strings) - List of supported token modifiers. #### Response Example ```json { "result": { "capabilities": { "semanticTokensProvider": { "legend": { "tokenTypes": ["variable", "function"], "tokenModifiers": ["static"] } } } } } ``` #### Error Response (e.g., 500) - **error** (object) - Details about the initialization error. - **code** (integer) - The error code. - **message** (string) - A message describing the error. #### Error Response Example ```json { "error": { "code": -32602, "message": "Initialization failed: Invalid parameters" } } ``` ``` -------------------------------- ### Dart Getter for Calculated Property Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspSemanticToken/end.html Use a getter to provide read-only access to a computed property. This example calculates the end position based on start and length. ```dart int get end => start + length; ``` -------------------------------- ### Static Methods Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspStdioConfig-class.html Static methods for initializing and configuring the LSP client. ```APIDOC ## POST /start ### Description Initializes and starts the LSP server. ### Method POST ### Endpoint /start ### Parameters #### Request Body - **executable** (String) - Required - The path to the LSP executable. - **workspacePath** (String) - Required - The path to the workspace. - **languageId** (String) - Required - The language identifier. - **capabilities** (LspClientCapabilities) - Optional - Client capabilities. - **initializationOptions** (Map) - Optional - Initialization options for the server. - **workspaceConfiguration** (Map) - Optional - Workspace configuration. - **args** (List) - Optional - Arguments to pass to the LSP executable. - **environment** (Map) - Optional - Environment variables for the LSP process. - **disableWarning** (bool) - Optional - Disable warnings. - **disableError** (bool) - Optional - Disable errors. ### Request Example ```json { "executable": "/path/to/lsp/server", "workspacePath": "/path/to/workspace", "languageId": "dart", "capabilities": {}, "initializationOptions": {}, "workspaceConfiguration": {}, "args": ["--enable-analytics"], "environment": {"DEBUG": "true"}, "disableWarning": false, "disableError": false } ``` ### Response #### Success Response (200) - **LspStdioConfig** - Configuration for the LSP server. #### Response Example ```json { "process": "lsp_process_info", "stdio": "stdio_config_details" } ``` ``` -------------------------------- ### Get isReplaceMode Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_find_controller/FindController/isReplaceMode.html Retrieves the current boolean value indicating if the replace mode is active. No specific setup is required beyond the property's existence. ```dart bool get isReplaceMode => _isReplaceMode; ``` -------------------------------- ### Get BiDi Segments for a Line Source: https://pub.dev/documentation/code_forge/latest/code_forge_rope/Rope/getBiDiSegmentsForLine.html Use this method to obtain BiDi segments for a specific line index. It calculates the line's start and end offsets and then retrieves the segments within that range. ```dart List getBiDiSegmentsForLine(int lineIndex) { final lineStart = getLineStartOffset(lineIndex); final lineEnd = findLineEnd(lineStart); return getBiDiSegmentsInRange(lineStart, lineEnd); } ``` -------------------------------- ### showInlayHints Method Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/showInlayHints.html Fetches and displays inlay hints from the LSP server for the visible range in the editor. It temporarily sets the editor to read-only mode while hints are displayed. ```APIDOC ## showInlayHints ### Description Shows inlay hints in the editor. This fetches inlay hints from the LSP server for the visible range and displays them inline in the code. Sets readOnly to true while hints are visible to prevent user input. Inlay hints show type annotations (kind: 1) and parameter names (kind: 2). ### Method Future ### Endpoint N/A (This is a method call within a client-side application) ### Parameters None ### Request Example ```dart // Call this when Ctrl+Alt is pressed await controller.showInlayHints(); ``` ### Response #### Success Response N/A (This method returns void and modifies the editor state) #### Response Example N/A ``` -------------------------------- ### Get Semantic Token Mapping Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/getSemanticMapping.html Retrieves the semantic token mapping for a given language ID, applying server-specific overrides to the standard mapping. Includes commented-out examples for potential language-specific overrides. ```dart /// Get the semantic token mapping for a specific language server. /// Returns the standard mapping with any server-specific overrides applied. Map> getSemanticMapping(String languageId) { final baseMap = Map>.from(semanticToHljs); // Apply language-specific overrides switch (languageId) { // case 'rust': // baseMap.addAll(rustAnalyzerOverrides); // break; // case 'typescript': // case 'javascript': // // typescript-language-server follows standard mappings // break; } return baseMap; } ``` -------------------------------- ### Initialize LSP Server with Connect Method Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspSocketConfig/connect.html Initializes the LSP server by listening to the channel stream and decoding JSON responses. Avoid calling this method directly as it's intended for internal use by the CodeCrafter widget and may cause instability if invoked multiple times. ```dart Future connect() async { _channel.stream.listen((data) { try { final json = jsonDecode(data as String); _responseController.add(json); } catch (e) { throw FormatException('Invalid JSON response: $data', e); } }); } ``` -------------------------------- ### bufferLineRopeStart Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/bufferLineRopeStart.html Provides details on the bufferLineRopeStart property, including its type and how it is implemented. ```APIDOC ## bufferLineRopeStart Property ### Description An integer property that indicates the starting position of a buffer line rope. ### Type `int` ### Implementation ```dart int get bufferLineRopeStart => _bufferLineRopeStart; ``` ``` -------------------------------- ### Declare 'start' Property in Dart Source: https://pub.dev/documentation/code_forge/latest/code_forge_styling/SearchHighlight/start.html This snippet shows the declaration of the 'start' property as a final integer. It represents the starting offset of highlighted text. ```dart final int start; ``` -------------------------------- ### Initialize and Use CodeForgeController Source: https://pub.dev/documentation/code_forge/latest Initializes the CodeForgeController and demonstrates basic text operations, selection manipulation, and line management. Requires instantiation of the controller. ```dart final controller = CodeForgeController(); // Text operations controller.text = 'Hello, World!'; String content = controller.text; controller.getLineText(int lineIndex); controller.insertText(String text, int line, int character); controller.insertAtCurrentCursor(String text); // Selection & modification controller.selection = TextSelection(baseOffset: 0, extentOffset: 5); controller.selectAll(); controller.copy(); controller.cut(); controller.paste(); // Line operations int lineCount = controller.lineCount; String line = controller.getLineText(0); int lineStart = controller.getLineStartOffset(0); controller.duplicateLine(); controller.moveLineDown(); controller.moveLineUp(); controller.backspace(); controller.delete(); ``` -------------------------------- ### Set Ghost Text Example Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/setGhostText.html Example of how to set ghost text with specific line, column, text, and style. ```dart controller.setGhostText(GhostText( line: 10, column: 15, text: 'print("Hello, World!");', style: TextStyle( color: Colors.grey.withOpacity(0.5), fontStyle: FontStyle.italic, ), )); ``` -------------------------------- ### LspSignatureHelps Class Overview Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspSignatureHelps-class.html Provides details about the LspSignatureHelps class, its constructors, properties, and methods. ```APIDOC ## LspSignatureHelps Class ### Description Represents signature help information from a language server. ### Constructors #### LspSignatureHelps ```dart LspSignatureHelps({ required int activeParameter, required int activeSignature, required String documentation, required String label, required List> parameters, }) ``` ### Properties - **activeParameter** (int) - The index of the currently active parameter. - **activeSignature** (int) - The index of the currently active signature. - **documentation** (String) - Documentation for the signature help. - **label** (String) - The label for the signature help. - **parameters** (List>) - A list of parameters for the signature help. - **hashCode** (int) - The hash code for this object. - **runtimeType** (Type) - A representation of the runtime type of the object. ### Methods - **noSuchMethod**(Invocation invocation) → dynamic - Invoked when a nonexistent method or property is accessed. - **toString**() → String - A string representation of this object. ### Operators - **operator ==**(Object other) → bool - The equality operator. ``` -------------------------------- ### Get Completions API Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspConfig/getCompletions.html This method is used to get code completions at a specific position in a document. It's an internal method of the CodeForge. ```APIDOC ## GET /textDocument/completion ### Description Retrieves code completion suggestions for a given file path, line, and character position. ### Method POST ### Endpoint /textDocument/completion ### Parameters #### Query Parameters None #### Request Body - **filePath** (string) - Required - The path to the file. - **line** (integer) - Required - The line number (0-based). - **character** (integer) - Required - The character position (0-based). ### Request Example ```json { "filePath": "/path/to/your/file.js", "line": 10, "character": 5 } ``` ### Response #### Success Response (200) - **label** (string) - The text of the completion item. - **kind** (integer) - The type of the completion item (e.g., method, function, variable). - **data** (object) - Optional - Additional data associated with the completion item, may contain 'importUris' and 'ref'. - **importUris** (array of strings) - URIs for importing the completion item. - **ref** (string) - A reference to the completion item. #### Response Example ```json { "result": [ { "label": "myFunction", "kind": 3, "data": { "importUris": ["file:///path/to/module.js"], "ref": "myFunctionRef" } } ] } ``` ``` -------------------------------- ### Initialize Search Highlights List Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/searchHighlights.html Initialize an empty list to store search highlights. Add SearchHighlight objects to this list to highlight search results or other text ranges. ```java List searchHighlights = []; ``` -------------------------------- ### Setup Dart LSP with Stdio Source: https://pub.dev/documentation/code_forge/latest Configure the Dart Language Server Protocol using stdio for integration with CodeForge. Ensure the 'dart' executable is in your PATH and specify the workspace path. ```dart Future setupDartLsp() async { return await LspStdioConfig.start( executable: 'dart', args: ['language-server', '--protocol=lsp'], workspacePath: '/path/to/your/project', languageId: 'dart', ); } // In your widget @override Widget build(BuildContext context) { return MaterialApp( home: Scaffold( body: SafeArea( child: FutureBuilder( future: setupDartLsp(), builder: (context, snapshot) { if (snapshot.connectionState == ConnectionState.waiting) { return CircularProgressIndicator(); } return CodeForge( language: langDart, textStyle: GoogleFonts.jetBrainsMono(), controller: CodeForgeController( lspConfig: snapshot.data ), filePath: '/path/to/your/file.dart', // Mandatory field ) }, ), ), ), ); } ``` -------------------------------- ### Find Line Start in Rope Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/findLineStart.html Finds the start of the line containing the specified offset. This method delegates to the underlying rope's findLineStart functionality. ```Dart int findLineStart(int offset) => _rope.findLineStart(offset); ``` -------------------------------- ### BiDi Class Overview Source: https://pub.dev/documentation/code_forge/latest/code_forge_rope/BiDi-class.html This section provides an overview of the BiDi class, its constructors, properties, and methods. ```APIDOC ## BiDi Class Unicode BiDi character ranges and utilities. ### Constructors #### BiDi() - Description: Initializes a new instance of the BiDi class. ### Properties #### hashCode → int - Description: The hash code for this object. - Setter: no setter - Inherited: yes #### runtimeType → Type - Description: A representation of the runtime type of the object. - Setter: no setter - Inherited: yes ``` -------------------------------- ### Initialize CodeForgeController Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/CodeForgeController.html Use this constructor to create an instance of CodeForgeController. Optionally provide LspConfig. ```dart CodeForgeController({ 1. LspConfig? lspConfig, }) ``` -------------------------------- ### Server Management and Commands Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspConfig-class.html Methods for executing commands, initializing, and exiting the LSP server. ```APIDOC ## POST /execute-command ### Description Execute a workspace command on the server. Wrapper around the 'workspace/executeCommand' request. ### Method POST ### Endpoint /execute-command ### Parameters #### Request Body - **command** (String) - Required - The command to execute. - **arguments** (List?) - Optional - Arguments for the command. ### Response #### Success Response (200) - **result** (void) - Indicates the command execution status. ### Response Example ```json { "result": null } ``` ## POST /initialize ### Description Initializes the LSP server. ### Method POST ### Endpoint /initialize ### Parameters #### Request Body - **initializationOptions** (Map) - Optional - Options for server initialization. ### Response #### Success Response (200) - **status** (String) - Indicates the success of the initialization. ### Response Example ```json { "status": "Server initialized successfully" } ``` ## POST /exit ### Description Exits the LSP server process. ### Method POST ### Endpoint /exit ### Response #### Success Response (200) - **status** (String) - Indicates the server exit status. ### Response Example ```json { "status": "Server exited gracefully" } ``` ``` -------------------------------- ### Implement Rope deleteImmutable Method Source: https://pub.dev/documentation/code_forge/latest/code_forge_rope/Rope/deleteImmutable.html Creates a new Rope with text deleted between start and end (immutable). Throws RangeError for invalid ranges. Returns a new Rope instance if start equals end. ```dart Rope deleteImmutable(int start, int end) { if (start < 0 || end < start || end > _length) { throw RangeError('Invalid range: [$start, $end) for length $_length'); } if (start == end) return Rope._fromNode(_root, _length); final first = _split(_root, start); final second = _split(first.right, end - start); final newRoot = _concat(first.left, second.right); return Rope._fromNode(newRoot, _length - (end - start)); } ``` -------------------------------- ### Example Implementation of updateEditingValueWithDeltas Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/updateEditingValueWithDeltas.html This example demonstrates a basic implementation of the `updateEditingValueWithDeltas` method. It iterates through provided deltas and applies them to the local text editing value. Ensure the client has an initial `_localValue` set before calling this method. ```dart class MyClient with DeltaTextInputClient { TextEditingValue? _localValue; @override void updateEditingValueWithDeltas(List textEditingDeltas) { if (_localValue == null) { return; } TextEditingValue newValue = _localValue!; for (final TextEditingDelta delta in textEditingDeltas) { newValue = delta.apply(newValue); } _localValue = newValue; } // ... } ``` -------------------------------- ### SyntaxHighlighter Constructor Source: https://pub.dev/documentation/code_forge/latest/code_forge_syntax_highlighter/SyntaxHighlighter-class.html Initializes a new instance of the SyntaxHighlighter class. ```APIDOC ## SyntaxHighlighter Constructor ### Description Initializes a new instance of the SyntaxHighlighter class. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example None ### Response #### Success Response (200) None #### Response Example None ``` -------------------------------- ### GET /diagnostics Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/diagnostics.html Retrieves a list of all diagnostics available in the editor. ```APIDOC ## GET /diagnostics ### Description Returns the errors, warnings and info available in the editor as a List. Each LspErrors item holds the error severity, range and the message of each errors. ### Method GET ### Endpoint /diagnostics ### Response #### Success Response (200) - **diagnostics** (List) - A list of LspErrors objects. #### Response Example ```json [ { "severity": "error", "range": { "start": {"line": 1, "character": 0}, "end": {"line": 1, "character": 10} }, "message": "Example error message" } ] ``` ``` -------------------------------- ### Initialize CodeForge with WebSocket LSP Source: https://pub.dev/documentation/code_forge/latest Pass the configured LspSocketConfig to the CodeForgeController and then to the CodeForge widget. Specify the theme and file path. ```dart final _controller = CodeForgeController( lspConfig: lspConfig // Pass the LspConfig here. ) CodeForge( controller: _controller, // Pass the controller here. theme: anOldHopeTheme, filePath: "/home/athul/Projects/lsp/example.py" ), ``` -------------------------------- ### GET /workspace/symbol Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspConfig/getWorkspaceSymbols.html Searches for symbols across the entire workspace. ```APIDOC ## GET /workspace/symbol ### Description Searches for symbols across the entire workspace. Used for global symbol search (e.g., Ctrl+T). ### Method GET ### Endpoint /workspace/symbol ### Parameters #### Query Parameters - **query** (String) - Required - The search query string. ### Request Example ```json { "query": "exampleQuery" } ``` ### Response #### Success Response (200) - **result** (List) - A list of symbols found matching the query. #### Response Example ```json { "result": [ { "name": "exampleSymbol", "type": "function", "location": { "uri": "file:///path/to/file.dart", "range": { "start": {"line": 10, "character": 5}, "end": {"line": 10, "character": 15} } } } ] } ``` ``` -------------------------------- ### Implement showInlayHints Method Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/showInlayHints.html This method fetches inlay hints from the LSP server for the visible range and displays them inline. It sets readOnly to true while hints are visible to prevent user input. Inlay hints show type annotations (kind: 1) and parameter names (kind: 2). ```dart Future showInlayHints() async { if (_inlayHintsVisible || lspConfig == null || openedFile == null) return; _inlayHintsVisible = true; readOnly = true; try { final endLine = lineCount > 500 ? 500 : lineCount; final response = await lspConfig!.getInlayHints( openedFile!, 0, 0, endLine, 0, ); final result = response['result']; if (result is List) { _inlayHints = result .whereType>() .map((data) => InlayHint.fromLsp(data)) .toList(); } else { _inlayHints = []; } inlayHintsChanged = true; notifyListeners(); } catch (e) { debugPrint('Error fetching inlay hints: $e'); _inlayHintsVisible = false; readOnly = false; } } ``` -------------------------------- ### Length Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_rope/BiDiSegment/length.html Provides information on how to get the length property and its implementation. ```APIDOC ## Length Property ### Description This property returns the length of an object, calculated as the difference between its end and start points. ### Method GET ### Endpoint `/length` ### Parameters This property does not take any parameters. ### Request Example ```json { "example": "No request body needed for this operation." } ``` ### Response #### Success Response (200) - **length** (int) - The calculated length. #### Response Example ```json { "length": 100 } ``` ## Implementation ```dart int get length => end - start; ``` ``` -------------------------------- ### Constructors Source: https://pub.dev/documentation/code_forge/latest/code_forge_styling/InlayHint-class.html Details on how to create InlayHint objects. ```APIDOC ## Constructors ### InlayHint ```dart InlayHint({required int line, required int column, required String text, required InlayHintKind kind, bool paddingRight = false, bool paddingLeft = false, Map? location}) ``` ### InlayHint.fromLsp Creates an InlayHint from LSP response data. ```dart factory InlayHint.fromLsp(Map data) ``` ``` -------------------------------- ### Get isActive Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_find_controller/FindController/isActive.html Retrieves the current active/visible state of the finder. ```dart bool get isActive => _isActive; ``` -------------------------------- ### Example: Adding Left Border Line Decoration Source: https://pub.dev/documentation/code_forge/latest/code_forge_styling/LineDecoration-class.html Demonstrates how to add a left border decoration to a range of lines, including specifying thickness. ```APIDOC ## Example: Git diff left border ```dart controller.addLineDecoration(LineDecoration( startLine: 10, endLine: 15, type: LineDecorationType.leftBorder, color: Colors.green, thickness: 3, )); ``` ``` -------------------------------- ### Get Lines Property Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/lines.html Retrieves a list of all lines present in the document. ```APIDOC ## GET /lines ### Description Retrieves a list of all lines in the document. ### Method GET ### Endpoint /lines ### Parameters This endpoint does not accept any parameters. ### Response #### Success Response (200) - **lines** (List) - A list containing all lines of the document. #### Response Example { "lines": [ "This is the first line.", "This is the second line.", "And so on..." ] } ``` -------------------------------- ### Initialize and Use CodeForge Editor Source: https://pub.dev/documentation/code_forge/latest/code_forge_code_area/CodeForge-class.html Instantiate a CodeForgeController and use it to create a CodeForge widget. Configure language, folding, gutter, and text styles for the editor. ```dart final controller = CodeForgeController(); CodeForge( controller: controller, language: langDart, enableFolding: true, enableGutter: true, textStyle: TextStyle( fontFamily: 'JetBrains Mono', fontSize: 14, ), ) ``` -------------------------------- ### Get Document Colors Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/documentColors.html Retrieves a list of the current document colors. ```APIDOC ## GET /documentColors ### Description Returns the current document colors. ### Method GET ### Endpoint /documentColors ### Response #### Success Response (200) - **documentColors** (List) - A list of the current document colors. #### Response Example ```json { "documentColors": [ { "red": 255, "green": 0, "blue": 0, "alpha": 1.0 } ] } ``` ``` -------------------------------- ### Initialize and Use CodeForgeController Source: https://pub.dev/documentation/code_forge/latest/index.html Instantiate the CodeForgeController and perform basic text operations. Requires initialization before use. ```dart final controller = CodeForgeController(); // Text operations controller.text = 'Hello, World!'; String content = controller.text; controller.getLineText(int lineIndex); controller.insertText(String text, int line, int character); controller.insertAtCurrentCursor(String text); ``` -------------------------------- ### Create LspSocketConfig Object Source: https://pub.dev/documentation/code_forge/latest/LSP_lsp/LspSocketConfig-class.html Instantiate LspSocketConfig with workspace path, language ID, and server URL. Ensure the server is running at the specified URL. ```dart final lspConfig = LspSocketConfig( workspacePath: "/home/athul/Projects/lsp", languageId: "python", serverUrl: "ws://localhost:5656" ), ``` -------------------------------- ### Get Document Highlights Source: https://pub.dev/documentation/code_forge/latest/code_forge_controller/CodeForgeController/documentHighlights.html Retrieves the current list of document highlights. ```APIDOC ## GET /documentHighlights ### Description Returns the current document highlights. ### Method GET ### Endpoint /documentHighlights ### Response #### Success Response (200) - **documentHighlights** (List) - A list of current document highlights. ``` -------------------------------- ### FoldRange Constructor Source: https://pub.dev/documentation/code_forge/latest/code_forge_code_area/FoldRange/FoldRange.html Creates a FoldRange with the specified start and end line indices. ```APIDOC ## FoldRange Constructor ### Description Creates a FoldRange with the specified start and end line indices. ### Parameters #### Path Parameters - **startIndex** (int) - Required - The starting line index. - **endIndex** (int) - Required - The ending line index. ### Implementation ```dart FoldRange(this.startIndex, this.endIndex); ``` ```