### Install lib.wezterm in WezTerm Configuration Source: https://github.com/chrisgve/lib.wezterm/blob/main/README.md This snippet shows how to load the lib.wezterm library into your WezTerm configuration file. It requires the library using `wezterm.plugin.require` and assigns it to a local variable `lib`. ```lua --@type LibWezterm local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") ``` -------------------------------- ### Execute Shell Command and Get Output (Lua) Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Executes a given shell command and captures its standard output. It uses `pcall` for safe execution, returning a boolean indicating success and either the output or an error message. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Execute a command and get output local success, output = lib.file_io.execute("ls -la") if success then print("Directory listing:") print(output) else print("Error: " .. output) end -- Get git branch name local ok, branch = lib.file_io.execute("git branch --show-current") if ok then local current_branch = branch:gsub("%s+", "") -- trim whitespace print("Current branch: " .. current_branch) end -- Cross-platform command execution local env = lib.env local cmd = env.is_windows and "dir" or "ls" local success, listing = lib.file_io.execute(cmd) ``` -------------------------------- ### Get Current Working Directory (CWD) from WezTerm Pane Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Retrieves the current working directory of a specified WezTerm pane. Returns an empty string if the CWD cannot be determined. Useful for context-aware tab titles or opening new tabs in the same directory. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Display current directory in tab title wezterm.on("format-tab-title", function(tab) local pane = tab.active_pane local cwd = lib.wezterm.get_cwd(pane) if cwd ~= "" then -- Extract just the directory name local dir_name = cwd:match("([^/\\]+)$") or cwd return " " .. dir_name .. " " end return " Terminal " end) -- Use CWD for context-aware behavior wezterm.on("open-new-tab", function(window, pane) local current_cwd = lib.wezterm.get_cwd(pane) if current_cwd ~= "" then -- Open new tab in same directory window:perform_action( wezterm.action.SpawnCommandInNewTab({ cwd = current_cwd }), pane ) end end) ``` -------------------------------- ### Initialize lib.wezterm Plugin Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Demonstrates how to import and initialize the lib.wezterm library within a wezterm.lua configuration file to access its various utility modules. ```lua local wezterm = require("wezterm") ---@type LibWezterm local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local string_utils = lib.string local file_io = lib.file_io local table_utils = lib.table local env = lib.env local wez_utils = lib.wezterm local Logger = lib.logger ``` -------------------------------- ### Detect platform environment with lib.env Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Provides boolean flags to identify the operating system (Windows or macOS) and retrieve the system-specific path separator and home directory. These utilities ensure cross-platform compatibility for file system operations and configuration paths. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Platform detection if lib.env.is_windows then print("Running on Windows") elseif lib.env.is_mac then print("Running on macOS") end -- Path utilities local sep = lib.env.separator local home = lib.env.home local config_path = home .. sep .. ".config" .. sep .. "wezterm" ``` -------------------------------- ### Use lib.wezterm String Hashing Functionality Source: https://github.com/chrisgve/lib.wezterm/blob/main/README.md Demonstrates how to use the string hashing utility from lib.wezterm. It shows both regular and sugar syntax for calling the `hash` function, which computes a DJB2 hash from a string. ```lua -- Example: Using the hash function (regular syntax) local key = lib.string.hash("my-string") -- Example: Using the hash function (sugar syntax) local hash = "test":hash() ``` -------------------------------- ### Ensure Folder Exists (Lua) Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Creates a directory at the specified path if it does not already exist. It employs platform-specific commands (`mkdir -p` or `mkdir /p`) for cross-platform compatibility. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Create a cache directory local cache_path = lib.env.home .. "/.cache/my-plugin" local success, signal = lib.file_io.ensure_folder_exists(cache_path) if success then print("Cache directory ready: " .. cache_path) else print("Failed to create directory, signal: " .. tostring(signal)) end -- Create nested directory structure local data_path = lib.env.home .. "/.local/share/wezterm/my-plugin/data" lib.file_io.ensure_folder_exists(data_path) ``` -------------------------------- ### Run lib.wezterm Local Tests Source: https://github.com/chrisgve/lib.wezterm/blob/main/README.md This command navigates to the lib.wezterm directory and executes the local test script. It's used to verify the library's functionality after making changes or for general testing. ```bash cd lib.wezterm ./tests/run_local.sh ``` -------------------------------- ### Create and Configure Logger Instance in WezTerm Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Initializes a new logger instance with options for a custom prefix and debug level control. Supports `debug`, `info`, `warn`, and `error` log levels for consistent logging within WezTerm plugins. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Create a logger for your plugin local logger = lib.logger.new({ prefix = "[my-plugin]", debug_enabled = false }) -- Log at different levels logger:info("Plugin initialized successfully") logger:warn("Configuration file not found, using defaults") logger:error("Failed to connect to service") logger:debug("This won't appear unless debug is enabled") -- Enable debug mode for troubleshooting logger:enable_debug() logger:debug("Now this debug message will appear") -- Chain configuration local dev_logger = lib.logger.new({}) :set_prefix("[dev-plugin]") :enable_debug() dev_logger:debug("Development logging enabled") ``` -------------------------------- ### Use lib.wezterm WezTerm Utilities for Window Dimensions Source: https://github.com/chrisgve/lib.wezterm/blob/main/README.md Shows how to retrieve the current window width using the `get_current_window_width` function from lib.wezterm's `wezterm` module. This is useful for UI adjustments based on screen size. ```lua -- Example: Get current window width local width = lib.wezterm.get_current_window_width() ``` -------------------------------- ### Retrieve pane process information with lib.wezterm Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Inspects the process running within a specific pane to extract details like the process name, arguments, PID, and current working directory. Supports an optional shell list to identify if the running process is a shell. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Get process info with custom shell detection local custom_shells = {"bash", "zsh", "fish", "powershell", "pwsh"} local info = lib.wezterm.get_pane_process(pane, custom_shells) if info.is_shell then wezterm.log_info("Shell detected: " .. info.name) else wezterm.log_info("Program: " .. info.name .. " in " .. info.cwd) end ``` -------------------------------- ### Use lib.wezterm File I/O for Reading Files Source: https://github.com/chrisgve/lib.wezterm/blob/main/README.md Illustrates reading the content of a file using the `read_file` function from lib.wezterm's `file_io` module. It returns a success status and the file content, allowing for error handling. ```lua -- Example: Reading a file local success, content = lib.file_io.read_file("/path/to/file") if success then -- Use content end ``` -------------------------------- ### Perform deep and shallow table copies Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Provides utilities for duplicating tables. deepcopy recursively copies all nested tables to ensure complete isolation, while shallowcopy only duplicates top-level keys, maintaining references for nested objects. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Deep copy a nested configuration table local original_config = { font = { family = "JetBrains Mono", size = 14, features = {"calt", "liga"} }, colors = { foreground = "#ffffff", background = "#1e1e1e" } } local config_copy = lib.table.deepcopy(original_config) config_copy.font.size = 16 -- Shallow copy for simple tables local simple_config = { timeout = 5000, retries = 3, enabled = true } local copy = lib.table.shallowcopy(simple_config) copy.timeout = 10000 ``` -------------------------------- ### Generic Logging Method with Dynamic Level Selection Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Provides a generic `log` method for the logger module that accepts a log level as a parameter. This allows for dynamic selection of log levels based on runtime conditions or severity. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local logger = lib.logger.new({ prefix = "[app]", debug_enabled = true }) -- Dynamic logging based on conditions local function log_operation(success, message) local level = success and "info" or "error" logger:log(level, message) end log_operation(true, "Operation completed") -- Logs as INFO log_operation(false, "Operation failed") -- Logs as ERROR -- Log at varying levels based on severity local function handle_event(severity, event_data) local level_map = { [1] = "debug", [2] = "info", [3] = "warn", [4] = "error" } logger:log(level_map[severity] or "info", "Event:", event_data) end ``` -------------------------------- ### Write String to File (Lua) Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Writes a given string to a specified file, creating the file if it doesn't exist or overwriting it if it does. This function ensures safe file handling, including proper flushing and closing, and returns a success status along with any error message. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Write configuration to a file local config = [[ { "theme": "dark", "font_size": 14, "tab_bar_at_bottom": true } ]] local config_path = lib.env.home .. "/.config/my-plugin/settings.json" -- Ensure directory exists first lib.file_io.ensure_folder_exists(lib.env.home .. "/.config/my-plugin") local success, err = lib.file_io.write_file(config_path, config) if success then print("Configuration saved to: " .. config_path) else print("Failed to save config: " .. err) end -- Write log data local log_entry = os.date("%Y-%m-%d %H:%M:%S") .. " - Plugin initialized\n" lib.file_io.write_file("/tmp/my-plugin.log", log_entry) ``` -------------------------------- ### Read file contents with lib.file_io.read_file Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Reads the entire contents of a specified file path. Returns a success boolean and the file content or an error message, facilitating safe file access in Wezterm plugins. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Read a configuration file local config_path = lib.env.home .. "/.config/my-plugin/settings.json" local success, content = lib.file_io.read_file(config_path) if success then local wezterm = require("wezterm") local config = wezterm.json_parse(content) print("Theme: " .. config.theme) print("Font size: " .. config.font_size) else print("Could not read config: " .. content) end -- Read and process a data file local data_file = "/tmp/plugin-data.txt" local ok, data = lib.file_io.read_file(data_file) if ok and data then for line in data:gmatch("[^\r\n]+") do print("Line: " .. line) end end ``` -------------------------------- ### Capture Scrollback Buffer from WezTerm Pane Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Captures the scrollback buffer from a WezTerm pane. An optional `max_lines` argument can limit the capture to the most recent lines, improving performance for large buffers. The captured content is returned as a string. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Capture recent terminal output wezterm.on("capture-output", function(window, pane) -- Capture last 100 lines local recent_output = lib.wezterm.capture_scrollback(pane, 100) if recent_output then -- Save to file for analysis local timestamp = os.date("%Y%m%d_%H%M%S") local filename = "/tmp/terminal_capture_" .. timestamp .. ".txt" lib.file_io.write_file(filename, recent_output) wezterm.log_info("Output saved to: " .. filename) end end) -- Capture entire scrollback wezterm.on("save-full-history", function(window, pane) local full_history = lib.wezterm.capture_scrollback(pane) if full_history then local line_count = select(2, full_history:gsub("\n", "\n")) wezterm.log_info("Captured " .. line_count .. " lines of history") else wezterm.log_warn("Failed to capture scrollback") end end) ``` -------------------------------- ### Generate Hash from Array Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Creates a unique hash from an array of values by concatenating them with commas and applying the DJB2 algorithm. Ideal for generating compound cache keys. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local items = {"window", "pane", "tab", "123"} local hash = lib.string.array_hash(items) print(hash) local context = {"user", "session", tostring(os.time())} local session_key = lib.string.array_hash(context) ``` -------------------------------- ### Normalize Path Separators (Lua) Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Converts all backslashes to forward slashes in a given path string, ensuring cross-platform compatibility. This is useful for standardizing path formats regardless of the operating system. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Normalize Windows-style paths local windows_path = "C:\\Users\\name\\Documents\\file.txt" local normalized = lib.string.norm_path(windows_path) print(normalized) -- Output: "C:/Users/name/Documents/file.txt" -- Works with mixed separators local mixed_path = "path\\to/some\\file" local clean_path = lib.string.norm_path(mixed_path) print(clean_path) -- Output: "path/to/some/file" ``` -------------------------------- ### Merge tables with lib.table.tbl_deep_extend Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Merges multiple tables with configurable conflict resolution behaviors: 'error' (raise error on conflict), 'keep' (preserve first value), or 'force' (override with last value). ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local defaults = { font_size = 12, window = { padding = { left = 10 } } } local user_config = { font_size = 14, window = { padding = { left = 20 } } } -- Merge using "force" behavior local merged = lib.table.tbl_deep_extend("force", defaults, user_config) -- Using "error" to catch conflicts local success, result = pcall(function() return lib.table.tbl_deep_extend("error", {a=1}, {a=2}) end) ``` -------------------------------- ### Compute String Hash with DJB2 Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Computes a non-cryptographic hash of a string using the DJB2 algorithm. Returns an 8-character hexadecimal string, useful for cache keys. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local hash = lib.string.hash("my-unique-key") print(hash) local config_hash = lib.string.hash("config:" .. os.date("%Y-%m-%d")) local cache_filename = "cache_" .. config_hash .. ".json" ``` -------------------------------- ### Analyze pane orientation with lib.wezterm Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Determines if two given panes are adjacent and identifies their split orientation. Returns a boolean adjacency status and a string representing the orientation (horizontal, vertical, or unknown). ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local is_adjacent, orientation = lib.wezterm.get_panes_orientation(pane1, pane2) if is_adjacent then wezterm.log_info("Orientation: " .. orientation) end ``` -------------------------------- ### Decode WezTerm Encoded Directories (Lua) Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Reverses WezTerm's custom encoding for directory names, converting special character representations (like 'sZs' for '/') back to their original characters. This is essential for reconstructing original URLs or paths from WezTerm's internal representations. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Decode a WezTerm-encoded plugin directory name local encoded = "httpssZsssZsgithubsDscomsZsusersZsplugin" local decoded = lib.string.decode_wezterm_dir(encoded) print(decoded) -- Output: "https://github.com/user/plugin" -- Useful for getting original URLs from plugin cache directories local plugin_dir = "httpsZscolon/githubsDscom" local original = lib.string.decode_wezterm_dir(plugin_dir) ``` -------------------------------- ### Extract Basename from Path (Lua) Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Extracts the filename without its extension from a given file path. It identifies the portion of the string between the last directory separator and the file extension. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") -- Get basename from a full file path local file_path = "/home/user/documents/report.pdf" local basename = lib.string.basename(file_path) print(basename) -- Output: "report" -- Works with Windows paths too local windows_file = "C:\\Projects\\app\\main.lua" local name = lib.string.basename(windows_file) print(name) -- Output: "main" ``` -------------------------------- ### Replace Center of String Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Replaces the middle portion of a string with a specified padding string. Useful for truncating long paths or titles for UI display. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local long_path = "/home/user/very/long/path/to/file.txt" local truncated = lib.string.replace_center(long_path, 10, "...") print(truncated) local title = "My Very Long Window Title That Needs Shortening" local short_title = lib.string.replace_center(title, 20, "...") ``` -------------------------------- ### Calculate UTF-8 String Length Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Returns the character count of a UTF-8 encoded string, correctly handling multi-byte characters like emojis and non-Latin scripts. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local emoji_text = "Hello ๐Ÿ‘‹ World ๐ŸŒ" local char_count = lib.string.utf8len(emoji_text) print(char_count) local japanese = "ใ“ใ‚“ใซใกใฏ" print(#japanese) print(lib.string.utf8len(japanese)) ``` -------------------------------- ### Remove ANSI Escape Sequences Source: https://context7.com/chrisgve/lib.wezterm/llms.txt Strips ANSI formatting escape sequences from strings. This is useful for cleaning terminal output containing color codes for plain text processing. ```lua local lib = wezterm.plugin.require("https://github.com/chrisgve/lib.wezterm") local colored_text = "\27[31mError:\27[0m Something went wrong" local clean_text = lib.string.strip_format_esc_seq(colored_text) print(clean_text) local terminal_output = "\27[1;32mSuccess\27[0m: Build completed" local log_message = lib.string.strip_format_esc_seq(terminal_output) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.