diff --git a/Cargo.lock b/Cargo.lock index 7ee54e852..30f1735e2 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -689,6 +689,7 @@ dependencies = [ "serde", "serde_json", "smol", + "terminfo", "termwiz", "toml", "umask", diff --git a/config/Cargo.toml b/config/Cargo.toml index e462f2602..5a3553cdf 100644 --- a/config/Cargo.toml +++ b/config/Cargo.toml @@ -32,6 +32,7 @@ promise = { path = "../promise" } serde = {version="1.0", features = ["rc", "derive"]} serde_json = "1.0" smol = "1.2" +terminfo = "0.7" termwiz = { path = "../termwiz" } toml = "0.5" umask = { path = "../umask" } diff --git a/config/src/lua.rs b/config/src/lua.rs index 090f221e4..66eda6a73 100644 --- a/config/src/lua.rs +++ b/config/src/lua.rs @@ -7,7 +7,10 @@ use mlua::{Lua, Table, Value}; use serde::*; use smol::prelude::*; use std::path::Path; +use termwiz::cell::{AttributeChange, CellAttributes}; +use termwiz::color::{AnsiColor, ColorAttribute, ColorSpec, RgbColor}; use termwiz::input::Modifiers; +use termwiz::surface::change::Change; /// Set up a lua context for executing some code. /// The path to the directory containing the configuration is @@ -129,6 +132,7 @@ pub fn make_lua_context(config_dir: &Path) -> anyhow::Result { wezterm_mod.set("on", lua.create_function(register_event)?)?; wezterm_mod.set("emit", lua.create_async_function(emit_event)?)?; wezterm_mod.set("sleep_ms", lua.create_async_function(sleep_ms)?)?; + wezterm_mod.set("format", lua.create_function(format)?)?; package.set("path", path_array.join(";"))?; @@ -139,6 +143,110 @@ pub fn make_lua_context(config_dir: &Path) -> anyhow::Result { Ok(lua) } +use termwiz::caps::{Capabilities, ColorLevel, ProbeHints}; +use termwiz::render::terminfo::TerminfoRenderer; + +fn new_wezterm_terminfo_renderer() -> TerminfoRenderer { + let data = include_bytes!("../../termwiz/data/xterm-256color"); + let db = terminfo::Database::from_buffer(&data[..]).unwrap(); + + TerminfoRenderer::new( + Capabilities::new_with_hints( + ProbeHints::new_from_env() + .term(Some("xterm-256color".into())) + .terminfo_db(Some(db)) + .color_level(Some(ColorLevel::TrueColor)) + .colorterm(None) + .colorterm_bce(None) + .term_program(Some("WezTerm".into())) + .term_program_version(Some(crate::wezterm_version().into())), + ) + .expect("cannot fail to make internal Capabilities"), + ) +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] +#[serde(transparent)] +struct ChangeWrap(Change); +impl_lua_conversion!(ChangeWrap); + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] +enum FormatColor { + AnsiColor(AnsiColor), + Color(String), +} + +impl FormatColor { + fn to_attr(self) -> ColorAttribute { + let spec: ColorSpec = self.into(); + let attr: ColorAttribute = spec.into(); + attr + } +} + +impl Into for FormatColor { + fn into(self) -> ColorSpec { + match self { + FormatColor::AnsiColor(c) => c.into(), + FormatColor::Color(s) => { + let rgb = RgbColor::from_named_or_rgb_string(&s) + .unwrap_or(RgbColor::new(0xff, 0xff, 0xff)); + rgb.into() + } + } + } +} + +#[derive(Debug, Serialize, Deserialize, Clone, PartialEq, Eq)] +enum FormatItem { + Foreground(FormatColor), + Background(FormatColor), + Attribute(AttributeChange), + Text(String), +} +impl_lua_conversion!(FormatItem); + +impl Into for FormatItem { + fn into(self) -> Change { + match self { + Self::Attribute(change) => change.into(), + Self::Text(t) => t.into(), + Self::Foreground(c) => AttributeChange::Foreground(c.to_attr()).into(), + Self::Background(c) => AttributeChange::Background(c.to_attr()).into(), + } + } +} + +struct FormatTarget { + target: Vec, +} + +impl std::io::Write for FormatTarget { + fn write(&mut self, buf: &[u8]) -> std::io::Result { + std::io::Write::write(&mut self.target, buf) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + +impl termwiz::render::RenderTty for FormatTarget { + fn get_size_in_cells(&mut self) -> termwiz::Result<(usize, usize)> { + Ok((80, 24)) + } +} + +fn format<'lua>(_: &'lua Lua, items: Vec) -> mlua::Result { + let mut changes: Vec = items.into_iter().map(Into::into).collect(); + changes.push(Change::AllAttributes(CellAttributes::default()).into()); + let mut renderer = new_wezterm_terminfo_renderer(); + let mut target = FormatTarget { target: vec![] }; + renderer + .render_to(&changes, &mut target) + .map_err(|e| mlua::Error::external(e))?; + String::from_utf8(target.target).map_err(|e| mlua::Error::external(e)) +} + async fn sleep_ms<'lua>(_: &'lua Lua, milliseconds: u64) -> mlua::Result<()> { let duration = std::time::Duration::from_millis(milliseconds); smol::Timer::after(duration).await; diff --git a/docs/config/lua/wezterm/format.md b/docs/config/lua/wezterm/format.md new file mode 100644 index 000000000..4db4d34fc --- /dev/null +++ b/docs/config/lua/wezterm/format.md @@ -0,0 +1,47 @@ +# `wezterm.format({})` + +*Since: nightly* + +`wezterm.format` can be used to produce a formatted string +with terminal graphic attributes such as bold, italic and colors. +The resultant string is rendered into a string with wezterm +compatible escape sequences embedded. + +`wezterm.format` accepts a single array argument, where each +element is a `FormatItem`. + +This example logs the text `Hello`, then the date/time, underlined, in purple +text on a blue background to the stderr of the wezterm process: + +```lua +local wezterm = require 'wezterm'; + +local success, date, stderr = wezterm.run_child_process({"date"}); + +wezterm.log_info(wezterm.format({ + {Attribute={Underline="Single"}}, + {Foreground={AnsiColor="Fuschia"}}, + {Background={Color="blue"}}, + {Text="Hello " .. date}, +})) +``` + +Possible values for the `FormatItem` elements are: + +* `{Text="Hello"}` - the text `Hello`. The string can be any string expression. +* `{Attribute={Underline="None"}}` - disable underline +* `{Attribute={Underline="Single"}}` - enable single underline +* `{Attribute={Underline="Double"}}` - enable double underline +* `{Attribute={Underline="Curly"}}` - enable curly underline +* `{Attribute={Underline="Dotted"}}` - enable dotted underline +* `{Attribute={Underline="Dashed"}}` - enable dashed underline +* `{Attribute={Intensity="Normal"}}` - set normal intensity +* `{Attribute={Intensity="Bold"}}` - set bold intensity +* `{Attribute={Intensity="Half"}}` - set half intensity +* `{Attribute={Italic=true}}` - enable italics +* `{Attribute={Italic=false}}` - disable italics +* `{Foreground={AnsiColor="Black"}}` - set foreground color to one of the ansi color palette values (index 0-15) using one of the names `Black`, `Maroon`, `Green`, `Olive`, `Navy`, `Purple`, `Teal`, `Silver`, `Grey`, `Red`, `Lime`, `Yellow`, `Blue`, `Fuschia`, `Aqua` or `White`. +* `{Foreground={Color="yellow"}}` - set foreground color to a named color or rgb value like `#ffffff`. +* `{Background={AnsiColor="Black"}}` - set the background color to an ansi color as per `Foreground` above. +* `{Background={Color="blue"}}` - set the background color to a named color or rgb value as per `Foreground` above. + diff --git a/termwiz/src/color.rs b/termwiz/src/color.rs index 73312beb1..8616cfe1c 100644 --- a/termwiz/src/color.rs +++ b/termwiz/src/color.rs @@ -7,7 +7,8 @@ use num_derive::*; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use std::collections::HashMap; -#[derive(Debug, Clone, Copy, FromPrimitive)] +#[derive(Debug, Clone, Copy, FromPrimitive, PartialEq, Eq)] +#[cfg_attr(feature = "use_serde", derive(Serialize, Deserialize))] #[repr(u8)] /// These correspond to the classic ANSI color indices and are /// used for convenience/readability in code