lua: add wezterm.format function

The intent is to use this to compose text for a configurable tab bar.

refs: https://github.com/wez/wezterm/issues/500
This commit is contained in:
Wez Furlong committed 2021-03-02 09:52:54 -08:00
1 parent 62e14efcb3
commit 565a4c69d5
5 files changed
+159 -1

No files matched your search

Generated
+1
View File
@@ -689,6 +689,7 @@ dependencies = [
"serde",
"serde_json",
"smol",
"terminfo",
"termwiz",
"toml",
"umask",
+1
View File
@@ -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" }
+108
View File
@@ -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<Lua> {
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<Lua> {
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<ColorSpec> 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<Change> 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<u8>,
}
impl std::io::Write for FormatTarget {
fn write(&mut self, buf: &[u8]) -> std::io::Result<usize> {
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<FormatItem>) -> mlua::Result<String> {
let mut changes: Vec<Change> = 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;
+47
View File
@@ -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.
+2 -1
View File
@@ -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