### Manage Neovim Key Mappings in Rust Source: https://context7.com/daa84/neovim-lib/llms.txt Demonstrates creating, retrieving, and deleting key mappings in Neovim using Rust. Includes examples for global and buffer-local mappings. ```rust use neovim_lib::{Neovim, NeovimApi, Session, Value}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Create a global keymap // mode: "n" = normal, "i" = insert, "v" = visual, etc. let opts: Vec<(Value, Value)> = vec![ (Value::from("noremap"), Value::from(true)), (Value::from("silent"), Value::from(true)), (Value::from("desc"), Value::from("My custom mapping")), ]; nvim.set_keymap("n", "h", ":echo 'Hello!'", opts.clone())?; nvim.set_keymap("n", "w", ":write", opts)?; // Get all normal mode mappings let mappings = nvim.get_keymap("n")?; for mapping in mappings { println!("Mapping: {:?}", mapping); } // Delete a keymap nvim.del_keymap("n", "h")?; // Buffer-local keymap let buf = nvim.get_current_buf()?; buf.set_keymap( &mut nvim, "n", "q", ":bdelete", vec![(Value::from("silent"), Value::from(true))], )?; Ok(()) } ``` -------------------------------- ### Start Event Loop with Channel Receiver Source: https://context7.com/daa84/neovim-lib/llms.txt Starts the Neovim event loop and returns a channel receiver for asynchronous processing of notifications. Useful for reactive plugins. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; use std::thread; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; // Start event loop with channel receiver let receiver = session.start_event_loop_channel(); let mut nvim = Neovim::new(session); // Subscribe to buffer change events nvim.subscribe("BufEnter")?; nvim.command("autocmd BufEnter * call rpcnotify(1, 'BufEnter', expand('%'))")?; // Process incoming notifications in a separate thread thread::spawn(move || { loop { match receiver.recv() { Ok((event_name, args)) => { println!("Event: {} with args: {:?}", event_name, args); } Err(_) => break, } } }); // Keep main thread alive thread::sleep(std::time::Duration::from_secs(60)); Ok(()) } ``` -------------------------------- ### Connect to Neovim via TCP Source: https://context7.com/daa84/neovim-lib/llms.txt Use `Session::new_tcp` to connect to a Neovim instance listening on a TCP address. Ensure Neovim is started with `--listen` on the specified address. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { // Connect to Neovim listening on TCP port // Start nvim with: nvim --listen 127.0.0.1:6666 let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Execute a command to verify connection nvim.command("echo 'Connected via TCP!'")?; Ok(()) } ``` -------------------------------- ### Manage Global Variables and Options in Neovim with Rust Source: https://context7.com/daa84/neovim-lib/llms.txt Illustrates how to get, set, and delete global variables (g:) and Vim variables (v:), as well as get and set Neovim options using Rust. ```rust use neovim_lib::{Neovim, NeovimApi, Session, Value}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Set global variables nvim.set_var("my_plugin_version", Value::from("1.0.0"))?; nvim.set_var("my_plugin_config", Value::Map(vec![ (Value::from("enabled"), Value::from(true)), (Value::from("debug"), Value::from(false)), ]))?; // Get global variables let version = nvim.get_var("my_plugin_version")?; println!("Plugin version: {:?}", version); // Access vim variables (v: namespace) let vim_version = nvim.get_vvar("version")?; println!("Vim version: {:?}", vim_version); // Delete variable nvim.del_var("my_plugin_version")?; // Get and set global options let tabstop = nvim.get_option("tabstop")?; println!("Current tabstop: {:?}", tabstop); nvim.set_option("tabstop", Value::from(4))?; nvim.set_option("expandtab", Value::from(true))?; nvim.set_option("shiftwidth", Value::from(4))?; Ok(()) } ``` -------------------------------- ### Connect to Neovim via Unix Socket Source: https://context7.com/daa84/neovim-lib/llms.txt Use `Session::new_unix_socket` for local inter-process communication on Unix-like systems. Ensure Neovim is started with `--listen` on the specified socket path. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { // Connect to Neovim via Unix socket // Start nvim with: nvim --listen /tmp/nvim.sock let mut session = Session::new_unix_socket("/tmp/nvim.sock")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Verify connection let version = nvim.command_output("echo v:version")?; println!("Neovim version: {}", version); Ok(()) } ``` -------------------------------- ### Set and Get Buffer Variables and Options Source: https://context7.com/daa84/neovim-lib/llms.txt Use this to customize buffer-specific behavior by setting and retrieving local variables and options. Ensure the Neovim session is established before calling these methods. ```rust use neovim_lib::{Neovim, NeovimApi, Session, Value}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); let buf = nvim.get_current_buf()?; // Set a buffer-local variable buf.set_var(&mut nvim, "my_plugin_enabled", Value::from(true))?; buf.set_var(&mut nvim, "my_plugin_config", Value::from("custom_value"))?; // Read buffer variable let enabled = buf.get_var(&mut nvim, "my_plugin_enabled")?; println!("Plugin enabled: {:?}", enabled); // Set buffer options buf.set_option(&mut nvim, "modifiable", Value::from(false))?; buf.set_option(&mut nvim, "buftype", Value::from("nofile"))?; // Read buffer option let filetype = buf.get_option(&mut nvim, "filetype")?; println!("Filetype: {:?}", filetype); // Get buffer info let name = buf.get_name(&mut nvim)?; let line_count = buf.line_count(&mut nvim)?; println!("Buffer '{}' has {} lines", name, line_count); Ok(()) } ``` -------------------------------- ### start_event_loop_channel - Receive Notifications via Channel Source: https://context7.com/daa84/neovim-lib/llms.txt Starts the event loop and returns a channel receiver for processing Neovim notifications asynchronously. Essential for building reactive plugins that respond to editor events. ```APIDOC ## start_event_loop_channel ### Description Starts the event loop and returns a channel receiver for processing Neovim notifications asynchronously. Essential for building reactive plugins that respond to editor events. ### Method Not applicable (function call within Rust code) ### Endpoint Not applicable (function call within Rust code) ### Parameters None ### Request Example ```rust use neovim_lib::{Neovim, NeovimApi, Session}; use std::thread; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; // Start event loop with channel receiver let receiver = session.start_event_loop_channel(); let mut nvim = Neovim::new(session); // Subscribe to buffer change events nvim.subscribe("BufEnter")?; nvim.command("autocmd BufEnter * call rpcnotify(1, 'BufEnter', expand('%'))")?; // Process incoming notifications in a separate thread thread::spawn(move || { loop { match receiver.recv() { Ok((event_name, args)) => { println!("Event: {} with args: {:?}", event_name, args); } Err(_) => break, } } }); // Keep main thread alive thread::sleep(std::time::Duration::from_secs(60)); Ok(()) } ``` ### Response #### Success Response (200) Returns a channel receiver (`std::sync::mpsc::Receiver`) that yields tuples of `(event_name: String, args: Vec)`. #### Response Example ``` // Example output from receiver.recv(): // Event: BufEnter with args: ["/path/to/file.txt"] ``` ``` -------------------------------- ### Global Variables and Options Source: https://context7.com/daa84/neovim-lib/llms.txt APIs for getting, setting, and deleting global variables (g:) and accessing/modifying Neovim options. ```APIDOC ## Global Variables and Options ### get_var / set_var / del_var #### Description Manage global variables (prefixed with `g:` in Neovim). These functions allow you to read, write, and remove variables from the global scope. #### Methods - `set_var(name: &str, value: Value) -> Result<()>` - `get_var(name: &str) -> Result` - `del_var(name: &str) -> Result<()>` #### Parameters - **name** (string) - Required - The name of the global variable (without the `g:` prefix). - **value** (Value) - Required for `set_var` - The value to set for the variable. Can be various Neovim `Value` types (string, integer, map, etc.). #### Request Example (set_var) ```rust vim.set_var("my_plugin_version", Value::from("1.0.0"))?; vim.set_var("my_plugin_config", Value::Map(vec![ (Value::from("enabled"), Value::from(true)), (Value::from("debug"), Value::from(false)), ]))?; ``` #### Response Example (get_var) ```rust let version = nvim.get_var("my_plugin_version")?; println!("Plugin version: {:?}", version); ``` ### get_vvar #### Description Retrieve the value of a Vim internal variable (prefixed with `v:`). #### Method - `get_vvar(name: &str) -> Result` #### Parameters - **name** (string) - Required - The name of the v-variable (e.g., `"version"`). #### Response Example ```rust let vim_version = nvim.get_vvar("version")?; println!("Vim version: {:?}", vim_version); ``` ### get_option / set_option #### Description Access and modify Neovim runtime options. #### Methods - `get_option(name: &str) -> Result` - `set_option(name: &str, value: Value) -> Result<()>` #### Parameters - **name** (string) - Required - The name of the option (e.g., `"tabstop"`). - **value** (Value) - Required for `set_option` - The value to set for the option. #### Request Example (set_option) ```rust vim.set_option("tabstop", Value::from(4))?; vim.set_option("expandtab", Value::from(true))?; vim.set_option("shiftwidth", Value::from(4))?; ``` #### Response Example (get_option) ```rust let tabstop = nvim.get_option("tabstop")?; println!("Current tabstop: {:?}", tabstop); ``` ``` -------------------------------- ### Expression Evaluation API Source: https://context7.com/daa84/neovim-lib/llms.txt Evaluate Vimscript or Lua expressions and get results back in Rust. ```APIDOC ## eval / execute_lua - Evaluate Expressions ### Description Evaluate Vimscript or Lua expressions and get results back in Rust. ### Method POST ### Endpoint /api/eval ### Parameters #### Request Body - **expression** (string) - Required - The Vimscript or Lua expression to evaluate. - **arguments** (array) - Optional - Arguments to pass to the Lua function. ### Request Example ```json { "expression": "1 + 2 * 3" } ``` ### Response #### Success Response (200) - **result** (any) - The result of the evaluated expression. #### Response Example ```json { "result": 7 } ``` ``` -------------------------------- ### Evaluate Vimscript and Lua Expressions Source: https://context7.com/daa84/neovim-lib/llms.txt Evaluate Vimscript or Lua expressions and get results back in Rust. Supports basic arithmetic, function calls, and checking for plugin existence. Can execute Lua code with or without arguments. ```rust use neovim_lib::{Neovim, NeovimApi, Session, Value}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Evaluate Vimscript expression let result = nvim.eval("1 + 2 * 3")?; println!("Math result: {:?}", result); let cwd = nvim.eval("getcwd()")?; println!("Current directory: {:?}", cwd); // Check if plugin exists let has_plugin = nvim.eval("exists(':Telescope')")?; println!("Has Telescope: {:?}", has_plugin); // Execute Lua code let lua_result = nvim.execute_lua( "return vim.api.nvim_get_current_buf()", vec![], )?; println!("Current buffer (from Lua): {:?}", lua_result); // Execute Lua with arguments let sum = nvim.execute_lua( "local a, b = ...; return a + b", vec![Value::from(10), Value::from(20)], )?; println!("Lua sum: {:?}", sum); // Call Vim function let result = nvim.call_function("strlen", vec![Value::from("Hello")])?; println!("String length: {:?}", result); Ok(()) } ``` -------------------------------- ### Manage Neovim Tabpages in Rust Source: https://context7.com/daa84/neovim-lib/llms.txt Demonstrates creating, listing, and interacting with Neovim tabpages using the neovim-lib library. Ensure a Neovim instance is accessible via TCP. ```rust use neovim_lib::{Neovim, NeovimApi, Session, Value}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Create new tab nvim.command("tabnew")?; // List all tabpages let tabpages = nvim.list_tabpages()?; println!("Number of tabs: {}", tabpages.len()); // Get current tabpage let current_tab = nvim.get_current_tabpage()?; let tab_number = current_tab.get_number(&mut nvim)?; println!("Current tab number: {}", tab_number); // Get windows in tabpage let windows = current_tab.list_wins(&mut nvim)?; println!("Windows in current tab: {}", windows.len()); // Set tabpage variable current_tab.set_var(&mut nvim, "my_tab_data", Value::from("important"))?; // Switch to first tabpage if tabpages.len() > 1 { nvim.set_current_tabpage(&tabpages[0])?; } // Get current window in a tabpage let tab_win = current_tab.get_win(&mut nvim)?; println!("Tab's current window valid: {}", tab_win.is_valid(&mut nvim)?); Ok(()) } ``` -------------------------------- ### Connect to Parent Neovim Process Source: https://context7.com/daa84/neovim-lib/llms.txt Use `Session::new_parent` when the Rust program runs as a Neovim plugin via `jobstart()`. This connects to the parent Neovim process that spawned the program. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { // Connect to the parent Neovim that started this process let mut session = Session::new_parent()?; session.start_event_loop(); let mut nvim = Neovim::new(session); // This code runs inside Neovim as a plugin nvim.command("echom 'Plugin started!'")?; // Get current buffer info let buf = nvim.get_current_buf()?; let name = buf.get_name(&mut nvim)?; nvim.command(&format!("echom 'Current buffer: {}"", name))?; Ok(()) } ``` -------------------------------- ### Create Floating Windows with Custom Content Source: https://context7.com/daa84/neovim-lib/llms.txt Generate scratch buffers and open them as floating windows for popups or overlays. Configure position, size, and appearance using a vector of key-value pairs. ```rust use neovim_lib::{Neovim, NeovimApi, Session, Value}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Create a scratch buffer (unlisted, scratch) let buf = nvim.create_buf(false, true)?; // Add content to the buffer buf.set_lines(&mut nvim, 0, 0, true, vec![ " Floating Window Demo ".to_owned(), "------------------------".to_owned(), " Press 'q' to close ".to_owned(), ])?; // Open a floating window with the buffer // Config options specify position and appearance let config: Vec<(Value, Value)> = vec![ (Value::from("relative"), Value::from("editor")), (Value::from("width"), Value::from(26)), (Value::from("height"), Value::from(3)), (Value::from("row"), Value::from(5)), (Value::from("col"), Value::from(10)), (Value::from("style"), Value::from("minimal")), (Value::from("border"), Value::from("rounded")), ]; let win = nvim.open_win(&buf, true, config)?; // Set window-local options win.set_option(&mut nvim, "winhl", Value::from("Normal:Pmenu"))?; // Map 'q' to close the window nvim.command("nnoremap q :close")?; Ok(()) } ``` -------------------------------- ### Execute Vim Commands Source: https://context7.com/daa84/neovim-lib/llms.txt Execute Ex commands with or without capturing output. Use `command` for execution and `command_output` to capture the result. Supports executing multiple commands. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Execute commands without output nvim.command("set number")?; nvim.command("syntax on")?; nvim.command("colorscheme desert")?; // Execute command and capture output let output = nvim.command_output("echo &filetype")?; println!("Filetype: {}", output); let version = nvim.command_output("version")?; println!("Neovim version info:\n{}", version); // Execute multiple commands nvim.command("new | setlocal buftype=nofile | put ='Hello World'")?; Ok(()) } ``` -------------------------------- ### Async Neovim API Operations in Rust Source: https://context7.com/daa84/neovim-lib/llms.txt Shows how to perform non-blocking operations with the Neovim API using async methods and callbacks. Useful for operations that shouldn't block the UI. ```rust use neovim_lib::{Neovim, NeovimApi, NeovimApiAsync, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Async command without waiting for completion nvim.command_async("sleep 100m | echo 'Done sleeping'").call(); // Async with callback nvim.eval_async("expand('%:p')") .cb(|result| { match result { Ok(path) => println!("Current file path: {:?}", path), Err(e) => eprintln!("Error: {:?}", e), } }) .call(); // Multiple async operations nvim.list_bufs_async() .cb(|result| { if let Ok(bufs) = result { println!("Number of buffers: {}", bufs.len()); } }) .call(); nvim.list_wins_async() .cb(|result| { if let Ok(wins) = result { println!("Number of windows: {}", wins.len()); } }) .call(); // Need to trigger event loop processing for callbacks // Use a sync call to flush nvim.command("echo ''")?; Ok(()) } ``` -------------------------------- ### Command Execution API Source: https://context7.com/daa84/neovim-lib/llms.txt Execute Ex commands with or without capturing output. Fundamental for controlling Neovim behavior. ```APIDOC ## command / command_output - Execute Vim Commands ### Description Execute Ex commands with or without capturing output. Fundamental for controlling Neovim behavior. ### Method POST ### Endpoint /api/command ### Parameters #### Request Body - **command** (string) - Required - The Ex command to execute. - **capture_output** (boolean) - Optional - Whether to capture and return the command output. Defaults to false. ### Request Example ```json { "command": "set number", "capture_output": false } ``` ### Response #### Success Response (200) - **output** (string) - The captured output of the command, if `capture_output` was true. #### Response Example ```json { "output": "syntax on\ncolorscheme desert" } ``` ``` -------------------------------- ### Manage Window Size, Position, and Cursor Source: https://context7.com/daa84/neovim-lib/llms.txt Control window dimensions, cursor placement, and retrieve window layout information. This is useful for dynamic UI adjustments and navigation. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Create a vertical split nvim.command("vsplit")?; // Get all windows let windows = nvim.list_wins()?; println!("Number of windows: {}", windows.len()); // Get current window let win = nvim.get_current_win()?; // Get and set window size let width = win.get_width(&mut nvim)?; let height = win.get_height(&mut nvim)?; println!("Window size: {}x{}", width, height); win.set_width(&mut nvim, 40)?; win.set_height(&mut nvim, 20)?; // Get and set cursor position (1-indexed line, 0-indexed column) let (line, col) = win.get_cursor(&mut nvim)?; println!("Cursor at line {}, column {}", line, col); win.set_cursor(&mut nvim, (5, 10))?; // Get window position in the grid let (row, col) = win.get_position(&mut nvim)?; println!("Window position: row {}, col {}", row, col); // Switch to another window if windows.len() > 1 { nvim.set_current_win(&windows[1])?; } Ok(()) } ``` -------------------------------- ### Spawn Embedded Neovim Instance Source: https://context7.com/daa84/neovim-lib/llms.txt Use `Session::new_child` to spawn an embedded Neovim process and connect via stdin/stdout. This is ideal for plugins managing their own Neovim instance. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { // Spawn a new embedded Neovim instance let mut session = Session::new_child()?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Open a file in the embedded instance nvim.command("edit /tmp/test.txt")?; // Set some content nvim.set_current_line("Hello from embedded Neovim!")?; // Save and quit nvim.command("write")?; nvim.quit_no_save()?; Ok(()) } ``` -------------------------------- ### Attach as External UI Source: https://context7.com/daa84/neovim-lib/llms.txt Register the client as an external UI to receive redraw events. Configure UI options like RGB, linegrid, and popupmenu. Attach with specific dimensions and process redraw events. ```rust use neovim_lib::{Neovim, NeovimApi, Session, UiAttachOptions}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; let receiver = session.start_event_loop_channel(); let mut nvim = Neovim::new(session); // Configure UI options let mut opts = UiAttachOptions::new(); opts.set_rgb(true) .set_linegrid_external(true) .set_popupmenu_external(true) .set_tabline_external(false); // Attach as UI with specific dimensions nvim.ui_attach(80, 24, &opts)?; // Process redraw events std::thread::spawn(move || { for (event, args) in receiver { match event.as_str() { "redraw" => { // Process redraw batch for arg in args { println!("Redraw event: {:?}", arg); } } _ => println!("Event: {} - {:?}", event, args), } } }); // Resize UI nvim.ui_try_resize(120, 40)?; // Keep running std::thread::sleep(std::time::Duration::from_secs(60)); // Detach when done nvim.ui_detach()?; Ok(()) } ``` -------------------------------- ### Input and Keymap Management API Source: https://context7.com/daa84/neovim-lib/llms.txt Send keyboard input to Neovim programmatically for automation and testing. ```APIDOC ## feedkeys / input - Send Keystrokes ### Description Send keyboard input to Neovim programmatically for automation and testing. ### Method POST ### Endpoint /api/input ### Parameters #### Request Body - **keys** (string) - Required - The keys to send to Neovim. - **mode** (string) - Optional - The mode in which to process the keys ('n', 'm', 't'). Defaults to 'n'. - **remap** (boolean) - Optional - Whether to remap keys. Defaults to true. - **replace_termcodes** (boolean) - Optional - Whether to replace terminal codes. Defaults to false. ### Request Example ```json { "keys": "iHello World", "mode": "n", "remap": true } ``` ### Response #### Success Response (200) - **bytes_queued** (integer) - The number of bytes queued for input. #### Response Example ```json { "bytes_queued": 15 } ``` ``` -------------------------------- ### Key Mapping Management Source: https://context7.com/daa84/neovim-lib/llms.txt APIs for creating, modifying, querying, and deleting key mappings in Neovim. ```APIDOC ## set_keymap / get_keymap / del_keymap ### Description Manage key mappings programmatically. This includes creating, updating, querying, and deleting key mappings for different modes. ### Methods - `set_keymap(mode: &str, lhs: &str, rhs: &str, opts: Vec<(Value, Value)>) -> Result<()> - `get_keymap(mode: &str) -> Result> - `del_keymap(mode: &str, lhs: &str) -> Result<()> ### Parameters #### `set_keymap` Parameters - **mode** (string) - Required - The mode for the keymap (e.g., "n" for normal, "i" for insert). - **lhs** (string) - Required - The left-hand side of the keymap (the keys to press). - **rhs** (string) - Required - The right-hand side of the keymap (the command or keys to execute). - **opts** (Vec<(Value, Value)>) - Optional - A vector of key-value pairs for options like `noremap`, `silent`, `desc`. #### `get_keymap` Parameters - **mode** (string) - Required - The mode for which to retrieve key mappings. #### `del_keymap` Parameters - **mode** (string) - Required - The mode of the keymap to delete. - **lhs** (string) - Required - The left-hand side of the keymap to delete. ### Request Example (set_keymap) ```rust let opts: Vec<(Value, Value)> = vec![ (Value::from("noremap"), Value::from(true)), (Value::from("silent"), Value::from(true)), (Value::from("desc"), Value::from("My custom mapping")), ]; vim.set_keymap("n", "h", ":echo 'Hello!'", opts.clone())?; ``` ### Response Example (get_keymap) ```rust // Assuming 'mappings' is the result of nvim.get_keymap("n")? for mapping in mappings { println!("Mapping: {:?}", mapping); } ``` ### Buffer-local Keymaps Keymaps can also be set on a buffer-local level using the `Buf::set_keymap` method. ```rust let buf = nvim.get_current_buf()?; buf.set_keymap( &mut nvim, "n", "q", ":bdelete", vec![(Value::from("silent"), Value::from(true))], )?; ``` ``` -------------------------------- ### Add and Clear Buffer Syntax Highlighting Source: https://context7.com/daa84/neovim-lib/llms.txt Add custom highlighting to buffer regions using highlight groups and namespaces. Namespaces facilitate management and clearing of highlights. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Create a namespace for our highlights let ns_id = nvim.create_namespace("my_plugin_highlights")?; let buf = nvim.get_current_buf()?; // Add highlight to line 0, columns 0-5 (0-indexed) // Use -1 for col_end to highlight to end of line buf.add_highlight(&mut nvim, ns_id, "ErrorMsg", 0, 0, 5)?; buf.add_highlight(&mut nvim, ns_id, "WarningMsg", 1, 0, -1)?; buf.add_highlight(&mut nvim, ns_id, "Search", 2, 10, 20)?; // Later, clear all highlights in the namespace // line_start=0, line_end=-1 clears entire buffer buf.clear_namespace(&mut nvim, ns_id, 0, -1)?; Ok(()) } ``` -------------------------------- ### Buffer::add_highlight / Buffer::clear_namespace - Syntax Highlighting Source: https://context7.com/daa84/neovim-lib/llms.txt Add custom highlighting to buffer regions using highlight groups. Namespaces allow grouping highlights for easy management and clearing. ```APIDOC ## Buffer Operations: add_highlight / clear_namespace ### Description Add custom highlighting to buffer regions using highlight groups. Namespaces allow grouping highlights for easy management and clearing. ### Method `Buffer::add_highlight`, `Buffer::clear_namespace` ### Endpoint Not applicable (method calls on a `Buffer` object) ### Parameters #### Buffer::add_highlight - **nvim** (*Neovim*) - Mutable reference to the Neovim instance. - **ns_id** (*i32*) - The namespace ID to associate the highlight with. - **group_name** (*&str*) - The name of the highlight group (e.g., "ErrorMsg", "WarningMsg"). - **line** (*usize*) - The line number (0-indexed). - **col_start** (*usize*) - The starting column (0-indexed). - **col_end** (*isize*) - The ending column (0-indexed). Use -1 to highlight to the end of the line. #### Buffer::clear_namespace - **nvim** (*Neovim*) - Mutable reference to the Neovim instance. - **ns_id** (*i32*) - The namespace ID to clear highlights from. - **line_start** (*usize*) - The starting line number (0-indexed). Use 0 for the beginning of the buffer. - **line_end** (*isize*) - The ending line number (0-indexed, exclusive). Use -1 for the end of the buffer. ### Request Example ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Create a namespace for our highlights let ns_id = nvim.create_namespace("my_plugin_highlights")?; let buf = nvim.get_current_buf()?; // Add highlight to line 0, columns 0-5 (0-indexed) // Use -1 for col_end to highlight to end of line buf.add_highlight(&mut nvim, ns_id, "ErrorMsg", 0, 0, 5)?; buf.add_highlight(&mut nvim, ns_id, "WarningMsg", 1, 0, -1)?; buf.add_highlight(&mut nvim, ns_id, "Search", 2, 10, 20)?; // Later, clear all highlights in the namespace // line_start=0, line_end=-1 clears entire buffer buf.clear_namespace(&mut nvim, ns_id, 0, -1)?; Ok(()) } ``` ### Response #### Success Response (200) - **Buffer::create_namespace**: `i32` - The ID of the created namespace. - **Buffer::add_highlight**: `()` - Indicates success. - **Buffer::clear_namespace**: `()` - Indicates success. #### Response Example No direct output is shown in the example, but highlights would be applied visually in the Neovim editor. ``` -------------------------------- ### Send Keystrokes to Neovim Source: https://context7.com/daa84/neovim-lib/llms.txt Send keyboard input to Neovim programmatically for automation and testing. `feedkeys` processes keys after the current command, while `input` adds them to the buffer immediately. `replace_termcodes` can be used to escape special keys. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // feedkeys - keys are processed after the current command // mode: "n" = as if typed, "m" = remap keys, "t" = handle as if typed nvim.feedkeys("iHello World", "n", true)?; // input - returns number of bytes queued // Keys are added to input buffer immediately let bytes = nvim.input(":echo 'Hello'")?; println!("Queued {} bytes", bytes); // Replace terminal codes for special keys let escaped = nvim.replace_termcodes("h", true, true, true)?; nvim.feedkeys(&escaped, "n", false)?; Ok(()) } ``` -------------------------------- ### Handle Neovim API Errors in Rust Source: https://context7.com/daa84/neovim-lib/llms.txt Illustrates how to handle `CallError` from Neovim API calls, distinguishing between Neovim-specific errors and generic errors. This is crucial for robust plugin development. ```rust use neovim_lib::{Neovim, NeovimApi, Session, CallError}; fn main() { let result = run_plugin(); if let Err(e) = result { eprintln!("Plugin error: {}", e); } } fn run_plugin() -> Result<(), Box> { let mut session = Session::new_tcp("127.0.0.1:6666")?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Handle specific error types match nvim.command("nonexistent_command") { Ok(()) => println!("Command succeeded"), Err(CallError::NeovimError(code, msg)) => { eprintln!("Neovim error {}: {}", code, msg); } Err(CallError::GenericError(msg)) => { eprintln!("Generic error: {}", msg); } } // Use Result combinators let line = nvim.get_current_line() .map_err(|e| format!("Failed to get line: {}", e))?; // Chain operations with error handling let buf = nvim.get_current_buf()?; let name = buf.get_name(&mut nvim)?; if name.is_empty() { nvim.err_writeln("Warning: Buffer has no name")?; } // Validate before operations if buf.is_valid(&mut nvim)? && buf.is_loaded(&mut nvim)? { let lines = buf.get_lines(&mut nvim, 0, 10, false)?; println!("First 10 lines: {:?}", lines); } Ok(()) } ``` -------------------------------- ### UI Attachment API Source: https://context7.com/daa84/neovim-lib/llms.txt Register the client as an external UI to receive redraw events. This enables building custom Neovim frontends. ```APIDOC ## ui_attach - Register as External UI ### Description Register the client as an external UI to receive redraw events. This enables building custom Neovim frontends. ### Method POST ### Endpoint /api/ui/attach ### Parameters #### Query Parameters - **width** (integer) - Required - The width of the UI. - **height** (integer) - Required - The height of the UI. #### Request Body - **options** (object) - Required - UI attachment options. - **rgb** (boolean) - Optional - Enable RGB color support. - **linegrid_external** (boolean) - Optional - Enable external linegrid. - **popupmenu_external** (boolean) - Optional - Enable external popup menu. - **tabline_external** (boolean) - Optional - Enable external tabline. ### Request Example ```json { "options": { "rgb": true, "linegrid_external": true, "popupmenu_external": true, "tabline_external": false } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates success. #### Response Example ```json { "status": "attached" } ``` ``` -------------------------------- ### Asynchronous Operations Source: https://context7.com/daa84/neovim-lib/llms.txt Perform Neovim API operations asynchronously without blocking the main thread, with optional callbacks. ```APIDOC ## Async API - NeovimApiAsync ### Description Provides non-blocking variants of Neovim API methods. These methods return a future or allow attaching a callback to handle the result asynchronously. ### Methods - `command_async(command: &str) -> CmdAsync` - `eval_async(expr: &str) -> EvalAsync` - `list_bufs_async() -> ListBufsAsync` - `list_wins_async() -> ListWinsAsync` ### Usage Async methods are typically chained with `.call()` to initiate the operation. Callbacks can be attached using `.cb(|result| { ... })`. ### Request Example (command_async) ```rust vim.command_async("sleep 100m | echo 'Done sleeping'").call(); ``` ### Request Example (eval_async with callback) ```rust vim.eval_async("expand('%:p')") .cb(|result| { match result { Ok(path) => println!("Current file path: {:?}", path), Err(e) => eprintln!("Error: {:?}", e), } }) .call(); ``` ### Request Example (multiple async operations) ```rust vim.list_bufs_async() .cb(|result| { if let Ok(bufs) = result { println!("Number of buffers: {}", bufs.len()); } }) .call(); vim.list_wins_async() .cb(|result| { if let Ok(wins) = result { println!("Number of windows: {}", wins.len()); } }) .call(); // Ensure event loop processes callbacks by making a sync call vim.command("echo ''")?; ``` ``` -------------------------------- ### Read and Write Buffer Content with set_lines and get_lines Source: https://context7.com/daa84/neovim-lib/llms.txt Read lines from a buffer or replace buffer content. The strict_indexing parameter controls error handling for out-of-bounds indices. ```rust use neovim_lib::{Neovim, NeovimApi, Session}; fn main() -> Result<(), Box> { let mut session = Session::new_child()?; session.start_event_loop(); let mut nvim = Neovim::new(session); // Get current buffer let buf = nvim.get_current_buf()?; // Set lines in the buffer (0-indexed, end-exclusive) // Replace lines 0-0 (insert at beginning) with new content buf.set_lines(&mut nvim, 0, 0, true, vec![ "Line 1: Hello".to_owned(), "Line 2: World".to_owned(), "Line 3: From Rust!".to_owned(), ])?; // Read lines back (0 to -1 means entire buffer) let lines = buf.get_lines(&mut nvim, 0, -1, false)?; for (i, line) in lines.iter().enumerate() { println!("Line {}: {}", i + 1, line); } // Replace specific line range (lines 1-2, 0-indexed) buf.set_lines(&mut nvim, 1, 2, true, vec![ "Modified Line 2".to_owned(), ])?; nvim.quit_no_save()?; Ok(()) } ```