lua: Add wezterm.url.encode function to percent encode string (#7131)
This is helpful to encode a string to pass it as query string.
This commit is contained in:
1 parent
cca5700f38
commit
a0d411761d
2 files changed
+63
-1
No files matched your search
@@ -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
|
||||
```
|
||||
@@ -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(())
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user