### Usage with (neo)vim - Basic Setup Source: https://github.com/ompugao/patto/blob/master/README.md Guides users on how to start using Patto Note within (neo)vim. It covers setting up the file syntax and triggering LSP features like link and snippet completion. ```vim First, open a file in a workspace with suffix `.pn`, or `:new` and `:set syntax=patto` Then, write your memos. Once you type `[` and `@`, lsp client will complete links and snippets respectively * snippets will only be completed with lsp-oriented snippet plugins such as [vim-vsnip](https://github.com/hrsh7th/vim-vsnip). ``` -------------------------------- ### Run Development Server (Bash) Source: https://github.com/ompugao/patto/blob/master/patto-preview-next/README.md Commands to start the Next.js development server using npm, yarn, pnpm, or bun. These commands initiate a local server for development and hot-reloading. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Install Patto LSP Server from GitHub Release Source: https://github.com/ompugao/patto/blob/master/README.md Provides instructions for downloading pre-compiled binaries of the Patto LSP server from the GitHub releases page. This is an alternative installation method to using Cargo. ```sh Please download binaries from [GitHub release](https://github.com/ompugao/patto/releases) ``` -------------------------------- ### Patto Note Syntax Examples Source: https://github.com/ompugao/patto/blob/master/README.md Demonstrates the various syntax elements of Patto Note, including itemization, task management, decorations, links, code highlighting, and math rendering. Each example showcases a specific feature of the Patto Note format. ```txt Hello world. itemize lines with a leading hard tab `\t' that can be nested the second element #sampleanchor the third element [@quote] quoted text must be indented with `\t' [@table caption="sample table"] header column1 column2 column3 column4 row1 item1 item2 item3 item4 row2 item5 item6 item7 item8 Task Management a task {@task status=todo} another task with deadline {@task status=todo due=2030-12-31T23:59:00} abbreviated version of task !2030-12-31 a completed task {@task status=done} Decoration: [* bold text] [/ italic text] [*/ bold italic text] Links: [other note] link to other note in a workspace [other note#anchor] direct link to an anchored line [#sampleanchor] self note link to the anchored line (i.e., this line) #sampleanchor url link: [https://google.com url title] title and url can be flipped: [url title https://google.com] link to an image [@img https://placehold.co/100.png "alt string"] Code highlight with highlight.js [@code python] import numpy as np print(np.sum(10)) [` inline code `] Math with MathJax inline math: [$ O(n log(n)) $] [@math] O(n^2)\ sum_{i=0}^{10}{i} = 55 ``` -------------------------------- ### Install Patto LSP Server with Cargo Source: https://github.com/ompugao/patto/blob/master/README.md Provides instructions for installing the Patto Language Server Protocol (LSP) server using the Cargo package manager. This is a common method for installing Rust-based command-line tools. ```sh cargo install patto ``` -------------------------------- ### Start Patto Preview Server Source: https://context7.com/ompugao/patto/llms.txt Command to launch the Patto preview server, which provides real-time HTML rendering of Patto notes. It specifies the port for the server and outlines the services it offers, including WebSocket updates and file serving. ```bash # Start preview server on port 3000 patto-preview --port 3000 # The server provides: # - WebSocket endpoint at /ws for real-time updates # - Static file serving at /api/files/*path # - HTML rendering with syntax highlighting and math support ``` -------------------------------- ### Setup Neovim with nvim-lspconfig Source: https://github.com/ompugao/patto/blob/master/README.md This snippet sets up Neovim with nvim-lspconfig and nvim-cmp for LSP support, including the 'patto' plugin and its LSP configuration. ```vim call plug#begin() Plug 'neovim/nvim-lspconfig' Plug 'hrsh7th/cmp-nvim-lsp' Plug 'hrsh7th/nvim-cmp' Plug 'ompugao/patto' call plug#end() lua << EOF require('patto') require('lspconfig.configs').patto_lsp.setup({}) EOF ``` -------------------------------- ### Watch Repository Files and Handle Changes (Rust) Source: https://context7.com/ompugao/patto/llms.txt This Rust code snippet demonstrates how to initialize a Patto repository, subscribe to its messages, and start a file watcher. It processes various repository events such as file changes, additions, removals, scan progress, and backlink updates, printing relevant information to the console. ```rust use patto::repository::{Repository, RepositoryMessage}; use std::path::PathBuf; // Create repository with automatic workspace scanning let root_dir = PathBuf::from("/path/to/notes"); let repository = Repository::new(root_dir); // Subscribe to repository change notifications let mut rx = repository.subscribe(); // Start file watcher for automatic updates tokio::spawn(async move { repository.start_watcher().await }); // Handle repository events while let Ok(msg) = rx.recv().await { match msg { RepositoryMessage::FileChanged(path, metadata, content) => { println!("File changed: {:?}", path); println!("Modified: {}", metadata.modified); println!("Link count: {}", metadata.link_count); }, RepositoryMessage::FileAdded(path, metadata) => { println!("New file added: {:?}", path); }, RepositoryMessage::FileRemoved(path) => { println!("File removed: {:?}", path); }, RepositoryMessage::ScanProgress { scanned, total } => { let percentage = (scanned * 100) / total; println!("Scan progress: {}%", percentage); }, RepositoryMessage::BackLinksChanged(path, back_links) => { println!("Backlinks updated for {:?}: {} links", path, back_links.len()); }, _ => {} } } ``` -------------------------------- ### Setup Vim with vim-lsp Source: https://github.com/ompugao/patto/blob/master/README.md This snippet configures the Vim editor to use the vim-lsp plugin for language server protocol support, specifically integrating the 'patto' plugin. ```vim call plug#begin() Plug 'prabirshrestha/asyncomplete.vim' Plug 'prabirshrestha/asyncomplete-lsp.vim' Plug 'prabirshrestha/vim-lsp' Plug 'ompugao/patto', {'for': 'patto'} call plug#end() ``` -------------------------------- ### Initialize Rust LSP Server for Patto Source: https://context7.com/ompugao/patto/llms.txt Sets up the Language Server Protocol (LSP) server for Patto notes using Rust and the `tower-lsp` crate. It handles initialization, workspace scanning, and integrates with the `patto::repository::Repository` for note management. ```rust use tower_lsp::{LspService, Server}; use patto::repository::Repository; use std::sync::{Arc, Mutex}; struct Backend { client: tower_lsp::Client, repository: Arc>>, // Assume Repository is properly defined elsewhere root_uri: Arc>>, // Assume root_uri is properly defined elsewhere } #[tokio::main] async fn main() { let stdin = tokio::io::stdin(); let stdout = tokio::io::stdout(); let (service, socket) = LspService::new(|client| Backend { client, repository: Arc::new(Mutex::new(None)), // Initialize with None or actual Repository root_uri: Arc::new(Mutex::new(None)), // Initialize with None or actual root URI }); Server::new(stdin, stdout, socket).serve(service).await; } ``` -------------------------------- ### Configure Patto LSP with Neovim (Lua) Source: https://context7.com/ompugao/patto/llms.txt This Lua code snippet demonstrates how to set up the Patto LSP client for Neovim using the `nvim-lspconfig` plugin. It includes basic configuration for the LSP server command, filetypes, and root directory detection. It also shows optional integration with `trouble.nvim` for task management. ```lua -- neovim with nvim-lspconfig require('patto') require('lspconfig.configs').patto_lsp.setup({ cmd = { 'patto-lsp' }, filetypes = { 'patto' }, root_dir = function(fname) return vim.fn.getcwd() end, }) -- Optional: trouble.nvim integration for task management require('trouble').setup() vim.cmd('Trouble patto_tasks') -- Displays tasks sorted by deadline: -- - Overdue -- - Today -- - This Week -- - This Month -- - Later ``` -------------------------------- ### Bash CLI Tools for Patto Rendering Source: https://context7.com/ompugao/patto/llms.txt Provides command-line interface (CLI) tools for converting Patto files (.pn) to Markdown and HTML formats using dedicated renderers. ```bash # Convert Patto to Markdown patto-markdown-renderer input.pn > output.md # Convert Patto to HTML patto-html-renderer input.pn > output.html ``` -------------------------------- ### Rust Parsing and Rendering Patto Text Source: https://context7.com/ompugao/patto/llms.txt Demonstrates parsing Patto syntax into an Abstract Syntax Tree (AST) and then rendering that AST into HTML. Includes error handling for parsing and options for HTML rendering, such as syntax highlighting and math rendering. ```rust use patto::parser::{parse_text, AstNode}; use patto::renderer::{HtmlRenderer, HtmlRendererOptions, Renderer}; // Parse Patto text let input = r#" Title of my note This is an itemized line nested item Code example: [@code rust] fn main() { println!("Hello!"); } [*bold text*] and [/italic text/] Math formula: [$O(n \log n)$] "#; let result = parse_text(input); // Check for parse errors if !result.parse_errors.is_empty() { for error in result.parse_errors { eprintln!("Parse error at line {}: {}", error.location().row, error); } } // Render to HTML let renderer = HtmlRenderer::new(HtmlRendererOptions {}); let mut output = Vec::new(); renderer.format(&result.ast, &mut output)?; let html = String::from_utf8(output)?; // HTML output includes: // - Syntax highlighting for code blocks (highlight.js) // - Math rendering (MathJax) // - Clickable note links // - Properly nested lists // - Styled decorations (bold, italic) ``` -------------------------------- ### Rust LSP Go-to-Definition for Note Links Source: https://context7.com/ompugao/patto/llms.txt Implements the Language Server Protocol (LSP) go-to-definition functionality for Patto's wiki-style note links. It parses the AST, locates wiki links, resolves them to target URIs, and finds specific anchors if specified, returning the location of the definition. ```rust // LSP go-to-definition for note links async fn goto_definition(&self, params: GotoDefinitionParams) -> Result> { let uri = params.text_document_position_params.text_document.uri; let position = params.text_document_position_params.position; // Parse and locate the WikiLink at cursor position let node_route = locate_node_route(&ast, position.line, position.character); // Extract link and optional anchor if let Some((link, anchor)) = find_wikilink(&node_route) { let target_uri = repo.link_to_uri(link, &root_uri); // Find anchored line if anchor specified if let Some(anchor_name) = anchor { let range = repo.ast_map.get(&target_uri) .and_then(|ast| find_anchor(ast, anchor_name)) .map(|line| get_node_range(&line)); return Ok(Some(GotoDefinitionResponse::Scalar( Location::new(target_uri, range) ))); } } Ok(None) } ``` -------------------------------- ### Language Server Protocol (LSP) Integration Source: https://context7.com/ompugao/patto/llms.txt Integrates with the Language Server Protocol to provide intelligent editing features such as auto-completion, go-to-definition, and semantic highlighting. ```APIDOC ## Language Server Protocol (LSP) Integration ### Description Initializes and runs the Language Server Protocol server for Patto Note, enabling advanced text editing features. ### Method `main` (Rust async function) ### Endpoint N/A (Local process) ### Parameters None ### Request Example ```rust use tower_lsp::{LspService, Server}; use patto::repository::Repository; #[tokio::main] async fn main() { let stdin = tokio::io::stdin(); let stdout = tokio::io::stdout(); let (service, socket) = LspService::new(|client| Backend { client, repository: Arc::new(Mutex::new(None)), root_uri: Arc::new(Mutex::new(None)), }); Server::new(stdin, stdout, socket).serve(service).await; } ``` ### Response #### Success Response (200) LSP server runs in the background, communicating with the client editor. #### Response Example N/A ``` -------------------------------- ### Configure Patto LSP with Vim (Vimscript) Source: https://context7.com/ompugao/patto/llms.txt This Vimscript code configures the vim-lsp plugin to integrate with Patto. It specifies the Patto plugin and lists custom commands provided by the Patto LSP, such as aggregating tasks and showing two-hop link networks. ```vimscript " vim-lsp configuration call plug#begin() Plug 'prabirshrestha/vim-lsp' Plug 'ompugao/patto', {'for': 'patto'} call plug#end() " Commands available: " :LspPattoTasks - Aggregate tasks in location window " :LspPattoTwoHopLinks - Show two-hop link network ``` -------------------------------- ### VSCode Extension package.json Command Definitions Source: https://context7.com/ompugao/patto/llms.txt Defines commands within the `package.json` file for the Patto VSCode extension. These commands enable features like task aggregation, workspace scanning, two-hop link visualization, and note preview. ```json { "contributes": { "commands": [ { "command": "patto.tasks", "title": "Patto: Aggregate tasks in the workspace" }, { "command": "patto.scanWorkspace", "title": "Patto: Scan workspace for notes" }, { "command": "patto.twoHopLinks", "title": "Patto: Show two-hop links" }, { "command": "patto.openPreview", "title": "Patto: Open preview" } ] } } ``` -------------------------------- ### Patto Wiki-Style Linking Syntax Source: https://context7.com/ompugao/patto/llms.txt Defines the syntax for creating wiki-style links within Patto notes, including linking to other notes, specific sections within notes, and defining anchors. Supports both full and abbreviated anchor syntax. ```patto Main note This links to [another note] This links to a specific section [another note#section] This links within the same note [#section] Section heading {@anchor section} Content of the section Abbreviated anchor syntax: #abbreviated ``` -------------------------------- ### Preview Server and WebSocket API Source: https://context7.com/ompugao/patto/llms.txt Provides real-time HTML rendering of Patto notes via a WebSocket connection, including file updates and link data. ```APIDOC ## Preview Server and WebSocket API ### Description Starts a preview server that renders Patto notes to HTML and provides real-time updates and data via WebSocket. ### Method `patto-preview` (Command-line utility) and WebSocket communication ### Endpoint - Preview Server: `http://localhost:3000` (default) - WebSocket: `ws://localhost:3000/ws` (default) ### Parameters #### Command Line Arguments - `--port` (number) - Optional - Specifies the port for the preview server. Default is 3000. #### WebSocket Message Types - `SelectFile` (Object): Request to render a specific file. - `data` (Object) - `path` (string) - Required - The path to the Patto note file. ### Request Example #### Starting the Server ```bash patto-preview --port 3000 ``` #### Connecting to WebSocket and Requesting a File ```javascript const ws = new WebSocket('ws://localhost:3000/ws'); ws.onmessage = (event) => { const message = JSON.parse(event.data); switch (message.type) { case 'FileList': // Initial file list with metadata console.log(message.data.files); console.log(message.data.metadata); break; case 'FileChanged': // File content updated document.getElementById('preview').innerHTML = message.data.html; break; case 'BackLinksData': // Backlinks for current note renderBacklinks(message.data.back_links); break; case 'TwoHopLinksData': // Two-hop links for network visualization renderNetworkGraph(message.data.two_hop_links); break; } }; // Request specific file ws.send(JSON.stringify({ type: 'SelectFile', data: { path: 'my-note.pn' } })); ``` ### Response #### Success Response (WebSocket Messages) - `FileList`: Provides an initial list of files and their metadata. - `FileChanged`: Contains the updated HTML content for a file. - `BackLinksData`: Returns backlink information for the current note. - `TwoHopLinksData`: Returns two-hop link data for network visualization. #### Response Example (FileChanged) ```json { "type": "FileChanged", "data": { "html": "

Rendered HTML Content

" } } ``` ``` -------------------------------- ### Connect to Patto Preview WebSocket Source: https://context7.com/ompugao/patto/llms.txt JavaScript code to establish a WebSocket connection to the Patto preview server. It handles incoming messages for file updates, backlinks, and network graph data, and demonstrates how to send a request to view a specific file. ```javascript const ws = new WebSocket('ws://localhost:3000/ws'); ws.onmessage = (event) => { const message = JSON.parse(event.data); switch (message.type) { case 'FileList': // Initial file list with metadata console.log(message.data.files); console.log(message.data.metadata); break; case 'FileChanged': // File content updated document.getElementById('preview').innerHTML = message.data.html; break; case 'BackLinksData': // Backlinks for current note renderBacklinks(message.data.back_links); // Assuming renderBacklinks function exists break; case 'TwoHopLinksData': // Two-hop links for network visualization renderNetworkGraph(message.data.two_hop_links); // Assuming renderNetworkGraph function exists break; default: console.log('Received unknown message type:', message.type); } }; ws.onerror = (error) => { console.error('WebSocket Error:', error); }; ws.onopen = () => { console.log('WebSocket connection established.'); // Request specific file content after connection is open ws.send(JSON.stringify({ type: 'SelectFile', data: { path: 'my-note.pn' } })); }; ws.onclose = () => { console.log('WebSocket connection closed.'); }; ``` -------------------------------- ### TypeScript VSCode Extension Command Execution Source: https://context7.com/ompugao/patto/llms.txt Demonstrates how to execute VSCode extension commands programmatically using TypeScript. This allows for integration of Patto's features directly into the VSCode environment, such as triggering tasks, opening previews, and scanning the workspace. ```typescript import * as vscode from 'vscode'; // Aggregate tasks and show in sidebar await vscode.commands.executeCommand('patto.tasks'); // Open preview panel await vscode.commands.executeCommand('patto.openPreview'); // Show two-hop links for network exploration await vscode.commands.executeCommand('patto.twoHopLinks'); // Trigger workspace rescan await vscode.commands.executeCommand('patto.scanWorkspace'); ``` -------------------------------- ### Task Management and Aggregation API Source: https://context7.com/ompugao/patto/llms.txt Defines and aggregates tasks within notes using specific inline syntax and LSP commands. ```APIDOC ## Task Management and Aggregation API ### Description Allows defining tasks within Patto notes using inline syntax and aggregating them across the workspace via LSP commands. ### Method `experimental/aggregate_tasks` (LSP Command) ### Endpoint N/A (LSP command) ### Parameters #### Query Parameters None #### Request Body None ### Request Example ```patto Sample task note Fix authentication bug {@task status=todo due=2025-12-31} Implement dark mode !2025-11-30 abbreviated syntax for todo tasks Completed feature {@task status=done} ``` ### Response #### Success Response (200) Returns a list of aggregated tasks with their locations and details. #### Response Example ```json [ { "location": { "uri": "file:///path/to/note.pn", "range": {...} }, "text": "Fix authentication bug", "due": "2025-12-31T00:00:00Z", "message": "" } ] ``` ``` -------------------------------- ### Neovim Configuration Option for Patto Source: https://github.com/ompugao/patto/blob/master/README.md Details a specific configuration option for the Patto plugin in Neovim, `g:patto_enable_open_browser`. This option controls whether the preview server automatically opens a browser window. ```vim g:patto_enable_open_browser: Set to `0` to disable automatic browser opening for the preview server (default: enabled) ``` -------------------------------- ### Optional: Integrate trouble.nvim for Task Viewing Source: https://github.com/ompugao/patto/blob/master/README.md This snippet shows how to optionally integrate the 'trouble.nvim' plugin to enhance task viewing within Neovim, providing deadline sorting and categorization. ```vim Plug 'folke/trouble.nvim' ``` -------------------------------- ### Usage with (neo)vim - Task Aggregation Command Source: https://github.com/ompugao/patto/blob/master/README.md Explains how to use the `:LspPattoTasks` command in (neo)vim to gather and display tasks from notes within the current workspace. This command integrates with location windows for a better overview. ```vim You will have `:LspPattoTasks` command; that will gather tasks from the notes in your workspace and show them in a location window. ``` -------------------------------- ### VSCode Extension for Patto Task Aggregation Source: https://context7.com/ompugao/patto/llms.txt Shows how a VSCode extension can leverage the Patto LSP server to aggregate tasks. It sends an `ExecuteCommandRequest` and then uses the response to refresh a task provider, likely for display in a tree view. ```typescript import * as vscode from 'vscode'; import { ExecuteCommandRequest, LanguageClient } from 'vscode-languageclient/node'; // Assume 'client' is an initialized LanguageClient instance for the Patto extension // Assume 'tasksProvider' is an instance responsible for managing and refreshing the task list async function refreshPattoTasks(client: LanguageClient, tasksProvider: any) { const response = await client.sendRequest(ExecuteCommandRequest.type, { command: "experimental/aggregate_tasks", arguments: [], }); // Render tasks in tree view tasksProvider.refresh(response); } ``` -------------------------------- ### Patto Note Format for Tasks Source: https://context7.com/ompugao/patto/llms.txt Illustrates the Patto note format for defining and managing tasks. Tasks can be marked with specific keywords and date formats, supporting different statuses like 'todo', 'doing', and 'done'. ```patto Sample task note Fix authentication bug {@task status=todo due=2025-12-31} Implement dark mode !2025-11-30 abbreviated syntax for todo tasks Completed feature {@task status=done} Another note with tasks Review pull request *2025-11-28 asterisk syntax for 'doing' status Update documentation -2025-11-27 dash syntax for 'done' status ``` -------------------------------- ### Aggregate Patto Tasks via LSP Command Source: https://context7.com/ompugao/patto/llms.txt Demonstrates how to request task aggregation from the Patto LSP server using an `ExecuteCommandRequest`. The expected response is a JSON array of tasks with their location, text, due dates, and messages. ```typescript // Aggregate all tasks in workspace via LSP command // Assuming 'client' is an instance of LanguageClient from 'vscode-languageclient' // This code is illustrative and might need adjustments based on the actual LSP client implementation. // The actual command execution would typically be within an async function or method. // Example structure: async function aggregatePattoTasks(client: LanguageClient) { const response = await client.sendRequest(ExecuteCommandRequest.type, { command: "experimental/aggregate_tasks", arguments: [], }); // The response is expected to be an array of task objects: // [ // { // "location": { "uri": "file:///path/to/note.pn", "range": {...} }, // "text": "Fix authentication bug", // "due": "2025-12-31T00:00:00Z", // "message": "" // } // ] console.log(response); return response; } ``` -------------------------------- ### Usage with (neo)vim - 2-Hop Links Command Source: https://github.com/ompugao/patto/blob/master/README.md Describes the `:LspPattoTwoHopLinks` command available in Neovim for viewing 2-hop links related to the current buffer. This feature helps in navigating and understanding note connections. ```vim You will see 2-hop links of the current buffer with `:LspPattoTwoHopLinks` command (only in neovim, currently). ``` -------------------------------- ### Sort Tasks with grep and sort Utilities Source: https://github.com/ompugao/patto/blob/master/README.md This command demonstrates how to sort tasks using command-line utilities like `rg` (ripgrep) and `awk`, extracting due dates and sorting them. It also provides a Vim-integrated version. ```sh rg --vimgrep '.*@task.*todo' . | awk '{match($0, /due=([0-9:\-T]+)/, m); if (RLENGTH>0) print m[1], $0; else print "9999-99-99", $0}' |sort |cut -d' ' -f2- # or, in vim cgetexpr system('rg --vimgrep ".*@task.*todo" . | awk "{match(\$0, /due=([0-9T:\-]+)/, m); if (RLENGTH>0) print m[1], $0; else print \"9999-99-99\", $0}" |sort|cut -d\" \" -f2-')|copen ``` -------------------------------- ### Rust Find All References (Backlinks) for Notes Source: https://context7.com/ompugao/patto/llms.txt Finds all references (backlinks) to a given note within the repository. It utilizes the document graph to iterate through incoming edges, extracting precise location information for each reference. ```rust // Find all references (backlinks) to current note async fn references(&self, params: ReferenceParams) -> Result>> { let uri = params.text_document_position.text_document.uri; let graph = repo.document_graph.lock().unwrap(); let node = graph.get(&uri)?; let mut references = Vec::new(); // Iterate through incoming edges (backlinks) for edge in node.iter_in() { let source_uri = edge.source().key(); let edge_data = edge.value(); // Each edge contains precise location information for link_loc in &edge_data.locations { references.push(Location::new( source_uri.clone(), Range::new( Position::new(link_loc.source_line, link_loc.source_col_range.0), Position::new(link_loc.source_line, link_loc.source_col_range.1), ) )); } } Ok(Some(references)) } ``` -------------------------------- ### Patto Note Syntax - Line Properties Source: https://github.com/ompugao/patto/blob/master/README.md Details the 'line property' syntax in Patto Note, which adds properties to individual lines, specifically focusing on 'anchor' and 'task' properties. It also shows abbreviated forms for task statuses and deadlines. ```txt A text in the form of `{@XXX YYY=ZZZ}` is named as `line property` and adds an property to the line (not the whole text). Currently, `anchor` and `task` properties are implemented: * `{@anchor name}`: adds an anchor to the line. abbrev: `#name` * `{@task status=todo due=2024-12-31}`: marks the line as a todo. The due date only supports the ISO 8601 UTC formats (YYYY-MM-DD or YYYY-MM-DDThh:mm). abbrev (symbols might be changed some time): * todo: `!2024-12-31` * doing: `*2024-12-31` * done: `-2024-12-31` ``` -------------------------------- ### Rename Notes and Update References (Rust) Source: https://context7.com/ompugao/patto/llms.txt This Rust code defines an asynchronous function to rename notes within the Patto repository. It identifies all references to the old note name across the workspace, updates them with the new name, and also renames the associated file, ensuring data integrity. ```rust // LSP rename operation updates all links async fn rename(&self, params: RenameParams) -> Result> { let uri = params.text_document_position.text_document.uri; let new_name = params.new_name.trim(); // Validate new name if new_name.is_empty() || new_name.contains('/') || new_name.ends_with(".pn") { return Err(Error::invalid_params("Invalid note name")); } let repo = self.repository.lock().unwrap(); let old_uri = repo.link_to_uri(&old_name, &root_uri); let mut document_changes = Vec::new(); // Find all references and create text edits if let Some(target_node) = repo.document_graph.get(&old_uri) { for edge in target_node.iter_in() { let source_uri = edge.source().key(); let mut edits = Vec::new(); // Update each link location for link_loc in &edge.value().locations { let new_link_text = if let Some(anchor) = &link_loc.target_anchor { format!("[{}#{}]", new_name, anchor) } else { format!("[{}]", new_name) }; edits.push(TextEdit { range: Range::new( Position::new(link_loc.source_line, link_loc.source_col_range.0), Position::new(link_loc.source_line, link_loc.source_col_range.1) ), new_text: new_link_text, }); } document_changes.push(TextDocumentEdit { text_document: source_uri.clone(), edits, }); } } // Add file rename operation let new_uri = repo.link_to_uri(new_name, &root_uri); document_changes.push(ResourceOp::Rename(RenameFile { old_uri, new_uri, options: Some(RenameFileOptions { overwrite: false }), })); Ok(Some(WorkspaceEdit { document_changes: Some(DocumentChanges::Operations(document_changes)), })) } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.