From a0d411761d353ce74d4a63fc4e8a852821325d47 Mon Sep 17 00:00:00 2001 From: mgpinf Date: Fri, 20 Nov 2026 08:49:20 +0530 Subject: [PATCH] lua: Add `wezterm.url.encode` function to percent encode string (#7131) This is helpful to encode a string to pass it as query string. --- docs/config/lua/wezterm.url/encode.md | 47 +++++++++++++++++++++++++++ lua-api-crates/url-funcs/src/lib.rs | 17 +++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) create mode 100644 docs/config/lua/wezterm.url/encode.md diff --git a/docs/config/lua/wezterm.url/encode.md b/docs/config/lua/wezterm.url/encode.md new file mode 100644 index 000000000..5c5e136c3 --- /dev/null +++ b/docs/config/lua/wezterm.url/encode.md @@ -0,0 +1,47 @@ +# `wezterm.url.encode(string)` + +{{since('nightly')}} + +Returns the percent encoded version of the provided string. + +## Example: opening a line in browser with a search engine + +```lua +local wezterm = require 'wezterm' +local act = wezterm.action + +local config = wezterm.config_builder() + +local SEARCH_ENGINES = { + ['Google'] = 'https://www.google.com/search?q=', + ['Youtube'] = 'https://www.youtube.com/results?search_query=', +} + +local function get_action_to_search(search_engine) + return act.PromptInputLine { + description = 'Search with ' .. search_engine, + action = wezterm.action_callback(function(_win, _pane, line) + if line and #line > 0 then + local final_url = SEARCH_ENGINES[search_engine] + .. wezterm.url.encode(line) + wezterm.open_with(final_url) + end + end), + } +end + +config.keys = { + { + key = 'g', + mods = 'CTRL', + action = get_action_to_search 'Google', + }, + { + key = 'y', + mods = 'CTRL', + action = get_action_to_search 'Youtube', + }, +} + +return config +``` diff --git a/lua-api-crates/url-funcs/src/lib.rs b/lua-api-crates/url-funcs/src/lib.rs index 3e8a9a2d8..bb800c497 100644 --- a/lua-api-crates/url-funcs/src/lib.rs +++ b/lua-api-crates/url-funcs/src/lib.rs @@ -1,7 +1,14 @@ use crate::mlua::UserDataFields; use config::lua::get_or_create_sub_module; use config::lua::mlua::{self, Lua, MetaMethod, UserData, UserDataMethods}; -use percent_encoding::percent_decode; +use percent_encoding::{percent_decode, utf8_percent_encode, AsciiSet, NON_ALPHANUMERIC}; + +/// https://url.spec.whatwg.org/#application-x-www-form-urlencoded-percent-encode-set +const PERCENT_ENCODE_SET: &AsciiSet = &NON_ALPHANUMERIC + .remove(b'*') + .remove(b'-') + .remove(b'.') + .remove(b'_'); pub fn register(lua: &Lua) -> anyhow::Result<()> { let url_mod = get_or_create_sub_module(lua, "url")?; @@ -16,6 +23,14 @@ pub fn register(lua: &Lua) -> anyhow::Result<()> { })?, )?; + url_mod.set( + "encode", + lua.create_function(|_, s: String| { + let encoded = utf8_percent_encode(&s, PERCENT_ENCODE_SET).to_string(); + Ok(encoded) + })?, + )?; + Ok(()) }